fabiochiu/medium-articles huggingface dataset:
3 Simple Ways to Download Files With Python
By: Zack West
Tags: Python, Python3, Software Development, Programming, Data Science

2. requests.get + manual save

The Python Requests module is a super-friendly library billed as “HTTP for humans.” Offering very simplified APIs, Requests lives up to its motto for even high-throughput HTTP-related demands. However, it doesn’t feature a one-liner for downloading files. Instead, one must manually save streamed file data as follows:

There are some important aspects of this approach to keep in mind — most notably the binary format of data transfer. When a web browser loads a page (or file), it encodes it using the specified encoding from the host.

Common encodings include UTF-8 and Latin-1. This is a directive aimed at web browsers that are receiving and displaying data that isn’t immediately applicable to downloading files.

Note: Downloaded files may require encoding in order to display properly. That’s beyond the scope of this tutorial.
Python List
Tags: Python, Python3, Machine Learning, Python Programming, Data Science

The list type is probably the most commonly used collection type in Python. Despite its name, a list is more like an

array in other languages, mostly JavaScript. In Python, a list is merely an ordered collection of valid Python values. A

list can be created by enclosing values, separated by commas, in square brackets.

Source:https://goalkicker.com/PythonBook/

#python #pythoncode #pythonprogramming #pythonlearning #pythonprogrammer #java #javascript #emprendedores #developer #jupyternotebook #pythonlist #pythonlanguage
A Movie Recommender Engine using K-Means and Collaborative Filtering & Deployed to Kubernetes
By: Amlan Chakladar
Tags: AWS, Kubernetes, K Means Clustering, Python3, Machine Learning

This is my version of the #CloudGuruChallenge. The whole post can be found below.

This post describes about how I built a Movie recommender system (similar to Netflix). I built this system in response to the Cloud Challenge from Acloudguru (Here). But then I thought why not have an end to end implementation of the system along with a Web app and a CI/CD deployment process to deploy the Machine learning model. Hopefully I will be able to help someone learn the concepts and fulfill the challenge requirements too. This is my first attempt on building something based on Machine learning so I apologize if there are some gaps in my understanding of the algorithms and how its executed. I write about other cloud related topics Here .

The whole post is below:

https://cloudy.achakladar.com/a-movie-recommender-engine-using-k-means-and-collaborative-filtering-and-deployed-to-kubernetes-ckj7mj1280292w7s1bzxw4uiv
How I started writing better python code with sourcery.ai
By: Sukumar Rdjf
Tags: Python, Python3, Pycharm, Sourcery, Pep8

With the rise in popularity of python, the demand for good python developers also went up. I mean who wouldn’t want to write better code?

One can definitely write better python code once they get ample experience in it. What if there is a tool that can help you write python code even better by providing you suggestions on refactoring.

Today, we are going to look at one such tool called Sourcery.

Sourcery is nothing but a tool to help you write better python code when you are working on Pycharm (my preferred IDE) or VSCode. It is a plugin which can be configured very easily in Pycharm or VSCode. All you need is an email for signup to get the token which should be entered in IDE.
Python one line function(Map, Zip, Reduce and Filter Functions)
By: Ergün Elvan Bilsel
Tags: Comprehension, Zip, Python3, Map, Filter

Functions that you can always use in your Python scripts, that will gain useful and speed.When you start writing Python scripts, especially after learning about for loops and lists, we are constantly taking a similar approach.

Let’s start with a few examples

n ** 3 calculation from 0 to 10 in the first example

result-1

Now let’s find the numbers in the list we created that can be divided by 2.

result-2

Map Function

It is used in the form of map (func, iter1). In other words, it sends the elements of the data you have to a function in order and returns the result as a single object.

result-3

We have created a new list with the results of the square of the elements in the list we created.

Zip Function

Combines 2 lists on each other’s indices. While doing this, it is based on the length of the list with the shortest element.

We have listed the battles and their dates in a single list.

result-4

Reduce Function

It needs to be imported into the project to use it.

from functools import reduce

The Reduce function is a structure that can circulate within any data type that you can loop, reducing all the elements in the data type and allowing comparison.

result-5

Filter Function

It is the filtering function.

Used as filter (func, push), uses push elements as a filter function that returns true or false. A new list is returned containing all x items for which the func (x) function is true.

In our example, we see the use of the zip function that we learned earlier. We are doing a filtering process to find the date and name of wars, including the year 1071 and the year 1091, from the zip list we have.

result-6

I hope it was a useful writing…
[django] How to make REST API using django rest framework
Tags: Django Rest Framework, Python3, 42seoul, Django, Rest Api

Serializers

Then go to your app and make serializers.py file. And import serializers from rest_framework and models that you want to make into REST API.

Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON , XML or other content types.
Hire Dedicated Python Developers in the USA
By: Khushbu Muchhadiya
Tags: Python, Hire Python Developers, Python3, Web Development, Python Programming

