1580786700

# Introduction Python Fsum() Method with Examples

math.fsum() method is a library method of math module, it is used to find the sum (in float) of the values of an iterable, it accepts an iterable object like an array, list, tuple, etc (that should contain numbers either integers or floats), and returns sum in float of all values.

## Python Fsum()

### Syntax

``````    math.fsum(iterable)

``````

Here, the value can be a range or an iterable like an array, tuple.

### Parameters:

`iterable` – an iterable object like list, array, tuple, etc.

### Return value:

The fsum() function returns the sum of the iterable or range in floating-point number. ‘f’ in fsum() stands for float.

### Example 1

``````# Python code demonstrate example of
# math.fsum() method
import math

# iterable objects
a = range(10)   # a range object (0,10)
b = [10, 20, 30, 40, 50]    # list of integers
c = [10, 20, 30.30, 40, 50.0]   # list of integers & floats
d = [10.20, 30.40]  # list of floats
e = (10, 20, 30, 40.50) # tuple

# printing sum of all values of the iterable objects
print("fsum(a): ", math.fsum(a))
print("fsum(b): ", math.fsum(b))
print("fsum(c): ", math.fsum(c))
print("fsum(d): ", math.fsum(d))
print("fsum(e): ", math.fsum(e))

``````

Output

``````fsum(a):  45.0
fsum(b):  150.0
fsum(c):  150.3
fsum(d):  40.599999999999994
fsum(e):  100.5

``````

### Example 2

``````# app.py

#importing math library
import math

#Finding sum of a range first

#taking input from the user
x=int(input("Please enter a range up to which you want to sum: "))

#finding sum of the range using fsum()
print("Sum of the range is: ",math.fsum(range(x)))

#Finding sum of an iterable

#taking input of a list
print("Please enter array element with space separated integer: ")
arr=list(map(int,input().split(" ")))

#printing all array elements
print("All array elements are: ",arr)

#Finding sum of all the values using fsum()
print("Sum of all elements of the array is: ",math.fsum(arr))

``````

Output

``````Please enter a range up to which you want to sum: 15
Sum of the range is:  105.0
Please enter the array element with space-separated integer:
1 3 5 7
All array elements are:  [1, 3, 5, 7]
Sum of all elements of the array is:  16.0

``````

In this program, we first have an imported math library, and then we have taken an input integer from the user. After that, we have calculated the sum of all elements up to that number, and then we have printed that.

On the other hand, we have taken input for a list, where the user will have to given all list elements by a space. Then we have called fsum() to calculate the sum of all the list elements.

Python fsum() is one of the Python Math function that is used to calculate and return the sum of iterators like Tuples and Lists.

Thanks for reading !

#python #programming

1677668905

## TS-mockito

Mocking library for TypeScript inspired by http://mockito.org/

## 1.x to 2.x migration guide

1.x to 2.x migration guide

## Main features

• Strongly typed
• IDE autocomplete
• Mock creation (`mock`) (also abstract classes) #example
• Spying on real objects (`spy`) #example
• Changing mock behavior (`when`) via:
• `thenReturn` - return value #example
• `thenThrow` - throw an error #example
• `thenCall` - call custom method #example
• `thenResolve` - resolve promise #example
• `thenReject` - rejects promise #example
• Checking if methods were called with given arguments (`verify`)
• `anything`, `notNull`, `anyString`, `anyOfClass` etc. - for more flexible comparision
• `once`, `twice`, `times`, `atLeast` etc. - allows call count verification #example
• `calledBefore`, `calledAfter` - allows call order verification #example
• Resetting mock (`reset`, `resetCalls`) #example, #example
• Capturing arguments passed to method (`capture`) #example
• Recording multiple behaviors #example
• Readable error messages (ex. `'Expected "convertNumberToString(strictEqual(3))" to be called 2 time(s). But has been called 1 time(s).'`)

## Installation

`npm install ts-mockito --save-dev`

## Usage

### Basics

``````// Creating mock
let mockedFoo:Foo = mock(Foo);

// Getting instance from mock
let foo:Foo = instance(mockedFoo);

