· 6 years ago · Jul 31, 2019, 12:18 PM
1*1) Diffence between session and cookies
2 Cookies
3 A cookie is a bit of data stored by the browser and sent to the server with every request.
4 Cookies are used to identify sessions
5 Cookies can be check in "request header" using enspect element
6 setcookie(cookie_name, cookie_value, [expiry_time], [cookie_path], [domain], [secure], [httponly]);
7 setcookie("user_name", "Guru99", time()+ 60,'/'); // expires after 60 seconds
8
9 Seesion
10 A session is a collection of data stored on the server and associated with a given user (usually via a cookie containing an id code)
11 if session time is not set then, Seesion expire when you cloase browser
12 session used to used to overcome the http stateless behaviour and used data from one page to another page
13 You want the alternative to cookies on browsers that do not support cookies.
14 You are developing an application such as a shopping cart that has to temporary store information with a capacity larger than 4KB
15
16 session_start();
17 $_SESSION['key'] = "Value";
18 print_r($_SESSION);
19 session_destroy();
20
212) abstract class
22 Instance of abstract class can not be created.
23 Abstract classes are the classes in which at least one method is abstract
24 An abstract class can contain abstract as well as non abstract methods.
25 Abstract class cab also have constructor.
26 abstract method can NOT have defination, and its should be extends. And client access its method without creating insatce of same class.
27
28
29
30 abstract class Base {
31 function __construct() {
32 echo "this is abstrct class constructor ";
33 }
34
35 // This is abstract function
36 abstract function printdata();
37 function sayhi(){
38 echo "Hi bro..!";
39 }
40 }
41 class Derived extends base {
42 function __construct() {
43 echo "\n Derived class constructor";
44 }
45 function printdata() {
46 echo "\n Derived class printdata function";
47 }
48 }
49 $b1 = new Derived;
50 $b1->printdata();
51 echo $b1->sayhi();
52
533) inheritance
54 support single and multilevel inharitance. Multiple inharitance achive by interface or trait
55 subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality.
56 Parent class method can be access by parrent::methodname();
57 Call parent construct : parent::__construct();
58
594)trait
60 Traits define the actual implementation of each method within each class, Multiple trait can be use by class.
61 trait can have constructure and its constructor run when we use it.
62
63 trait HelloGeeks {
64 function __construct(){
65 echo "constructing";
66 }
67 public function geeks() {
68 echo 'Hello World!';
69 }
70 }
71
72 trait HelloGeeks2 {
73 public function geeks2() {
74 echo 'Hello World! 2';
75 }
76 }
77
78
79 class Geeksforgeeks{
80 use HelloGeeks;
81 use HelloGeeks2;
82 public function geeks() {
83 echo 'Hello World child!';
84 }
85 }
86
87 $obj = new Geeksforgeeks();
88 $obj->geeks();
89 echo "</br>";
90 $obj->geeks2();
91 echo "</br>";
92
93
945) include & include_once, require and require_once
95 -> include not return error if file does not exits, include_once check file already included or not.
96 -> require retain error if file not exuts, require_once check file already included or not.
97
98
996) PHP operator
100
101 A) Arithmetic Operators
102 + Addition $x + $y Sum the operands
103 – Subtraction $x – $y Differences the operands
104 * Multiplication $x * $y Product of the operands
105 / Division $x / $y Quotient of the operands
106 ** Exponentiation $x ** $y $x raised to the power $y 10**2 = 100
107 % Modulus $x % $y Remainder of the operands 10%2=0
108
109 B) Logical or Relational Operators
110 and Logical AND $x and $y True if both the operands are true else false
111 or Logical OR $x or $y True if either of the operand is true else false
112 && Logical AND $x && $y True if both the operands are true else false
113 || Logical OR $x || $y True if either of the operand is true else false
114 ! Logical NOT !$x True if $x is false
115 xor Logical XOR $x xor $y True if either of the operand is true and false if both are true
116
117 C) Comparison Operators
118 == Equal To $x == $y Returns True if both the operands are equal
119 != Not Equal To $x != $y Returns True if both the operands are not equal
120 <> Not Equal To $x <> $y Returns True if both the operands are unequal
121 === Identical $x === $y Returns True if both the operands are equal and are of the same type
122 !== Not Identical $x == $y Returns True if both the operands are unequal and are of different types
123 < Less Than $x < $y Returns True if $x is less than $y
124 > Greater Than $x > $y Returns True if $x is greater than $y
125 <= Less Than or Equal To $x <= $y Returns True if $x is less than or equal to $y
126 >= Greater Than or Equal To $x >= $y
127
128 D) Conditional or Ternary Operators
129 ?: eg: $var = (condition)? value1 : value2;
130
131 E) Assignment Operators
132 = Assign $x = $y Operand on the left obtains the value of the operand on right
133 += Add then Assign $x += $y Simple Addition same as $x = $x + $y
134 -= Subtract then Assign $x -= $y Simple subtraction same as $x = $x – $y
135 *= Multiply then Assign $x *= $y Simple product same as $x = $x * $y
136 /= Divide then Assign (quotient) $x /= $y Simple division same as $x = $x / $y
137 %= Divide then Assign (remainder) $x %= $y Simple division same as $x = $x % $y
138
139 F) Increment/Decrement Operators
140 ++ Pre-Increment ++$x First increments $x by one, then return $x
141 ++ Post-Increment $x++
142 —- Pre-Decrement –-$x First decrements $x by one, then return $x
143 ++ Post-Decrement $x--
144
145 G) String Operators
146 . Concatenation $x.$y Concatenated $x and $y
147 .= Concatenation and assignment $x.=$y First concatenates then assigns, same as $x = $x.$y
148
149
150*7) Ajax
151 jQuery.ajax({
152 url:"http://xyz.com/add",
153 type:'POST', // "POST", "GET", "PUT"
154 dataType:'html', // (default: Intelligent Guess (xml, json, script, or html)) The type of data that you're expecting back from the server
155 data: '&dom_obt='+obj+'&tour_type='+tourType+'&Dest_dest='+Dest,
156 success:function(data, textStatus){
157 jQuery('#ajaxContainer').html(data);
158 },
159 beforeSend:function(XMLHttpRequest){
160 showLoader('loader');
161 },
162 complete:function(XMLHttpRequest, textStatus){
163 hideLoader('loader');
164 },
165 error:function(XMLHttpRequest, textStatus, errorThrown){
166 jQuery("#ajaxContainer").html('');
167 }
168 });
169
170*8) Curl
171
172 $curlObj = curl_init();
173
174 curl_setopt($curlObj,CURLOPT_URL,$url);
175 curl_setopt($curlObj, CURLOPT_POSTFIELDS, $params);
176 curl_setopt($curlObj, CURLOPT_POST, 1);
177 curl_setopt($curlObj, CURLOPT_HTTPHEADER, $headers);
178
179 curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0); // Skip SSL Verification
180 curl_setopt($curlObj, CURLOPT_SSL_VERIFYHOST, false);
181
182 //curl_setopt($curlObj, CURLOPT_HEADER, 1);
183 //curl_setopt($curlObj, CURLOPT_NOBODY, 1);
184
185 curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
186 curl_setopt($curlObj, CURLINFO_HEADER_OUT, true);
187
188 $output=curl_exec($curlObj);
189 if(curl_errno($curlObj))
190 {
191 echo 'Curl error: ' . curl_error($curlObj);
192 }
193 curl_close($curlObj);
194
1959) PHP database connection
196 $conn = mysql_connect($dbhost, $dbuser, $dbpass);
197 mysql_select_db('TUTORIALS');
198 $sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl';
199 $retval = mysql_query( $sql, $conn );
200
201 if(! $retval ) {
202 die('Could not get data: ' . mysql_error());
203 }
204
205 while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
206 echo "Tutorial ID :{$row['tutorial_id']}";
207 }
208 mysql_close($conn);
209
21010) MYSQL function
211 mysql_connect — Open a connection to a MySQL Server
212
213 mysql_escape_string — Escapes a string for use in a mysql_query
214 mysql_query — Send a MySQL query
215 mysql_affected_rows — Get number of affected rows in previous MySQL operation
216 mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
217
218 mysql_error — Returns the text of the error message from previous MySQL operation
219
220 mysql_close — Close MySQL connection
221
22211) Write to file
223 $fileobj = fopen('filePath', 'filename', 'mode'); / mode r, r+, w,w+, a, a+(write at end)
224 fwrite($fileboj, data) //
225 file_get_contents("my_settings.txt"); // The file_get_contents function is used to read the entire file contents.
226 $line = fgets($fileobj); // The fgets function is used to read php files line by line
227 copy('my_settings.txt', 'my_settings_backup.txt') // The PHP copy function is used to copy files
228 unlink('my_settings_backup.txt') // The unlink function is used to delete the file
229 fclose($fileboj);
230
23112 ) Server
232 * [HTTP_HOST] => ckisteamamber.coxandkings.com
233 [HTTP_CONNECTION] => keep-alive
234 [HTTP_CACHE_CONTROL] => max-age=0
235 [HTTP_UPGRADE_INSECURE_REQUESTS] => 1
236 *[HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36
237 [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
238 [HTTP_X_FIREPHP] => 0.4.4
239 [HTTP_X_FIREPHP_VERSION] => 0.4.4
240 [HTTP_X_WF_MAX_COMBINED_SIZE] => 262144
241 [HTTP_ACCEPT_ENCODING] => gzip, deflate
242 [HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.9
243 *[PATH] => /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
244 [SERVER_SIGNATURE] =>
245 [SERVER_SOFTWARE] => Apache/2.4.6 (Red Hat) OpenSSL/1.0.1e-fips PHP/5.6.31 SVN/1.7.14
246 [SERVER_NAME] => ckisteamamber.coxandkings.com
247 [SERVER_ADDR] => 10.21.32.171
248 [SERVER_PORT] => 80
249 *[REMOTE_ADDR] => 10.21.20.151
250 *[DOCUMENT_ROOT] => /home/ckisapps/ckisapps/development/amber
251 [REQUEST_SCHEME] => http
252 [CONTEXT_PREFIX] =>
253 [CONTEXT_DOCUMENT_ROOT] => /home/ckisapps/ckisapps/development/amber
254 [SERVER_ADMIN] => gurpreet.panesar@coxandkings.com
255 [SCRIPT_FILENAME] => /home/ckisapps/ckisapps/development/amber/dynamic_crm/shekhar/batch/dynamic_crm/amended_booking.php // __FILE__
256 [REMOTE_PORT] => 60327
257 [GATEWAY_INTERFACE] => CGI/1.1
258 [SERVER_PROTOCOL] => HTTP/1.1
259 *[REQUEST_METHOD] => GET
260 [QUERY_STRING] =>
261 *[REQUEST_URI] => /dynamic_crm/shekhar/batch/dynamic_crm/amended_booking.php
262 *[SCRIPT_NAME] => /dynamic_crm/shekhar/batch/dynamic_crm/amended_booking.php
263 *[PHP_SELF] => /dynamic_crm/shekhar/batch/dynamic_crm/amended_booking.php
264 [REQUEST_TIME_FLOAT] => 1563273941.267
265 [REQUEST_TIME] => 1563273941
266
267 __FILE__ // return complete path of file
268 __LINE__ // return line number
269 __DIR__ // return parrent dir of script
270
271
272can not create instace of interface class and abstract class
273interface can have constructor but without body and also implementer must have define constructor
274
275
276
277
278--------------------------- Logical -------------
2791) Leap year
280
281 Any year that is divisible by 400 is definitely a leap year.
282 If it is not divisible by 400, then check if it is divisible by 100, if so, then it is NOT a leap year (even if it is divisible by 4), and
283 If the above two conditions are not satisfied we check for divisibility by 4, if it is divisible by 4 it is a leap year.
284
285 $leapYear = 1900;
286 if($leapYear % 400 == 0){
287 echo "this is leap year";
288 }elseif($leapYear % 100 == 0){
289 echo "not a leap year";
290 }else if($leapYear % 4 == 0){
291 echo "leap year to";
292 }else{
293 echo "not a leap year too";
294 }
295 ----
296 function nodeStyleCallback(err, data) {
297 if (err) {
298 console.error('There was an error', err);
299 return;
300 }
301 console.log(data);
302 }
303
304
305========================== node ========================
306
307*What is Node.js
308 Node.js is a cross-platform runtime environment and library for running JavaScript applications outside the browser. It is used for creating server-side and networking web applications.
309
310nstall Node.js on Linux
311 sudo apt-get install nodejs npm
312 Now you can check the version of Node by node --version
313
314A node.js web application contains the following three parts:
315
316 Import required modules: The "require" directive is used to load a Node.js module.
317 Create server: You have to establish a server which will listen to client's request similar to Apache HTTP Server.
318 Read request and return response: Server created in the second step will read HTTP request made by client which can be a browser or console and return the response.
319
320First Program
321 file : node main.js
322 var http = require("http");
323 http.createServer(function (request, response) {
324 // Send the HTTP header
325 // HTTP Status: 200 : OK
326 // Content Type: text/plain
327 response.writeHead(200, {'Content-Type': 'text/plain'});
328 // Send the response body as "Hello World"
329 response.end('Hello World\n');
330 }).listen(8081);
331 // Console will print the message
332 console.log('Server running at http://127.0.0.1:8081/');
333 Run : cd /dir/
334 : node main.js
335
336There are three console methods that are used to write any node.js stream:
337
338 console.log() : console.log('Hello JavaTpoint');
339 console.error() : console.error(new Error('Hell! This is a wrong method.'));
340 console.warn() : console.warn(`Don't mess with me !`);
341
342REPL Environment
343 The Node.js or node come bundled with REPL environment. Each part of the REPL environment has a specific work.
344 Read: It reads user's input; parse the input into JavaScript data-structure and stores in memory.
345 Eval: It takes and evaluates the data structure.
346 Print: It prints the result.
347 Loop: It loops the above command until user press ctrl-c twice.
348
349While:
350
351 var x = 0
352 undefined
353 > do {
354 ... x++;
355 ... console.log("x: " + x);
356 ... } while ( x < 10 );
357
358Node.js Package Manager
359 It provides online repositories for node.js packages/modules which are searchable on search.nodejs.org
360 It also provides command line utility to install Node.js packages, do version management and dependency management of Node.js packages.
361
362Installing Modules using npm
363 npm install <Module Name>
364 npm install express // it created node_modules directory in the current directory where it installed express module.
365 npm install express -g // Globally installed packages/dependencies are stored in system directory
366
367 npm uninstall express // to uninstall
368 npm ls // get list of installed module
369 npm search express // command is used to search express or module.
370
371
372A list of Node.js global objects are given below:
373
374 __dirname
375 __filename
376 Console
377 Process
378 Buffer
379 setImmediate(callback[, arg][, ...])
380 setInterval(callback, delay[, arg][, ...])
381 setTimeout(callback, delay[, arg][, ...])
382 clearImmediate(immediateObject)
383 clearInterval(intervalObject)
384 clearTimeout(timeoutObject)
385
386Node.js OS Example 1
387 In this example, we are including some basic functions. Create a file named os_example1.js having the following code:
388 File: os_example1.js
389
390 const os=require('os');
391 console.log("os.freemem(): \n",os.freemem());
392 console.log("os.homedir(): \n",os.homedir());
393 console.log("os.hostname(): \n",os.hostname());
394 console.log("os.endianness(): \n",os.endianness());
395 console.log("os.loadavg(): \n",os.loadavg());
396 console.log("os.platform(): \n",os.platform());
397 console.log("os.release(): \n",os.release());
398 console.log("os.tmpdir(): \n",os.tmpdir());
399 console.log("os.totalmem(): \n",os.totalmem());
400 console.log("os.type(): \n",os.type());
401 console.log("os.uptime(): \n",os.uptime());
402
403Node.js Timer
404 Node.js Timer functions are global functions. You don't need to use require() function in order to use timer functions. Let's see the list of timer functions.
405
406 Set timer functions:
407
408 setImmediate(): It is used to execute setImmediate.
409 setInterval(): It is used to define a time interval.
410 setTimeout(): ()- It is used to execute a one-time callback after delay milliseconds.
411 Clear timer functions:
412
413 clearImmediate(immediateObject): It is used to stop an immediateObject, as created by setImmediate
414 clearInterval(intervalObject): It is used to stop an intervalObject, as created by setInterval
415 clearTimeout(timeoutObject): It prevents a timeoutObject, as created by setTimeout
416
417Node.js Errors
418 The Node.js applications generally face four types of errors:
419
420 Standard JavaScript errors i.e. <EvalError>, <SyntaxError>, <RangeError>, <ReferenceError>, <TypeError>, <URIError> etc.
421 System errors
422 User-specified errors
423 Assertion errors
424
425 // Throws with a ReferenceError because b is undefined
426 try {
427 const a = 1;
428 const c = a + b;
429 } catch (err) {
430 console.log(err);
431 }
432
433Node.js DNS
434 The Node.js DNS module contains methods to get information of given hostname.
435
436Node.js Net
437 Node.js provides the ability to perform socket programming. We can create chat application or communicate client and server applications using socket programming in Node.js. The Node.js net module contains functions for creating both servers and clients.
438
439Node.js Crypto
440The Node.js Crypto module supports cryptography. It provides cryptographic functionality that includes a set of wrappers for open SSL's hash HMAC, cipher, decipher, sign and verify functions.
441
442Node.js TLS/SSL
443 TLS stands for Transport Layer Security. It is the successor to Secure Sockets Layer (SSL). TLS along with SSL is used for cryptographic protocols to secure communication over the web.
444 TLS uses public-key cryptography to encrypt messages. It encrypts communication generally on the TCP layer.
445
446Node.js Debugger
447 Node.js provides a simple TCP based protocol and built-in Debuggergging client. For debugging your JavaScript file, you can use debug argument followed by the js file name you want to debug.
448
449
450
451Node.js Process
452 Node.js provides the facility to get process information such as process id, architecture, platform, version, release, uptime, upu usage etc. It can also be used to kill process, set uid, set groups, unmask etc.
453
454
455=================================== Python ==============================
456
457
458https://www.w3schools.com/python/default.asp
459https://www.w3schools.com/python/python_mongodb_getstarted.asp
460=> What can Python do?
461 Python can be used on a server to create web applications.
462 Python can be used alongside software to create workflows.
463 Python can connect to database systems. It can also read and modify files.
464 Python can be used to handle big data and perform complex mathematics.
465 Python can be used for rapid prototyping, or for production-ready software development.
466
467=> Why
468 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
469 Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick.
470 Python can be treated in a procedural way, an object-orientated way or a functional way.
471
472=> Good to know
473 It is possible to write Python in an Integrated Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which are particularly useful when managing larger collections of Python files.
474 Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses.
475 Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly-brackets for this purpose.
476
477=> Get installed version
478 python --version
479
480======================== var, condi and loops ========================
481
482
483=> run Python code
484 python hello.python
485
486OR
487 python
488 >>>> print('Cool')
489
490=> Indentation
491 Python uses indentation to indicate a block of code.
492 Example
493 if 5 > 2:
494 print("Five is greater than two!")
495
496=> Comments
497 Python has commenting capability for the purpose of in-code documentation.
498 Comments start with a #, and Python will render the rest of the line as a comment:
499
500=> Docstrings
501 Docstrings are also comments:
502 Python also has extended documentation capability, called docstrings.
503 Docstrings can be one line, or multiline.
504 Python uses triple quotes at the beginning and end of the docstring:
505
506 Example
507
508 """This is a
509 multiline docstring."""
510 print("Hello, World!")
511
512------------------------------------------------------------------
513
514=> Python Variables
515 A variable name must start with a letter or the underscore character
516 A variable name cannot start with a number
517 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
518 Variable names are case-sensitive (age, Age and AGE are three different variables)
519 EX.
520 x = "awesome"
521 print("Python is " + x)
522
523 Note: + can concate only same type of object.
524 Y = 5
525 print("Cool" + Y) // this will produce error => TypeError: cannot concatenate 'str' and 'int' objects
526
527=> Python Numbers
528 There are three numeric types in Python:
529
530 1 : int : Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length
531
532 2.5 : float: Float, is a number, positive or negative, containing one or more decimals.
533 Float can also be scientific numbers with an "e" to indicate the power of 10. (10.3e2)
534
535 3j : complex : Complex numbers are written with a "j" as the imaginary part:
536
537 x = 3k
538 print(type(x)) // type complex
539
540=> Python Casting
541 x = int(1) # x will be 1
542 y = int(2.8) # y will be 2
543 x = float(1) # x will be 1.0
544 y = float(2.8) # y will be 2.8
545 x = str("s1") # x will be 's1'
546 y = str(2) # y will be
547
548
549=> Python Strings
550 String literals in python are surrounded by either single quotation marks, or double quotation marks
551 a = "Hello, World!"
552 print(a[1]) // e
553 print(a[1:3]) // el
554
555=> Python Strings function
556 obj = "shekhar , Y"
557 len(obj),
558 obj.strip,
559 obj.upper,
560 obj.replace("H", "J")
561 obj.split(",") // return list
562
563=> Command-line String Input
564
565 Python allows for command line input.
566 That means we are able to ask the user for input.
567
568 The following example asks for the user's name, then, by using the input() method, the program prints the name to the screen:
569 Example
570
571 demo_string_input.py
572 print("Enter your name:")
573 x = input()
574 print("Hello, " + x)
575
576=> Python Operators
577
578 Operators are used to perform operations on variables and values.
579 Python divides the operators in the following groups:
580
581 Arithmetic operators
582 Assignment operators
583 Comparison operators
584 Logical operators
585 Identity operators
586 Membership operators
587 Bitwise operators
588
589=> Python Collections
590
591 List: is a collection which is ordered and changeable. Allows duplicate members. We can add,update, remove and del.
592 Tuple: is a collection which is ordered and unchangeable. Allows duplicate members. We can not add,update, remove but can del.
593
594 Set: is a collection which is unordered and unindexed. No duplicate members.
595 Dictionary: is a collection which is unordered, changeable and indexed. No duplicate key members.
596
597 Array type => List Dictionary
598 Tuple Set
599
600
601=> List : changeable, use [] to create
602 listData = ["one", "two", "three"]
603 if listData[1]=="two":
604 print("you are correct");
605
606 // you are correct
607
608 if "one" in listData:
609 print("yes")
610
611 // yes
612
613 => List methods
614 Method Description
615 append() : Adds an element at the end of the list
616 listData.append("orange")
617
618 len() : To determine how many items a list have.
619 len(listData)
620
621 clear() : Removes all the elements from the list
622 copy() : Returns a copy of the list
623 count() : Returns the number of elements with the specified value
624 extend() : Add the elements of a list (or any iterable), to the end of the current list
625 index() : Returns the index of the first element with the specified value
626
627 insert() : Adds an element at the specified position
628 listData.insert(1, "orange")
629
630 pop() : Removes the element at the specified position
631 remove() : Removes the item with the specified value
632 reverse() : Reverses the order of the list
633 sort() : Sorts the list
634
635=> Tuple : unchangeable, use () to create
636 listData = ("one", "two", "three")
637
638
639=> Set : unordered and unindexed. written with curly brackets {}.
640 numSet = {1,2,3,6,4}
641
642=> Dictionary
643 thisdict = {
644 "brand": "Ford",
645 "model": "Mustang",
646 "year": 1964
647 }
648 print(thisdict)
649
650
651--------------------------------------------------------------
652
653Condition & Loops
654
655=> else if
656 x=10
657 y=20
658 if x > y:
659 print("x is greater than y")
660 elif x == y:
661 print("x is equal to y")
662 else:
663 print("x is less than y")
664
665 op: x is less than y
666
667 Short hand else if
668
669 if x==y: print("both are equal")
670
671 if x==y: print("both are equal")
672 else: print("both are not equal")
673
674 if x==y or x>y: print("go ahead")
675 if x==y and y==z: print("both are equal")
676
677=> While
678 i=1
679 while i<10:
680 print(i)
681 i +=1
682
683
684 i=1
685 while i<10:
686 print(i)
687 if i==5:
688 break #break #continue
689 i +=1
690 // 12345
691
692=>Python Iterators:
693 An iterator is an object that contains a countable number of values.
694 An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.
695-----------------------------------------------------------
696Python Functions
697
698 def my_function(fname):
699 print(fname + " Refsnes")
700
701 my_function("Emil")
702
703--------------------------------------------------------------
704Class and Object
705
706 class Person:
707 def __init__(self, name, age): # self is similar to 'this'
708 self.name = name
709 self.age = age
710
711 def myfunc(self):
712 print("Hello my name is " + self.name)
713
714 p1 = Person("John", 36)
715 p1.myfunc()
716
717 del p1.age # del property
718 del p1 # del obj
719
720---------------------------------------------------------------
721Module
722
723 Create a Module
724
725 To create a module just save the code you want in a file with the file extension .py:
726 Example : Save this code in a file named mymodule.py
727 def greeting(name):
728 print("Hello, " + name)
729
730 Import the module named mymodule, and call the greeting function:
731
732 import mymodule
733 import mymodule as mx
734
735 mymodule.greeting("Jonathan")
736 Note: When using a function from a module, use the syntax: module_name.function_name
737
738 There is a built-in function to list all the function names (or variable names) in a module. The dir() function:
739 print(dir(mymodule))
740
741 from mymodule import person1 # this will import only person1 function from mymodule module
742
743
744----------------------------------------------------------------
745
746Python Dates
747
748 A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.
749 Example
750
751 import datetime
752 x = datetime.datetime.now()
753 print(x)
754
755
756JSON
757
758 import json
759 x = {
760 "name": "John",
761 "age": 30,
762 "city": "New York"
763 }
764
765 # convert(dictionary) into JSON:
766 y = json.dumps(x)
767
768 #Convert from JSON to Python(list):
769 z = json.loads(y)
770 print(z["age"])
771
772 You can convert Python objects of the following types, into JSON strings:
773
774 dict
775 list
776 tuple
777 string
778 int
779 float
780 True
781 False
782 None
783
784
785Python RegEx
786
787 Python has a built-in package called re, which can be used to work with Regular Expressions
788
789
790Python PIP
791 PIP is a package manager for Python packages, or modules if you like.
792 Note: If you have Python version 3.4 or later, PIP is included by default.
793 What is a Package?
794
795 A package contains all the files you need for a module.
796 Modules are Python code libraries you can include in your project.
797
798 pip --version # Check PIP version
799 pip install camelcase # Download a package named "camelcase"
800 pip uninstall camelcase # Uninstall the package named "camelcase"
801 pip list # List installed packages:
802
803Try Exception
804 try:
805 print("Hello")
806 except:
807 print("Something went wrong")
808 else:
809 print("Nothing went wrong")
810 --------------
811 try:
812 print("Hello")
813 except:
814 print("Something went wrong")
815 finally:
816 print("The 'try except' is finished")
817
818
819
820
821
822=============================== File handling ========================
823
824=>Open File
825
826 The key function for working with files in Python is the open() function.
827 The open() function takes two parameters; filename, and mode.
828
829 There are four different methods (modes) for opening a file:
830
831 "r" - Read - Default value. Opens a file for reading, error if the file does not exist
832 "a" - Append - Opens a file for appending, creates the file if it does not exist
833 "w" - Write - Opens a file for writing, creates the file if it does not exist
834 "x" - Create - Only Creates the specified file, returns an error if the file exists
835 In addition you can specify if the file should be handled as binary or text mode
836
837 "t" - Text - Default value. Text mode
838 "b" - Binary - Binary mode (e.g. images)
839
840 Syntax
841
842 To open a file for reading it is enough to specify the name of the file:
843 f = open("demofile.txt")
844
845 The code above is the same as:
846 f = open("demofile.txt", "rt")
847 f = open("demofile.txt", "rb")
848
849=> Read File
850 myFile = open("demofile.txt", "rt")
851 print(myFile.read())
852 print(myFile.read(5)) // read only 5 char from file
853 print(myFile.readline()) // read one line of file
854
855 for x in myFile: # loop through line by line
856 print(x)
857
858=> Write filename
859
860 myFile = open("demofile.txt", "a") # append contet to file
861 myFile.write("Now the file has one more line!")
862
863 f = open("demofile.txt", "w") # write to file
864 f.write("Woops! I have deleted the content!")
865
866 f = open("demofile.txt", "x") # create file
867
868=> Delete file
869 To delete a file, you must import the OS module, and run its os.remove() function:
870
871 import os
872 if os.path.exists("demofile.txt"):
873 os.remove("demofile.txt")
874 else:
875 print("The file does not exist")
876
877 os.rmdir("myfolder") # remove folder
878
879
880================================== Py & Mysql ===============================
881
882=> Install MySQL Driver
883
884 Python needs a MySQL driver to access the MySQL database..
885 python -m pip install mysql-connector
886
887 - Create Connection
888
889 import mysql.connector
890 mydb = mysql.connector.connect(
891 host="localhost",
892 user="yourusername",
893 passwd="yourpassword"
894 )
895 print(mydb)
896
897=> Create Database
898
899 mycursor = mydb.cursor()
900 mycursor.execute("CREATE DATABASE mydatabase")
901
902=> Creating a Table
903
904 mycursor = mydb.cursor()
905 mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
906 mycursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")
907
908=> insert into table
909 sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
910 val = ("John", "Highway 21")
911 val = [('Peter', 'Lowstreet 4'),('Amy', 'Apple st 652')] # for multiple value
912 mycursor.execute(sql, val)
913 mydb.commit() #It is required to make the changes, otherwise no changes are made to the table
914 mycursor.lastrowid # get the id of the row you just inserted
915
916=> Update
917 sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'"
918 mycursor.execute(sql)
919 mydb.commit()
920
921 // prevent sql injections
922 sql = "UPDATE customers SET address = %s WHERE address = %s"
923 val = ("Valley 345", "Canyon 123")
924 mycursor.execute(sql)
925 mydb.commit()
926
927
928=> Delete
929 sql = "DELETE FROM customers WHERE address = 'Mountain 21'"
930 mycursor.execute(sql)
931 mydb.commit()
932 print(mycursor.rowcount, "record(s) deleted")
933
934=> Delete table
935 sql = "DROP TABLE IF EXISTS customers"
936 mycursor.execute(sql)
937
938=> select
939 mycursor.execute("SELECT * FROM customers")
940 myresult = mycursor.fetchall() # return one all record
941 myresult = mycursor.fetchone() # return the first row of the result
942 print(myresult)
943
944=> where
945 sql = "SELECT * FROM customers WHERE address ='Park Lane 38'"
946 sql = "SELECT * FROM customers WHERE address LIKE '%way%'"
947 mycursor.execute(sql)
948
949=> prevent SQL injections : The mysql.connector module has methods to escape query values
950 sql = "SELECT * FROM customers WHERE address = %s"
951 adr = ("Yellow Garden 2", )
952 mycursor.execute(sql, adr)
953
954=> Order By
955 sql = "SELECT * FROM customers ORDER BY name DESC"
956 sql = "SELECT * FROM customers LIMIT 5"
957 mycursor.execute(sql)
958
959=> join
960 sql = "SELECT \
961 users.name AS user, \
962 products.name AS favorite \
963 FROM users \
964 INNER JOIN products ON users.fav = products.id"
965
966=>left
967 sql = "SELECT \
968 users.name AS user, \
969 products.name AS favorite \
970 FROM users \
971 LEFT JOIN products ON users.fav = products.id"
972
973=>right
974 sql = "SELECT \
975 users.name AS user, \
976 products.name AS favorite \
977 FROM users \
978 RIGHT JOIN products ON users.fav = products.id"
979
980
981======================================= MONGO ================================
982
983 One of the most popular NoSQL database is MongoDB.
984 Python needs a MongoDB driver to access the MongoDB database. ie "PyMongo"
985 CMD : pip install pymongo
986
987 import pymongo
988
989=> Creating a Database
990
991 To create a database in MongoDB, start by creating a MongoClient object, then specify a connection URL with the correct ip address and the name of the database you want to create.
992
993 MongoDB will create the database if it does not exist, and make a connection to it.
994 Example
995
996 Create a database called "mydatabase":
997
998 import pymongo
999 myclient = pymongo.MongoClient("mongodb://localhost:27017/")
1000 mydb = myclient["mydatabase"]
1001
1002=> Collections
1003 A collection in MongoDB is the same as a table in SQL databases.
1004 mycol = mydb["customers"]
1005
1006 print(mydb.list_collection_names()) // Return a list of all collections(table) in your database:
1007
1008=> Insert
1009 mycol = mydb["customers"]
1010 mydict = { "name": "John", "address": "Highway 37" }
1011 x = mycol.insert_one(mydict)
1012 print(x.inserted_id)
1013
1014 mylist = [
1015 { "name": "Amy", "address": "Apple st 652"},
1016 { "name": "Hannah", "address": "Mountain 21"}
1017 ]
1018 x = mycol.insert_many(mylist)
1019
1020
1021=> Find
1022 mycol.find()
1023 mycol.find({},{ "_id": 0, "name": 1, "address": 1 }) // return name and address
1024 mydoc = mycol.find().sort("name", -1) // -1 for desc and 1 asc
1025 myresult = mycol.find().limit(5)
1026
1027=> Query
1028 myquery = { "address": "Park Lane 38" } // find address with 'Park Lane 38'
1029 mydoc = mycol.find(myquery)
1030
1031 Advance
1032 myquery = { "address": { "$gt": "S" } } // find address that start with S or higher
1033 myquery = { "address": { "$regex": "^S" } } // with the help of regress
1034
1035=> Delete
1036 myquery = { "address": "Mountain 21" }
1037 mycol.delete_one(myquery) // delete collection with address value '"Mountain 21'
1038
1039 myquery = { "address": {"$regex": "^S"} } // Delete all documents were the address starts with the letter S
1040 x = mycol.delete_many(myquery)
1041
1042 x = mycol.delete_many({}) // Delete all documents in the "customers" collection:
1043
1044=> Drop
1045 mycol.drop()
1046
1047=> UPDATE
1048 myquery = { "address": "Valley 345" }
1049 newvalues = { "$set": { "address": "Canyon 123" } }
1050 mycol.update_one(myquery, newvalues) // Change the address from "Valley 345" to "Canyon 123":
1051
1052
1053 myquery = { "address": { "$regex": "^S" } }
1054 newvalues = { "$set": { "name": "Minnie" } }
1055 x = mycol.update_many(myquery, newvalues)
1056
1057============================ symphony ==============
1058
1059Symfony 1.3
1060yml : https://symfony.com/legacy/doc/reference
1061Doc : https://symfony.com/legacy/doc/gentle-introduction
1062
1063
1064
1065==> Design Pattern : MVC
1066 =>Symfony's MVC Implementation
1067
1068 isting 2-11 - list Action, in myproject/apps/myapp/modules/weblog/actions/actions.class.php
1069
1070 <?php
1071
1072 class weblogActions extends sfActions
1073 {
1074 public function executeList()
1075 {
1076 $this->posts = PostPeer::doSelect(new Criteria());
1077 }
1078 }
1079
1080 Listing 2-12 - list Template, in myproject/apps/myapp/modules/weblog/templates/listSuccess.php
1081
1082 <?php slot('title', 'List of Posts') ?>
1083
1084 <h1>List of Posts</h1>
1085 <table>
1086 <tr><th>Date</th><th>Title</th></tr>
1087 <?php foreach ($posts as $post): ?>
1088 <tr>
1089 <td><?php echo $post->getDate() ?></td>
1090 <td><?php echo $post->getTitle() ?></td>
1091 </tr>
1092 <?php endforeach; ?>
1093 </table>
1094
1095 In addition, you will still need to define a layout, as shown in Listing 2-13, but it will be reused many times.
1096
1097 Listing 2-13 - Layout, in myproject/apps/myapp/templates/layout.php
1098
1099 <html>
1100 <head>
1101 <title><?php include_slot('title') ?></title>
1102 </head>
1103 <body>
1104 <?php echo $sf_content ?>
1105 </body>
1106 </html>
1107
1108
1109=> Root Tree Structure
1110
1111apps/
1112 frontend/
1113 backend/
1114cache/
1115config/
1116data/
1117 sql/
1118doc/
1119lib/
1120 model/
1121log/
1122plugins/
1123test/
1124 bootstrap/
1125 unit/
1126 functional/
1127web/
1128 css/
1129 images/
1130 js/
1131 uploads/
1132
1133---------------------------
1134
11351: The YAML Format
1136
1137# Comment on a line
1138a. Sequences use a dash followed by a space (-):
1139 - PHP
1140 - Perl
1141 - Python
1142 OR
1143 [PHP, Perl, Python]
1144 This is equivalent to the following PHP code
1145 array('PHP', 'Perl', 'Python');
1146
1147 'Chapter 1': [Introduction, Event Types]
1148
1149
1150b. Mappings
1151 PHP: 5.2
1152 MySQL: 5.1
1153 Apache: 2.2.20
1154 which is equivalent to the following PHP code:
1155 array('PHP' => 5.2, 'MySQL' => 5.1, 'Apache' => '2.2.20');
1156
1157 "symfony 1.0":
1158 PHP: 5.0
1159 Propel: 1.2
1160 "symfony 1.2":
1161 PHP: 5.2
1162 Propel: 1.3
1163
1164 array(
1165 'symfony 1.0' => array(
1166 'PHP' => 5.0,
1167 'Propel' => 1.2,
1168 ),
1169 'symfony 1.2' => array(
1170 'PHP' => 5.2,
1171 'Propel' => 1.3,
1172 ),
1173 );
1174
1175 PHP code in yml
1176 1.0:
1177 version: <?php echo file_get_contents('1.0/VERSION')."\n" ?>
1178 1.1:
1179 version: "<?php echo file_get_contents('1.1/VERSION') ?>"
1180
1181
1182--------------------------------------------------------------
1183
11842. Configuration file principle
1185
1186==>Cache
1187
1188All configuration files in symfony are cached to PHP files by configuration handler classes. When the is_debug setting is set to false (for instance for the prod environment), the YAML file is only accessed for the very first request; the PHP cache is used for subsequent requests. This means that the "heavy" work is done only once, when the YAML file is parsed and interpreted the first time.
1189The parsing and caching of each configuration file is done by specialized configuration handler classes, configured in config_handler.yml.
1190
1191
1192==> Constants
1193
1194Configuration files: core_compile.yml, factories.yml, generator.yml, databases.yml, filters.yml, view.yml, autoload.yml
1195
1196==> Application Settings : app.yml
1197
1198You can also use settings defined in the app.yml configuration file by prefixing the key name with APP_.
1199APP_ : Its can be change as per nedd in config_handler.yml
1200
1201Eg. sfConfig::get('dycrm_logpath');
1202
1203==> Special Constants : By default, symfony defines four constants according to the current front controller:
1204
1205SF_APP :getApplication() -> The current application name
1206SF_ENVIRONMENT :getEnvironment() ->The current environment name
1207SF_DEBUG :isDebug() ->Whether debug is enabled or not
1208SF_SYMFONY_LIB_DIR :getSymfonyLibDir() ->The symfony libraries directory
1209
1210==>Directories
1211Constants are also very useful when you need to reference a directory or a file path without hardcoding it.
1212SF_APPS_DIR : SF_ROOT_DIR/apps
1213SF_CONFIG_DIR : SF_ROOT_DIR/config
1214SF_CACHE_DIR : SF_ROOT_DIR/cache
1215SF_DATA_DIR : SF_ROOT_DIR/data
1216SF_LIB_DIR : SF_ROOT_DIR/lib
1217SF_LOG_DIR : SF_ROOT_DIR/log
1218SF_PLUGINS_DIR : SF_ROOT_DIR/plugins
1219SF_TEST_DIR : SF_ROOT_DIR/test
1220SF_WEB_DIR : SF_ROOT_DIR/web
1221SF_UPLOAD_DIR : SF_WEB_DIR/uploads
1222
1223==>environment-awareness
1224
1225Configuration files: settings.yml, factories.yml, databases.yml, app.yml
1226
1227When symfony needs a value from a configuration file, it merges the configuration found in the current environment section with the 'all' configuration. The special 'all' section describes the default configuration for all environments. If the environment section is not defined, symfony falls back to the all configuration.
1228
1229When the configuration is compiled, the values from all the different files are merged according to a precedence order:
1230
1231 The module configuration (PROJECT_ROOT_DIR/apps/APP_NAME/modules/MODULE_NAME/config/XXX.yml)
1232 The application configuration (PROJECT_ROOT_DIR/apps/APP_NAME/config/XXX.yml)
1233 The project configuration (PROJECT_ROOT_DIR/config/XXX.yml)
1234 The configuration defined in the plugins (PROJECT_ROOT_DIR/plugins/*/config/XXX.yml)
1235 The default configuration defined in the symfony libraries (SF_LIB_DIR/config/XXX.yml)
1236
1237 For instance, the settings.yml defined in an application directory inherits from the configuration set in the main config/ directory of the project, and eventually from the default configuration contained in the framework itself (lib/config/config/settings.yml).
1238
1239NOTE:
1240 When a configuration file is environment-aware and can be defined in several directories, the following priority list applies:
1241
1242 Module
1243 Application
1244 Project
1245 Specific environment
1246 All environments
1247 Default
1248--------------------------------------------------------------
1249==> settings.yml
1250 Each environment section has two sub-sections: .actions and .settings. All configuration directives go under the .settings sub-section, except for the default actions to be rendered for some common pages.
1251
1252 The settings.yml configuration file is cached as a PHP file; the process is automatically managed by "sfDefineEnvironmentConfigHandler class".
1253
1254 .actions :The .actions sub-section defines the action to execute when common pages must be rendered.
1255 default:
1256 .actions:
1257 error_404_module: default
1258 error_404_action: error404
1259
1260 login_module: default
1261 login_action: login
1262
1263
1264 .settings: The.settings sub-section is where the framework configuration occurs.
1265 All settings defined in the .settings section are available anywhere in the code by using the sfConfig object and prefixing the setting with sf_. For instance, to get the value of the charset setting, use:
1266
1267 sfConfig::get('sf_charset');
1268
1269--------------------------------------------------------------
1270==> factories.yml
1271Factories are core objects needed by the framework during the life of any request. They are configured in the factories.yml configuration file and always accessible via the sfContext object:
1272
1273The supported factory names are: controller, logger, i18n, request, response, routing, storage, user, view_cache, and view_cache_manager.
1274
1275--------------------------------------------------------------
1276==> factories.yml
1277
1278 The admin generator of symfony allows the creation of a backend interface for your model classes. It works whether you use Propel or Doctrine as your ORM.
1279
1280 Creation
1281 Admin generator modules are created by the propel:generate-admin or doctrine:generate-admin tasks:
1282
1283 Configuration File
1284 The configuration of such a module can be done in the apps/backend/modules/model/article/generator.yml file:
1285
1286 generator:
1287 class: sfPropelGenerator
1288 param:
1289 # An array of parameters
1290
1291--------------------------------------------------------------
1292==> databases.yml
1293The main databases.yml configuration file for a project can be found in the config/
1294
1295
1296Most of the time, all applications of a project share the same database. That's why the main database configuration file is in the project config/ directory. You can of course override the default configuration by defining a databases.yml configuration file in your application configuration directories.