Python is an unmistakable and ground-breaking object-oriented programming language, similar to Perl, Ruby, Scheme, or Java. Python serves as one of the top programming languages, for developing even the most complex websites, and web apps.

At HoulryDeveloper.io, we deploy top developers in the USA, who have been working for years in Python programming, to ensure code quality and stability. We have successfully delivered several diverse projects for Python development which were related to various industry verticals, like Healthcare, Education, Finance, Oil & Gas, Logistics, Retail, Transportation, and so on…

Below are the simple steps that we follow to hire our dedicated Python developers in the USA:

Ready to build a solid team of developers? Call us on +161–97–986983, email us at sales@hourlydeveloper.io
Install pip3 on Big Sur using Brew
By: แมวใบไม, ครองโลก Airmee Chanita Anuwong
Tags: Big Sur, Pip3, Python3

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
JSON Web Token / JWT Raw Implementation in Python3
By: Injae Lee
Tags: Python3, Jwt, Coding, Python

In this article, we are going to walkthrough a version of the raw implementation of the JWT specification in Python3. For simplicity, we will use the HMAC + SHA256 for the signing algorithm.

Let’s look at the JWT in a functional sense. There are three outputs to the JWT concatenated with a dot(“.”).

{base64_header}.{base64_payload}.{base64_signature}

When building the JWT, there are three inputs.

the header describing the token type and the signing algorithm in JSON

describing the token type and the signing algorithm in JSON the payload describing the claims or information about the user assigned the token in JSON

describing the claims or information about the user assigned the token in JSON the private key that is used to sign the header and the payload

The following are the functional operations.

Removing all non-key, non-value white spaces in the JSON message

URL Safe Base64 encoding

HMAC (Keyed-Hashing for Message Authentication) operation

Functional Operations

We will first look at the individual operations and bring it all together.

JSON White Space Removal

import json cleaned_json_str = json.dumps(

json.loads(raw_json_string),

separators = (",", ":"), # default is (",", ": ") notice the space

)

Transport Safe Encoding

import base64 b64_encoded_json = base64.urlsafe_b64encode(

cleaned_json_str.encode("ascii") # convert to bytes

) # here we need to strip the offsets filled with "=" for use

#

b64_final_json = b64_encoded_json.decode("ascii").rstrip("=")

HMAC

import hmac

import hashlib

import base64 secret_key_bytes = b"my_secret_key" signature_bytes = hmac.new(

secret_key_bytes,

msg = your_message_to_sign.encode("ascii"),

digestmod = hashlib.sha256,

).digest() b64_signature = base64.urlsafe_b64encode(

signature_bytes).decode("ascii").rstrip("=")

Inputs

For the illustration we will use the following header and payload JSON’s.

Header

{

"alg": "HS256",

"typ": "JWT"

}

Payload

{

"sub": "cd08769d-c6a5-43cf-be5f-14f34ecddaa2",

"name": "Your Friendly Neighbor",

"iat": 1609459200

}

Private Key

your-secret-goes-here

Bring It All Together
[LeetCode]#1572. Matrix Diagonal Sum
By: Fatboy Slim
Tags: Python3, Leetcode, Python, Leetcode Easy

Environment: Python 3.8

Key technique: ~

Given a square matrix mat , return the sum of the matrix diagonals.

Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.

Example 1:

Input: mat = [[1,2,3],

[4,5,6],

[7,8,9]]

Output: 25

Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25

Notice that element mat[1][1] = 5 is counted only once.

Example 2:

Input: mat = [[1,1,1,1],

[1,1,1,1],

[1,1,1,1],

[1,1,1,1]]

Output: 8

Example 3:

Input: mat = [[5]]

Output: 5

Analysis:

Summary all i and ~i number if matrix size /2 has a remainder, summary -matrix center point.

Solution:

class Solution:

def diagonalSum(self, mat):

ans = 0

for i in range(len(mat)):

ans += mat[i][i] + mat[i][~i]

if (len(mat) % 2): ans -= mat[int(i/2)][int(i/2)]

return ans

Submissions:

Reference:

https://leetcode.com/problems/matrix-diagonal-sum/discuss/968730/Python-Simple-and-Easy-Solution
[Codility Series — Python solution] Lesson 2.1 CyclicRotation
By: Manish Joshi
Tags: Python, Python3, Tutorial, Codility, Programming

This post is to provide a solution for the Codility problem — Cyclic Rotation.

I would encourage you to read the problem statement carefully on the Codility website, try out your own solution first, and if you are really stuck even after spending considerable time on the problem, look for the solution provided below.

I will try to provide a detailed description of why I choose to write the solution a certain way but please note that I do not consider myself Python ‘Guru’ and hence would encourage you to try and make the solution even better and let me know your thoughts in the comments section as well :)

def solution(A, K):

if K == len(A) or len(A) == 0 or len(A) == 1:

return A

elif K > len(A):

K = K % len(A)

else:

pass

B = A[len(A)-K:]

C = A[:len(A)-K]

return B + C