// Using instance in source code
foo.getBar(3);
foo.getBar(5);

// Explicit, readable verification
verify(mockedFoo.getBar(3)).called();
verify(mockedFoo.getBar(anything())).called();
``````

### Stubbing method calls

``````// Creating mock
let mockedFoo:Foo = mock(Foo);

// stub method before execution
when(mockedFoo.getBar(3)).thenReturn('three');

// Getting instance
let foo:Foo = instance(mockedFoo);

// prints three
console.log(foo.getBar(3));

// prints null, because "getBar(999)" was not stubbed
console.log(foo.getBar(999));
``````

### Stubbing getter value

``````// Creating mock
let mockedFoo:Foo = mock(Foo);

// stub getter before execution
when(mockedFoo.sampleGetter).thenReturn('three');

// Getting instance
let foo:Foo = instance(mockedFoo);

// prints three
console.log(foo.sampleGetter);
``````

### Stubbing property values that have no getters

Syntax is the same as with getter values.

Please note, that stubbing properties that don't have getters only works if Proxy object is available (ES6).

### Call count verification

``````// Creating mock
let mockedFoo:Foo = mock(Foo);

// Getting instance
let foo:Foo = instance(mockedFoo);

// Some calls
foo.getBar(1);
foo.getBar(2);
foo.getBar(2);
foo.getBar(3);