Details on the Solution:

if K == len(A) or len(A) == 0 or len(A) == 1

The above “if statement” tries to catch the following straightforward cases early in the solution so that we do not have to waste the time and memory in processing these cases:

If we rotate an array the same number of times as its length, we will always get the same array back. Example — [1, 2, 3] rotated 3 times will give us [3, 1, 2] → [2, 3, 1] → [1, 2, 3]. If the array is empty, we will always get an empty array in the result. If the array has only 1 element, we will always get the same array back, no matter if we rotate it 10 times or 100, 000 times.

elif K > len(A):

K = K % len(A)

else:

pass

Since we know that if we rotate an array the same number of times as the length of the array we will always get the same array, so in case of a very high value for ‘K’ we could safely ignore the value of K that is in multiples of the length of the array. For example, if the length of an array is 80 and the value of ‘K’ is 82, instead of trying to rotate the array 82 times, we can rotate it just 82 % 80 = 2 times and get the same result. The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left-hand operand by the right-hand operand.

The program will enter the else state when K is already less than len(A) and in that case, we don’t have to do anything and hence we would just use pass.

B = A[len(A)-K:]

C = A[:len(A)-K]

return B + C

The final piece is just slicing coming to the rescue where we can create 2 arrays, the first one “B” which gives us array A that starts from len(A)-K index so for an array A = [1,2,3,4,5] and K =2, array B would start from index 5 -2 = 3, i.e. [4, 5]. Similarly, for the same example array, C with slicing will give us the elements of the array till index 3, i.e. C will be [1, 2, 3]. With the above 2 arrays set we can happily return array B + array C as the result, which will give us [4, 5, 1, 2, 3] which is the array A rotated 2 times.

Please note that we could have avoided assigning array B and array C altogether and wrote the slicing logic directly in the return statement like below.
[LeetCode]#1534. Count Good Triplets
By: Fatboy Slim
Tags: Leetcode, Python3, Python, Leetcode Easy

Environment: Python 3.8

Key technique: for

Given an array of integers arr , and three integers a , b and c . You need to find the number of good triplets.

A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true:

0 <= i < j < k < arr.length

|arr[i] - arr[j]| <= a

|arr[j] - arr[k]| <= b

|arr[i] - arr[k]| <= c

Where |x| denotes the absolute value of x .

Return the number of good triplets.

Example 1:

Input: arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3

Output: 4

Explanation: There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)].

Analysis:

Match three conditions as below. If get 3 passes, return 1 match.

Solution:

class Solution:

def countGoodTriplets(self, arr, a, b, c):

ans = 0 for i in range(len(arr)):

for j in range(i+1, len(arr)):

for k in range(j+1, len(arr)):

a_pass = abs(arr[i] - arr[j]) <= a

b_pass = abs(arr[j] - arr[k]) <= b

c_pass = abs(arr[i] - arr[k]) <= c



if a_pass and b_pass and c_pass:

ans += 1

return ans

Submissions:

Reference:

https://leetcode.com/problems/count-good-triplets/discuss/980046/Python3%3A-Not-efficient(at-all)-nested-for-loops-solution
getting started with python class 11
Tags: Python Programming, Python3, Computer Science, Python

getting started with python class 11

Q 1. Who developed python Programming Language ?

ans. Guido Van Rossum in 1990s developed programming language.

Q 2. Is pyhton an object oriented language ?

ans. Yes, Python is an object oriented language.

Q 3. ‘ Python is an interpreted high level language’ What it mean to you?

ans. ‘Python is a high level language’ means it is programmer-friendly i.e., easy to program and comprehend.

‘Python is an interpreted Language’ means it requires an interpreter (not compiler) to execute its code line by line — one statement at a time.

Q 4. Python programming language got its name from which show.

ans. Python programming language was named after a British TV sho namely ‘Monty Python’s Flying Circus’.

Q 5. What does a cross platform language mean ?

ans. A cross platform language means it can run well on variety of platforms like Windows, Linux/Unix, Macintosh etc.

read more
Python — 完全程式新手的起步經驗、課程&書單(不專業)分享
Tags: Python, 自學python, Python3, Python Programming, 自學

Free Python Tutorial - Python for Mathematics:For High School & Engineering Student

In this tutorial, We will learn the basics of Python and then we will learn to solve various mathematical problems in…
Which is better: Python or C++?
Tags: Program, Logic, Python3, Improvement, Programming Languages

Many people want to get started with coding but they don’t know which language should they start with. Both the languages are very popular among the tech community and you can start with any programming language. But I will still try to differentiate between two in terms of different features they have.
How to upload External Image URL Directly into S3 Bucket using python
By: Shardul Kulkarni
Tags: Python3, Python, Python Programming, Aws S3

Today we will try to understand how we can Upload Any External Image URL Directly into S3 Bucket using python

See below Flow diagram for the same.

For implementing this functionality we required below Python Components / Libraries.

pymysql boto3 urllib3 urllib.parse import urlparse requests

Note : Please indent python code properly in your editor.

Follow below steps to implement this functionality in your application

Step 1:

Define your AWS Credentials in Constants

AWS_ACCESS_KEY_ID = ‘XXXXXXXXXX’

AWS_SECRET_ACCESS_KEY = ‘XXXXXXXXXX’

AWS_BUCKET_NAME = ‘XXXXXXXXXX’

AWS_REGION_CODE = ‘XXXXXXXXXX’

AWS_SIGNATURE_VERSION = ‘XXXXXXXXXX’

Step 2:

Create Main python function

readUploadFileOnS3Bucket(‘http://www.abc.com/abc.jpg’)

Step 3:

Now we will create new function for validating Image URL In my case i have created “validateURL(url)” function which will validate is image URL valid or not.

def validateURL(url):

isImgValid = 0

http = urllib3.PoolManager()

r = http.request(‘GET’, url)

if(r.status == 200):

isImgValid = 1

return isImgValid

Step 4:

Through below function we will read the image and upload it on S3 Bucket . my function name is “readUploadFileOnS3Bucket(file_url):”

def readUploadFileOnS3Bucket(file_url):

parseUrl = urlparse(file_url);

tempS3Key = parseUrl.path

isImagePresent = validateURL(internet_image_url)



if(isImagePresent == 1):

req_for_image = requests.get(internet_image_url, stream=True)

file_object_from_req = req_for_image.raw

req_data = file_object_from_req.read() try:

tempS3Key = tempS3Key[1:]

s3Bucket = s3.Bucket(bucket_name_to_upload_image_to) // Name of the S3 Bucket

response = s3Bucket.put_object(Key=tempS3Key, Body=req_data,ACL=’public-read’)

return response

except ClientError as e:

response = 0

return response

In above Function inside Response which i have marked in bold you will get S3 Bucket Object Data. That you can store it in Database for referring image path on main web site.

If any queries contact me on

shardulk10@gmail.com
Python Basic Questions Part 4
By: Avanish Tiwari
Tags: Python Help, Python, Python3, Python Programming, Python Assignment Help

count words from input string in Python

first of all we have to take input from user and after that we have to split it and with the help of len () we can…
Python Basic Questions Part 3
By: Avanish Tiwari
Tags: Python Help, Python, Python3, Python Programming, Python Assignment Help

subtract all elements in a list in Python

we can subtract or add to all elements in list with help of array in Python Numpy. first of all we have to import numpy…
Python Flask — SQLAlchemy Relational DB 關聯式資料庫的建立
By: Sean Yeh
Tags: Flask Framework, Python, Flask, Python3

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Basic Operators in Python
By: Joseph Hart
Tags: Python Programming, Python3

Completing basic math operations is easier than you may think. Operations like addition, subtraction, multiplication, and division are useful for statistics and completing other tasks.

Addition

Addition can be as easy as typing out your integers and using the addition sign. You can sum all integers in a list.

Subtraction

Python will also subtract numbers, including subtracting from a negative number.

Division

Python is capable of diving your variables, as long as there is a numerical value to them.

Multiplication

To complete the multiplication operation, use the asterisk character.

In order to create an exponent, use double asterisks.
Leetcode-string
By: Yunrui Li
Tags: String, Leetcode, Python3

I’m Taiwanese expat. I’v worked in Singapore as data scientist after graduation from Taiwan and currently I work in Amsterdam as machine learning engineer.
Deauthentication Attacks with Python
By: Alexis Rodriguez
Tags: Python, Hacking, Python3, Security, Programming

Performing a Deauthentication Attack with Python

The Scapy module allows us to craft packets network layer by network layer. All fields related to a given layer have corresponding default values if they are not manually set, allowing us to craft valid packets without much effort. To show you just how easy it is to craft packets with Scapy, the following function definition, which contains just three lines of code, will provide all the instructions we need to perform our deauthentication attack:

The function above creates an 802.11 frame using the Dot11, RadioTap , and Dot11Deauth classes defined in the Scapy package. The Dot11 class allows us to create an 802.11 packet with 11 attributes that we can manually set as shown below:

To send deauthentications frames we only need to set the following Dot11 object properties: addr1 , addr2 , addr3 .

addr1 is set to the MAC address of the victim machine; addr2 is set to the AP’s MAC address; and addr3 is also set to the MAC address of the AP.

The Dot11Deauth class adds all the necessary details to our 802.11 frame that specifies that this will be a deauthentication frame. I did not look at the source code of the Dot11Deauth class, but I will assume it will set the appropriate type and subtype attributes that specify whether this frame will be a management, control, or data frame and the corresponding subtype . In our case, the type will be a management frame and the subtype will be a deauthentication frame. For more on type and subtype values, check out this link.

Scapy’s classes overload the / operator to permit us to stack different layers on top of each other using the / operator. In our case, we stack all three layers on top of each other ( RadioTap()/dot11/Dot11Deauth() ), creating a frame that we can send. Note: the RadioTap layer simply provides supplementary information about an 802.11 frame for analysis applications. It is not part of the 802.11 frame. More information on the RadioTap header can be found here.

As can be observed from the code above, Scapy does an excellent job of abstracting away the underlying sophistication of creating these packets. In a programming language like C, the creation of such packets would be tedious.
Upgrading PostgreSQL’s Enum type with SQLAlchemy using Alembic migration
By: Kamil Kucharski
Tags: Postgresql, Enum, Python3, Sqlalchemy, Alembic

Alembic is an awesome library to setup migrations for your database schema which works really great. There is one small thing which it isn’t capable of though. When you upgrade an enum value in your code, it may get pretty confused.

This tutorial will show you how to overcome this weakness, so you don’t get stuck with upgrading the enum types yourself on the PostgreSQL server, but rather create the migration file which will do that for you.

Basic model

Let’s jump straight into the code. Let’s say we have the following enum and SQLAlchemy’s ORM model:

Basic model example

Then, generating Alembic’s new revision will result in the migration file containing our status field details with available values imprinted:

First revision example

Updating the enum

What will happen if we want to add a new status to the enum definition? Let’s try and add one to our Status enum.

Enum after change

Now, after creating next revision, migration file is going to be empty i.e. it will look like this:

Empty migration

So, how can we make sure the REJECTED value is added so the database knows that it should be a valid one? Fortunately for us in PostgreSQL 9.1 an ALTER TYPE directive was added. With it, we can easily upgrade our enum type:

Enum upgrade

And what about downgrade to roll back the changes? In this case it would be a bit more work, but nothing that couldn’t be done:

Enum downgrade

This is still pretty easy, isn’t it?

Autocommit block

As you’ve probably noticed in the examples above I’ve executed all of the commands inside the autocommit block. Why is that?

If ALTER TYPE ... ADD VALUE (the form that adds a new value to an enum type) is executed inside a transaction block, the new value cannot be used until after the transaction has been committed. https://www.postgresql.org/docs/13/sql-altertype.html

As you can see from the documentation excerpt it’s necessary to run those commands within the autocommit block. Otherwise if our next migrations will try to use the new value (e.g. to insert new values to the database inside the migration) it will raise an exception as our updated type won’t be available until all migration files are properly executed.

Furthermore if you are using an older version of PostgreSQL (<12) you will have to add an autocommit block every time when using ALTER TYPE … ADD VALUE command, otherwise the migration will fail. The restriction is needed because using this directive may lead to possible index issues in the enum column.

Conclusion

In this tutorial we’ve successfully generated the migration file which can automatically upgrade enum types on PostgreSQL server. If you want to read more about this topic or Alembic migrations in general, take a look at an official Alembic documentation.
How I am learning Python for the fourth time?
Tags: Python, Python Programming, Python3

Python, together with SQL is becoming the lingua franca of data analytics and machine learning. I am a data analyst by profession and took up my first job in 2007 in India. However, I managed to get by at work for 12 years without learning Python.I was good at SAS and knew some SQL but not Python. I had no programming exposure in school or in university as I was studying to become a medical doctor and later on took up Electronics Engineering. I knew the importance of Python about 8 years ago when I read about it on the internet. I went to an instructor in India and tried to learn it 1–1 from him. It was a bad experience because it was taught like a history lesson. I didn’t practice any problems and there were only verbal lectures day after day. Needless to say, I quit in less than a month. It just didnt feel right although I didn’t know why.

My second attempt was to take a Coursera course after I came to the US. I passed the Beginner’s course but I didn’t ‘learn’ much. I knew bit of theory and to code a few problems but it was just not enough. They were all multiple choice questions and I understood them. But I couldn’t ace interviews or do anything material with that knowledge. I bought plenty of books and gathered some content in bits and pieces but that didn’t up my skills much.

My third attempt was to take a course from a university. I aced that course too and solved all the exercises but when I tried to do some web scraping and a Kaggle project, I was stumped. I was just doing something wrong. I needed to set it right.

I asked computer engineers and software professionals how they learnt coding and I came away with a few great tips. I was determined to use it and learn the right way. I signed up for a coursera specialization again. This time around, I aced the course BUT I didn’t stop there. I started practising atleast 50 odd problems for every concept. For instance, the first course introduced for loops and while loops together with functions. I installed the Atom editor and the following ensued:

a)I practiced a variety of for loop and while loop problems that went beyond the course.