// Call count verification
verify(mockedFoo.getBar(1)).once();               // was called with arg === 1 only once
verify(mockedFoo.getBar(2)).twice();              // was called with arg === 2 exactly two times
verify(mockedFoo.getBar(between(2, 3))).thrice(); // was called with arg between 2-3 exactly three times
verify(mockedFoo.getBar(anyNumber()).times(4);    // was called with any number arg exactly four times
verify(mockedFoo.getBar(2)).atLeast(2);           // was called with arg === 2 min two times
verify(mockedFoo.getBar(anything())).atMost(4);   // was called with any argument max four times
verify(mockedFoo.getBar(4)).never();              // was never called with arg === 4
``````

### Call order verification

``````// Creating mock
let mockedFoo:Foo = mock(Foo);
let mockedBar:Bar = mock(Bar);

// Getting instance
let foo:Foo = instance(mockedFoo);
let bar:Bar = instance(mockedBar);

// Some calls
foo.getBar(1);
bar.getFoo(2);

// Call order verification
verify(mockedFoo.getBar(1)).calledBefore(mockedBar.getFoo(2));    // foo.getBar(1) has been called before bar.getFoo(2)
verify(mockedBar.getFoo(2)).calledAfter(mockedFoo.getBar(1));    // bar.getFoo(2) has been called before foo.getBar(1)
verify(mockedFoo.getBar(1)).calledBefore(mockedBar.getFoo(999999));    // throws error (mockedBar.getFoo(999999) has never been called)
``````

### Throwing errors

``````let mockedFoo:Foo = mock(Foo);

when(mockedFoo.getBar(10)).thenThrow(new Error('fatal error'));

let foo:Foo = instance(mockedFoo);
try {
foo.getBar(10);
} catch (error:Error) {
console.log(error.message); // 'fatal error'
}
``````

### Custom function

You can also stub method with your own implementation

``````let mockedFoo:Foo = mock(Foo);
let foo:Foo = instance(mockedFoo);

when(mockedFoo.sumTwoNumbers(anyNumber(), anyNumber())).thenCall((arg1:number, arg2:number) => {
return arg1 * arg2;
});

// prints '50' because we've changed sum method implementation to multiply!
console.log(foo.sumTwoNumbers(5, 10));
``````

### Resolving / rejecting promises

You can also stub method to resolve / reject promise

``````let mockedFoo:Foo = mock(Foo);

when(mockedFoo.fetchData("a")).thenResolve({id: "a", value: "Hello world"});
when(mockedFoo.fetchData("b")).thenReject(new Error("b does not exist"));
``````

### Resetting mock calls

You can reset just mock call counter

``````// Creating mock
let mockedFoo:Foo = mock(Foo);

// Getting instance
let foo:Foo = instance(mockedFoo);

// Some calls
foo.getBar(1);
foo.getBar(1);
verify(mockedFoo.getBar(1)).twice();      // getBar with arg "1" has been called twice

// Reset mock
resetCalls(mockedFoo);

// Call count verification
verify(mockedFoo.getBar(1)).never();      // has never been called after reset
``````

You can also reset calls of multiple mocks at once `resetCalls(firstMock, secondMock, thirdMock)`

### Resetting mock

Or reset mock call counter with all stubs

``````// Creating mock
let mockedFoo:Foo = mock(Foo);
when(mockedFoo.getBar(1)).thenReturn("one").

// Getting instance
let foo:Foo = instance(mockedFoo);

// Some calls
console.log(foo.getBar(1));               // "one" - as defined in stub
console.log(foo.getBar(1));               // "one" - as defined in stub
verify(mockedFoo.getBar(1)).twice();      // getBar with arg "1" has been called twice

// Reset mock
reset(mockedFoo);

// Call count verification
verify(mockedFoo.getBar(1)).never();      // has never been called after reset
console.log(foo.getBar(1));               // null - previously added stub has been removed
``````

You can also reset multiple mocks at once `reset(firstMock, secondMock, thirdMock)`

### Capturing method arguments

``````let mockedFoo:Foo = mock(Foo);
let foo:Foo = instance(mockedFoo);

// Call method
foo.sumTwoNumbers(1, 2);

// Check first arg captor values
const [firstArg, secondArg] = capture(mockedFoo.sumTwoNumbers).last();
console.log(firstArg);    // prints 1
console.log(secondArg);    // prints 2
``````

You can also get other calls using `first()`, `second()`, `byCallIndex(3)` and more...

### Recording multiple behaviors

You can set multiple returning values for same matching values

``````const mockedFoo:Foo = mock(Foo);

when(mockedFoo.getBar(anyNumber())).thenReturn('one').thenReturn('two').thenReturn('three');

const foo:Foo = instance(mockedFoo);

console.log(foo.getBar(1));    // one
console.log(foo.getBar(1));    // two
console.log(foo.getBar(1));    // three
console.log(foo.getBar(1));    // three - last defined behavior will be repeated infinitely
``````

Another example with specific values

``````let mockedFoo:Foo = mock(Foo);

when(mockedFoo.getBar(1)).thenReturn('one').thenReturn('another one');
when(mockedFoo.getBar(2)).thenReturn('two');

let foo:Foo = instance(mockedFoo);

console.log(foo.getBar(1));    // one
console.log(foo.getBar(2));    // two
console.log(foo.getBar(1));    // another one
console.log(foo.getBar(1));    // another one - this is last defined behavior for arg '1' so it will be repeated
console.log(foo.getBar(2));    // two
console.log(foo.getBar(2));    // two - this is last defined behavior for arg '2' so it will be repeated
``````

Short notation:

``````const mockedFoo:Foo = mock(Foo);

// You can specify return values as multiple thenReturn args
when(mockedFoo.getBar(anyNumber())).thenReturn('one', 'two', 'three');

const foo:Foo = instance(mockedFoo);

console.log(foo.getBar(1));    // one
console.log(foo.getBar(1));    // two
console.log(foo.getBar(1));    // three
console.log(foo.getBar(1));    // three - last defined behavior will be repeated infinity
``````

Possible errors:

``````const mockedFoo:Foo = mock(Foo);

// When multiple matchers, matches same result:
when(mockedFoo.getBar(anyNumber())).thenReturn('one');
when(mockedFoo.getBar(3)).thenReturn('one');

const foo:Foo = instance(mockedFoo);
foo.getBar(3); // MultipleMatchersMatchSameStubError will be thrown, two matchers match same method call
``````

### Mocking interfaces

You can mock interfaces too, just instead of passing type to `mock` function, set `mock` function generic type Mocking interfaces requires `Proxy` implementation

``````let mockedFoo:Foo = mock<FooInterface>(); // instead of mock(FooInterface)
const foo: SampleGeneric<FooInterface> = instance(mockedFoo);
``````

### Mocking types

You can mock abstract classes

``````const mockedFoo: SampleAbstractClass = mock(SampleAbstractClass);
const foo: SampleAbstractClass = instance(mockedFoo);
``````

You can also mock generic classes, but note that generic type is just needed by mock type definition

``````const mockedFoo: SampleGeneric<SampleInterface> = mock(SampleGeneric);
const foo: SampleGeneric<SampleInterface> = instance(mockedFoo);
``````

### Spying on real objects

You can partially mock an existing instance:

``````const foo: Foo = new Foo();
const spiedFoo = spy(foo);

when(spiedFoo.getBar(3)).thenReturn('one');

console.log(foo.getBar(3)); // 'one'
console.log(foo.getBaz()); // call to a real method
``````

You can spy on plain objects too:

``````const foo = { bar: () => 42 };
const spiedFoo = spy(foo);

foo.bar();

console.log(capture(spiedFoo.bar).last()); // [42]
``````

### Thanks

Author: NagRock
Source Code: https://github.com/NagRock/ts-mockito

1626775355

## Why use Python for Software Development

No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas.

By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities.

Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly.

## 5 Reasons to Utilize Python for Programming Web Apps

Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.

Robust frameworks

Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions.

Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events.

Simple to read and compose

Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building.

The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties.

Utilized by the best

Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player.

Massive community support

Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions.

Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking.

Progressive applications

Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.

The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.

### Summary

Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential.

The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.

#python development services #python development company #python app development #python development #python in web development #python software development

1597751700

## How To Compare Tesla and Ford Company By Using Magic Methods in Python

Magic Methods are the special methods which gives us the ability to access built in syntactical features such as ‘<’, ‘>’, ‘==’, ‘+’ etc…

You must have worked with such methods without knowing them to be as magic methods. Magic methods can be identified with their names which start with __ and ends with __ like init, call, str etc. These methods are also called Dunder Methods, because of their name starting and ending with Double Underscore (Dunder).

Now there are a number of such special methods, which you might have come across too, in Python. We will just be taking an example of a few of them to understand how they work and how we can use them.

### 1. init

``````class AnyClass:
def __init__():
print("Init called on its own")
obj = AnyClass()
``````

The first example is _init, _and as the name suggests, it is used for initializing objects. Init method is called on its own, ie. whenever an object is created for the class, the init method is called on its own.

The output of the above code will be given below. Note how we did not call the init method and it got invoked as we created an object for class AnyClass.

``````Init called on its own
``````

Let’s move to some other example, add gives us the ability to access the built in syntax feature of the character +. Let’s see how,

``````class AnyClass:
def __init__(self, var):
self.some_var = var
print("Calling the add method")
return self.some_var + other_obj.some_var
obj1 = AnyClass(5)
obj2 = AnyClass(6)
obj1 + obj2
``````

#python3 #python #python-programming #python-web-development #python-tutorials #python-top-story #python-tips #learn-python

1602968400

## Python Tricks Every Developer Should Know

Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?

In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.

### Let’s get started

Swapping value in Python

Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead

``````>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName
>>> print(FirstName, LastName)
('Jordan', 'kalebu')
``````

#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development

1602666000

## How to Remove all Duplicate Files on your Drive via Python

Today you’re going to learn how to use Python programming in a way that can ultimately save a lot of space on your drive by removing all the duplicates.

### Intro

In many situations you may find yourself having duplicates files on your disk and but when it comes to tracking and checking them manually it can tedious.

Heres a solution

Instead of tracking throughout your disk to see if there is a duplicate, you can automate the process using coding, by writing a program to recursively track through the disk and remove all the found duplicates and that’s what this article is about.

But How do we do it?

If we were to read the whole file and then compare it to the rest of the files recursively through the given directory it will take a very long time, then how do we do it?

The answer is hashing, with hashing can generate a given string of letters and numbers which act as the identity of a given file and if we find any other file with the same identity we gonna delete it.

There’s a variety of hashing algorithms out there such as

• md5
• sha1
• sha224, sha256, sha384 and sha512

#python-programming #python-tutorials #learn-python #python-project #python3 #python #python-skills #python-tips