b) I did not look up any errors on Google. I used the knowledge I gained solely from the course and figured out the errors before I proceeded to even the next the chapter.

c)I wrote comments diligently.

d)I didn’t jump into the problem directly but wrote tiny bits of code to come up with the final solution. Breaking down the problem was one of the most important skills I learnt this time around.

e) I took down notes and decided to teach it back to someone else.

I am on the way to becoming a data scientist and using APIs and doing more complex programming. Most importantly, I found a better way to learn programming which is a life skill.
Python setup for Data Science in Windows
By: Rakesh Ts
Tags: Python3, Machine Learning, Python Programming, Artificial Intelligence, Computer Vision

Objective: To set up python and its libraries in Windows 10 and 7

The most easiest way to install python is using Anacondas

Anacondas:

There are two versions of python that you can choose to install.

Python 2.7 Python 3.6

Choose any version of your choice

Installation:

Create a folder named Machine Learning or PythonInstall (your choice). Get into the folder and create another folder Anaconda3

Click next and check both the boxes as shown below in the picture, This will take care of path settings in Windows enabling us to run python from any terminal plus, we don’t have to exclusively set the environmental path variables.

Follow as shown in the Picture

Click Install.

Post Installation :

Open Command Prompt and type python, You should get into Python Shell as shown below.

Python Version 3.6.5

python -V command gives you the version of python installed.

You can install and update any packages in python, the easiest way to do is using ‘pip’. The pip command is a tool for installing and managing Python packages, such as those found in the Python Package Index. Using PIP, You can install the module. It will install the dependency also.

To make your environment industry ready, it is advisable to update / Install using pip as it demands.

The below picture will show you, how to use pip command to install keras package.

>> pip install keras

pip install keras

The below exception can be solved by using the command python -m pip install — upgrade pip.

You are using pip version 10.0.1, however version 18.1 is available.

You should consider upgrading via the ‘python -m pip install — upgrade pip’ command.
Python Trojan (undetectable). I am going to be showing you how to…
By: Spencer Roffey
Tags: Ethical Hacking, Python, Hacking, Trojan, Python3

I am going to be showing you how to create a trojan horse virus using python, I have chosen to show a very basic trojan as it will be easier to understand.

I will be using python version 3.8 in this tutorial. This program we are creating also only uses standard libraries that come with python.

A trojan horse virus is a type of malware which disguises itself as a legitimate piece of software, this is to mislead the user so that it can perform tasks undetected. Trojans can enable cyber criminals to create backdoors on your device and steal sensitive data.

The example I will be using today is a trojan disguised as a number guessing game.

Tutorial:

First we will use python and the random library to create a simple number guessing game. We will be storing this under a function called “game”. We will save this file as client.py.

Game function

This game generates a random number from 0 to 100. The user is then given as many attempts as they need to guess the number. This is a very simple program. However, this is not going to be the only function running in our program.

We also need to make the trojan function. This will be done using the socket library. This is the client.py.

Trojan function

This is the trojan function, first we declare a few vital variables. These are the host IP address and the port that the client will be connecting to. Choose the IP of whatever device you will be hosting the server on and chose a port that is not in use. Then I created a tuple object of the IP and port stored under “ADDR”, this variable will be used to make the connection.

We must then create the socket object “client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)”. Then create the connection.

Once this is done we will check for any commands received from the server which the attacker will be sending. This is all happening in the background as the game is running and therefore, there are no outputs. I have created a command called “cmdon” and this will be used to give the attacker access to the terminal on the victims machine. The victim will not see any of this happening. When the attacker wishes to stop using terminal commands they can then send the command “cmdoff”.

To finish off the client file, we use the threading library to run both functions simultaneously.

threading functions

We must now create a server script. We must create a new file and call it “server.py”. This is the script that the attacker will use to initiate the attack.

Server file

The image above is a screenshot of the code we will be using for the server.py file. This is a very simple socket server which listens for connections and offers the user input to send to the victim. This is where the command will be sent to execute on the victims machine.

Make sure the server.py file is running on your machine and then run the client.py file on the victims machine.

Using Virus Total I have scanned the client file and it is undetectable.
Python as a popular language
By: Himanshu Tripathi
Tags: Python3

Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.

The Python interpreter and the extensive standard library are freely available in source or binary form for all major platforms from the Python Web site, https://www.python.org/, and may be freely distributed. The same site also contains distributions of and pointers to many free third party Python modules, programs and tools, and additional documentation

The Python interpreter is easily extended with new functions and data types implemented in C or C++ (or other languages callable from C). Python is also suitable as an extension language for customizable applications.

This tutorial introduces the reader informally to the basic concepts and features of the Python language and system. It helps to have a Python interpreter handy for hands-on experience, but all examples are self-contained, so the tutorial can be read off-line as well.

For a description of standard objects and modules, see The Python Standard Library. The Python Language Reference gives a more formal definition of the language. To write extensions in C or C++, read Extending and Embedding the Python Interpreter and Python/C API Reference Manual. There are also several books covering Python in depth.
Rename files alphabetically using python
By: Chirag Taneja
Tags: Python, Python3, Rename File, Python Programming, Rename

When we have to do work on a huge number of files, but don’t remember the sequence of files, python can help

Steps

sort the file paths on the basis of either modification time or creation time loop the sorted paths rename the path names

Skip to end if you just want the code without any comments

Just the code
Running Django on Google Colab.
By: Amit Sindoliya
Tags: Django, Google Colab, Python, Python3

Photo by Kevin Bhagat on Unsplash

Requirements:

Mobile, Laptop or any other device which has a web browser and can take input. (Why don’t you try developing a website on a fridge?)

A Google Account!

Internet Connection (I think you have this step down since you can read this post)

Okay, Here Are The Steps:

Step 1:

Go to Google Colab, Sign In and create a notebook. You can go to google Colab using the below link. Or just search on Google.

https://colab.google.research.com

Step 2:

Now try running this. It should say requirement already satisfied if not it would install Django in your Colab environment. You Need this! You can’t develop on Django without Django.

!pip install django

Since I want to show you guys a working example. I’ll create a new project. You can use the below command if don’t know how to or if you are new to Django. Using the ‘!’ at the start you can run any linux terminal command.

!django-admin startproject portfolio

Use ls to check your directory structure. Below is the output of my project.

Now keep in mind changing your directory i.e. portfolio doesn’t work with an exclamation(!) in Google Colab. You need to use % before your command.

%cd portfolio/

Now basic setup of your Django project is done. Let’s move on to the real thing.

Step 3:

Running this code will give you a link. We Need This Link.

from google.colab.output import eval_js print(eval_js("google.colab.kernel.proxyPort(8000)"))

Please note, I have provided a port in the above code. We need to use the same port no. whenever running the Django server. And we need the link for accessing the server from our local machine.

Also you cannot connect to the development server directly. we need to add it in ALLOWED_HOSTS, which is a list in settings.py.

ALLOWED_HOSTS = ['colab.research.google.com']

Now run your server using the below code. And access the server using Google Colab link you printed by running the eval_js method earlier.

DO NOT RUN THE SERVER USING THE SERVER ADDRESS YOU GET AFTER RUNNING THE BELOW COMMAND.

!python manage.py runserver 8000

Hooray!!! We can now work on Django Anywhere, Anytime.
[LeetCode]#1588. Sum of All Odd Length Subarrays
By: Fatboy Slim
Tags: Python3, Leetcode, Python, Leetcode Easy

Environment: Python 3.8

Key technique: while

Given an array of positive integers arr , calculate the sum of all possible odd-length subarrays.

A subarray is a contiguous subsequence of the array.

Return the sum of all odd-length subarrays of arr .

Example 1:

Input: arr = [1,4,2,5,3]

Output: 58

Explanation: The odd-length subarrays of arr and their sums are:

[1] = 1

[4] = 4

[2] = 2

[5] = 5

[3] = 3

[1,4,2] = 7

[4,2,5] = 11

[2,5,3] = 10

[1,4,2,5,3] = 15

If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58

Analysis:

Calculate all possible pairs as below. Return summary

Solution:

class Solution:

def sumOddLengthSubarrays(self, arr):

ans = 0

for i in range(len(arr)):

j = i + 1

while j <= len(arr):

ans += sum(arr[i:j])

j += 2

return ans

Submissions:

Reference:

https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/980723/Python-Non-Brute-Force-solution
Python made easy
Tags: Certification, Coding, Python3

Hello all

This blog to make all the developers and coders familiar with one of the fastest emerging languages which are made available in all the domains. In this blog, we will get to know the best python tutorial, python Interview questions, training, and certification courses. Currently, I’m pursuing a python online course certification from python online course certification

I will be updating all the information required to become an expert in python

What is python?

Python is one of the top 10 popular programming languages of 2020. Python is a general-purpose and high-level programming language. You can use Python for developing G.U.I, games, analytics. python online course certification adds weightage to your resume as well. The syntax is simple and easy to implement why should we python We should be able to adapt the fastest growing technologies for a better future and high career growth

Who can able to take the python training one who is interested in learning new technology can go through the course and can make a good career in it

What are the prerequisites for taking this Python course?

Well, You don’t need any specific knowledge to learn Python. A basic knowledge of programming can help you

I have seen many blogs out of that I found intellipaat is one of the best resource to learn python

How is Intellipaat Python certification awarded?

Intellipaat follows a rigorous certification process. To become a certified Python Programmer, you must fulfill the following criteria: Online Instructor-led Course Successful completion of all projects, which will be evaluated by trainers Scoring a minimum of 60 percent in the Python quiz conducted by Intellipaat Self-paced Course Completing all the course videos in our LMS Scoring a minimum of 60 percent in the Python quiz conducted by Intellipaat

For more information check out the python course page
Python 101
By: Mariana Yañez
Tags: Python3, Python, Python Beginner

Hello readers!!✨👋🏼 Here is my 12th-week blog as an intern in a software development company. For the past couple of weeks, we’ve been working with open source, but this last week more than being focus on doing open-source issues, I tried to understand and learn python. Here is some of what I’ve been learning as a newbie with python. Also, it’s helping me to find more challenging issues to work on next.

First of all, I’ve been going through the next concepts on REPL (Read-evaluate-print loop). You can use it in Visual Studio Code (extension). REPL is another terminal, and you can use it to test assumptions, little bits of code, and get an instant result. Let’s start with the basic concepts and their explanation:

Functions: To start a function, you need to start the function definition (def), then the name. For example, “def variable_name():”

Functions can also accept no arguments, for instance:

Accepting arguments: If there is no control flow, then everything after “return” is ignored.

Function Arguments:

Lists: Used for storing similar items and in cases where items need to be added or removed. An empty list can be defined as “[ ]” or “List_name( )” and it will always start in the position 0. Let’s see an example of updating an item in a list:

Also, there are two ways of sorting number in python. Let’s see some examples with this list “lottery_num = [1, 4, 34242, 78, 11]”:

Using “Sorted”: what this method does is make a copy of the list and return the values sorted.

if we want to save the copy we just need to define a variable, for example, “x=sorted (lottery_num).”

2. Doing it in place: This will actually modify the list

Adding items to a list: To add items we will used “append”

Extend: We use “extend” to combine two lists. “names.extend(colors)” where “colors” is the list that will be combined into “names.”

List lookups: It looks for the value and position inside a list.

Index: “.index” tells you in what position the item is.

Count: “.count” tells you how many items with the same name are on the list.

Change and remove an item:

Tuples: Lightweight collection that is used to keep track of related but different items “Immutable.” Tuples are perfect for containers that need an immutable key aka a key that can’t be changed.

Unpacking tuples: Are great to quickly consolidate information. To unpack “(“Max”, 10, “Math”, 9.5)” we need to declare variables for each item, for instance, it would look like this: “name, age, subject, grade = student”

if we don’t want to save one of the values as a variable, we can use underscore “_.” Example: name, age, subject, _ = subject

I know I wrote a lot about basic concepts, but from my experience, it’s better to start filling the voids or getting strong basics. To be able to start with something more challenging.
I want to learn to program. Should I begin with C; C++; Java; or Python? And why?
Tags: Progr, C, Python3, Java, Assignment Help

As a learner/ experimenter , I would recommend first by just search the internet for different languages that are available , just to get a brief about what you are getting into.

From my personal point of view,I would recommend starting with C. Do study different ways to manipulate code for computer to reveal its secrets.C is a very beautiful language and it finds its backbone in many different industries(LINUX ,for example)
How to use Python 2to3 Converter with Pycharm IDE
By: Valliappan Thenappan
Tags: Python3, Pycharm, Python2 Vs Python3, Python2, Python Programming

As a Python developer, we would be dealing with a lot of old python 2.x code which we would like to convert it to Python 3. Python by default provides us a nice command line utility called 2to3. You can read more about it here.

But let us say we want to use Pycharm to do that for us. All we need is few configurations using Pycharm’s External tools.

Here are the steps:

(1) First step is to find where the 2to3 utility is located in your system, o find that we can use the ‘which’ command as follows:

Open a terminal (For windows and linux) and type which 2to3 , this should give you the path of it. For me it was located on /usr/local/bin/2to3

(2) Open Pycharm->Preferences->Tools->External Tools and add a new tool with the following options:

Note the -w option, this means once you run this on a file, the changes get written to the disk.

(3) Now for the usage, take any python file which is in version 2.x and right click on the file and choose External Tools->2to3

Voila, this should convert your file to Python 3 as follows:

You can do this conversion on a directory level as well which will apply changes to all files within the directory. Hope you enjoyed the short read. Cheers!
Web Scraping in Python with BeautifulSoup
By: Enver Şanlı
Tags: Web Mining, Python, Python3, Beautifulsoup, Scraping

Hi everyone !

Web development is growing stey by step and every day it happens. Everyday developing a new web app with new technologies or technics. We will talk one of them today about Python.

Python is a popular language and it has a strong communities. Python let us for a lot of technic for web scraping. Also it has strong documentry and libraries for that. We are going to do an basic project to scraping data from any web site. I can suggest CoLab to develop Python projects easily and you do not need anything else to development. You can find that on your Google Drive.

Firstly, I will show you how to create a Python project on your CoLab studio.

Go to your drive

Click to “New” button

Click New(Yeni) Button on your Drive

After, find “Others” option and choose “Google Colaborotary”
Brute force .zip files. I am going to be talking about how you…
By: Spencer Roffey
Tags: Python, Brute Force, Hacking, Brute Force Attack, Python3

I am going to be talking about how you can brute force .zip files that have passwords.

Brute forcing is an attack method used by hackers to attempt to find passwords or break into accounts. In order to perform a brute force attack, the attacker submits many passwords or passphrases in the hope that one of them will be correct. These attacks can be completed using a wordlist. A wordlist is usually a text file that consists of many passwords or passphrases. The passwords and passphrases in the wordlists are the ones used to brute force by the attacker.

I will be using python3 and the zip file library to show how you can perform a brute force attack on a .zip file.

The code for the .zip brute forcer

Above is the code I have used to crack .zip passwords/passphrases.