text:
PYTHON NOTES

Table of Contents

PYTHON NOTES

Table of Contents

Functional Programming

Lambdas

Map

Filter

Generators-1

Generators-2

Generators-3

Decorators-1

Decorators-2

Recursion-1

Recursion-2

Recursion-3

Sets-1

Sets-2

Sets-3

Data Structures

itertools-1

itertools-2

itertools-3

Object-Oriented Programming

Classes-1

__init__

Methods

Classes-2

Inheritance-1

Inheritance-2

Inheritance-3

Inheritance-4

Source: SoloLearn Python Tutorial

Functional Programming

Lambdas

Creating a function normally (using def) assigns it to a variable automatically.

This is different from the creation of other objects - such as strings and integers - which can be created on the fly, without assigning them to a variable.

The same is possible with functions, provided that they are created using lambda syntax. Functions created this way are known as anonymous.

This approach is most commonly used when passing a simple function as an argument to another function. The syntax is shown in the next example and consists of the lambda keyword followed by a list of arguments, a colon, and the expression to evaluate and return.

def my_func(f, arg):
  return f(arg)

my_func(lambda x: 2*x*x, 5)

Note: Lambda functions get their name from lambda calculus, which is a model of computation invented by Alonzo Church.

Map

The built-in functions map and filter are very useful higher-order functions that operate on lists (or similar objects called iterables).

The function map takes a function and an iterable as arguments, and returns a new iterable with the function applied to each argument.

Example:

def add_five(x):
  return x + 5

nums = [11, 22, 33, 44, 55]
result = list(map(add_five, nums))
print(result)

Result:

[16, 27, 38, 49, 60]

We could have achieved the same result more easily by using lambda syntax.

nums = [11, 22, 33, 44, 55]

result = list(map(lambda x: x+5, nums))
print(result)

Note: To convert the result into a list, we used list explicitly.

Filter

The function filter filters an iterable by removing items that don't match a predicate (a function that returns a Boolean).

Example:

nums = [11, 22, 33, 44, 55]
res = list(filter(lambda x: x%2==0, nums))
print(res)

Result:

[22, 44]

Note: Like map, the result has to be explicitly converted to a list if you want to print it.

Example:

Fill in the blanks to remove all items that are greater than 4 from the list.

nums = [1, 2, 5, 8, 3, 0, 7]
res = list(filter(lambda x: x < 5, nums))
print(res)

Generators-1

Generators are a type of iterable, like lists or tuples.

Unlike lists, they don't allow indexing with arbitrary indices, but they can still be iterated through with for loops.

They can be created using functions and the yield statement.

Example:

def countdown():
  i=5
  while i > 0:
    yield i
    i -= 1

for i in countdown():
  print(i)

Result:

5

  4

  3

  2

  1

The yield statement is used to define a generator, replacing the return of a function to provide a result to its caller without destroying local variables.

Generators-2

Due to the fact that they yield one item at a time, generators don't have the memory restrictions of lists.

In fact, they can be infinite!

def infinite_sevens():
  while True:
    yield 7

for i in infinite_sevens():
  print(i)

Result:

7

  7

  7

  7

  7

  7

  7

  …

Note: In short, generators allow you to declare a function that behaves like an iterator, i.e. it can be used in a for loop.

Example:

Fill in the blanks to create a prime number generator, that yields all prime numbers in a loop. (Consider having an is_prime function already defined):

 def get_primes():
  num = 2
  while True:
    if is_prime(num):
      yield num
    num += 1

Generators-3

Finite generators can be converted into lists by passing them as arguments to the list function.

def numbers(x):
  for i in range(x):
    if i % 2 == 0:
      yield i

print(list(numbers(11)))

Result:

[0, 2, 4, 6, 8, 10]

Note: Using generators results in improved performance, which is the result of the lazy (on demand) generation of values, which translates to lower memory usage. Furthermore, we do not need to wait until all the elements have been generated before we start to use them.

Decorators-1

Decorators provide a way to modify functions using other functions.

This is ideal when you need to extend the functionality of functions that you don't want to modify.

Example:

def decor(func):
  def wrap():
    print("============")
    func()
    print("============")
  return wrap

def print_text():
  print("Hello world!")

decorated = decor(print_text)
decorated()

We defined a function named decor that has a single parameter func. Inside decor, we defined a nested function named wrap. The wrap function will print a string, then call func(), and print another string. The decor function returns the wrap function as its result.

We could say that the variable decorated is a decorated version of print_text - it's print_text plus something.

In fact, if we wrote a useful decorator we might want to replace print_text with the decorated version altogether so we always got our "plus something" version of print_text.

This is done by re-assigning the variable that contains our function:

print_text = decor(print_text)
print_text()

Now print_text corresponds to our decorated version.

Decorators-2

In our previous example, we decorated our function by replacing the variable containing the function with a wrapped version.

def print_text():
  print("Hello world!")

print_text = decor(print_text)

This pattern can be used at any time, to wrap any function.

Python provides support to wrap a function in a decorator by pre-pending the function definition with a decorator name and the @ symbol.

If we are defining a function we can "decorate" it with the @ symbol like:

@decor
def print_text():
  print("Hello world!")
Try It Yourself

This will have the same result as the above code.

Note: A single function can have multiple decorators.

Recursion-1

Recursion is a very important concept in functional programming.

The fundamental part of recursion is self-reference - functions calling themselves. It is used to solve problems that can be broken up into easier sub-problems of the same type.

A classic example of a function that is implemented recursively is the factorial function, which finds the product of all positive integers below a specified number.

For example, 5! (5 factorial) is 5 * 4 * 3 * 2 * 1 (120). To implement this recursively, notice that 5! = 5 * 4!, 4! = 4 * 3!, 3! = 3 * 2!, and so on. Generally, n! = n * (n-1)!.

Furthermore, 1! = 1. This is known as the base case, as it can be calculated without performing any more factorials.

Below is a recursive implementation of the factorial function.

def factorial(x):
  if x == 1:
    return 1
  else:
    return x * factorial(x-1)

print(factorial(5))

Result:

120

Note: The base case acts as the exit condition of the recursion.

Recursion-2

Recursive functions can be infinite, just like infinite while loops. These often occur when you forget to implement the base case.

Below is an incorrect version of the factorial function. It has no base case, so it runs until the interpreter runs out of memory and crashes.

def factorial(x):
  return x * factorial(x-1)

print(factorial(5))

Result:

RuntimeError: maximum recursion depth exceeded

Recursion-3

Recursion can also be indirect. One function can call a second, which calls the first, which calls the second, and so on. This can occur with any number of functions.

Example:

def is_even(x):
  if x == 0:
    return True
  else:
    return is_odd(x-1)

def is_odd(x):
  return not is_even(x)

print(is_odd(17))
print(is_even(23))

Result:

True

  False

Sets-1

Sets are data structures, similar to lists or dictionaries. They are created using curly braces, or the set function. They share some functionality with lists, such as the use of in to check whether they contain a particular item.

num_set = {1, 2, 3, 4, 5}
word_set = set(["spam", "eggs", "sausage"])

print(3 in num_set)
print("spam" not in word_set)

Result:

True

  False

Note: To create an empty set, you must use set(), as {} creates an empty dictionary.

Sets-2

Sets differ from lists in several ways, but share several list operations such as len.

They are unordered, which means that they can't be indexed.

They cannot contain duplicate elements.

Due to the way they're stored, it's faster to check whether an item is part of a set, rather than part of a list.

Instead of using append to add to a set, use add.

The method remove removes a specific element from a set; pop removes an arbitrary element.

nums = {1, 2, 1, 3, 1, 4, 5, 6}
print(nums)
nums.add(-7)
nums.remove(3)
print(nums)

Result:

{1, 2, 3, 4, 5, 6}

  {1, 2, 4, 5, 6, -7}

Note: Basic uses of sets include membership testing and the elimination of duplicate entries.

Sets-3

Sets can be combined using mathematical operations.

The union operator | combines two sets to form a new one containing items in either.

The intersection operator & gets items only in both.

The difference operator - gets items in the first set but not in the second.

The symmetric difference operator ^ gets items in either set, but not both.

first = {1, 2, 3, 4, 5, 6}
second = {4, 5, 6, 7, 8, 9}

print(first | second)
print(first & second)
print(first - second)
print(second - first)
print(first ^ second)

Result:

{1, 2, 3, 4, 5, 6, 7, 8, 9}

  {4, 5, 6}

  {1, 2, 3}

  {8, 9, 7}

  {1, 2, 3, 7, 8, 9}

StackEdit stores your documents in your browser, which means all your documents are automatically saved locally and are accessible offline!

Data Structures

As we have seen in the previous lessons, Python supports the following data structures: lists, dictionaries, tuples, sets.

When to use a dictionary:

When you need a logical association between a key:value pair.

When you need fast lookup for your data, based on a custom key.

When your data is being constantly modified. Remember, dictionaries are mutable.

When to use the other types:

Use lists if you have a collection of data that does not need random access. Try to choose lists when you need a simple, iterable collection that is modified frequently.

Use a set if you need uniqueness for the elements.

Use tuples when your data cannot change.

Many times, a tuple is used in combination with a dictionary, for example, a tuple might represent a key, because it's immutable.

itertools-1

The module itertools is a standard library that contains several functions that are useful in functional programming.

One type of function it produces is infinite iterators.

The function count counts up infinitely from a value.

The function cycle infinitely iterates through an iterable (for instance a list or string).

The function repeat repeats an object, either infinitely or a specific number of times.

Example:

from itertools import count

for i in count(3):
  print(i)
  if i >=11:
    break

Result:

3

  4

  5

  6

  7

  8

  9

  10

  11

itertools-2

There are many functions in itertools that operate on iterables, in a similar way to map and filter.

Some examples:

takewhile - takes items from an iterable while a predicate function remains true;

chain - combines several iterables into one long one;

accumulate - returns a running total of values in an iterable.

from itertools import accumulate, takewhile

nums = list(accumulate(range(8)))
print(nums)
print(list(takewhile(lambda x: x<= 6, nums)))

Result:

[0, 1, 3, 6, 10, 15, 21, 28]

  [0, 1, 3, 6]

itertools-3

There are also several combinatoric functions in itertool, such as product and permutation.

These are used when you want to accomplish a task with all possible combinations of some items.

Example:

from itertools import product, permutations

letters = ("A", "B")
print(list(product(letters, range(2))))
print(list(permutations(letters)))

Result:

[('A', 0), ('A', 1), ('B', 0), ('B', 1)]

  [('A', 'B'), ('B', 'A')]

Object-Oriented Programming

Classes-1

We have previously looked at two paradigms of programming - imperative (using statements, loops, and functions as subroutines), and functional (using pure functions, higher-order functions, and recursion).

Another very popular paradigm is object**-**oriented programming (OOP).

Objects are created using classes, which are actually the focal point of OOP.

The class describes what the object will be, but is separate from the object itself. In other words, a class can be described as an object's blueprint, description, or definition.

You can use the same class as a blueprint for creating multiple different objects.

Classes are created using the keyword class and an indented block, which contains class methods (which are functions).

Below is an example of a simple class and its objects.

class Cat:
  def __init__(self, color, legs):
    self.color = color
    self.legs = legs

felix = Cat("ginger", 4)
rover = Cat("dog-colored", 4)
stumpy = Cat("brown", 3)

Note: This code defines a class named Cat, which has two attributes: color and legs.

  Then the class is used to create 3 separate objects of that class.

__init__

The init method is the most important method in a class.

This is called when an instance (object) of the class is created, using the class name as a function.

All methods must have self as their first parameter, although it isn't explicitly passed, Python adds the self argument to the list for you; you do not need to include it when you call the methods. Within a method definition, self refers to the instance calling the method.

Instances of a class have attributes, which are pieces of data associated with them.

In this example, Cat instances have attributes color and legs. These can be accessed by putting a dot, and the attribute name after an instance.

In an init method, self.attribute can therefore be used to set the initial value of an instance's attributes.

Example:

class Cat:
  def __init__(self, color, legs):
    self.color = color
    self.legs = legs

felix = Cat("ginger", 4)
print(felix.color)

Result:

Note: ginger

Note: In the example above, the init method takes two arguments and assigns them to the object's attributes. The init method is called the class constructor.

Methods

Classes can have other methods defined to add functionality to them.

Remember, that all methods must have self as their first parameter.

These methods are accessed using the same dot syntax as attributes.

Example:

class Dog:
  def __init__(self, name, color):
    self.name = name
    self.color = color

  def bark(self):
    print("Woof!")

fido = Dog("Fido", "brown")
print(fido.name)
fido.bark()

Result:

Fido

  Woof!

Classes can also have class attributes, created by assigning variables within the body of the class. These can be accessed either from instances of the class, or the class itself.

Example:

class Dog:
  legs = 4
  def __init__(self, name, color):
    self.name = name
    self.color = color

fido = Dog("Fido", "brown")
print(fido.legs)
print(Dog.legs)

Result:

4

  4

NOTE: Class attributes are shared by all instances of the class.

Classes-2

Trying to access an attribute of an instance that isn't defined causes an AttributeError. This also applies when you call an undefined method.

Example:

class Rectangle:
  def __init__(self, width, height):
    self.width = width
    self.height = height

rect = Rectangle(7, 8)
print(rect.color)

Result:

AttributeError: 'Rectangle' object has no attribute 'color'

Inheritance-1

Inheritance provides a way to share functionality between classes.

Imagine several classes, Cat, Dog, Rabbit and so on. Although they may differ in some ways (only Dog might have the method bark), they are likely to be similar in others (all having the attributes color and name).

This similarity can be expressed by making them all inherit from a superclass Animal, which contains the shared functionality.

To inherit a class from another class, put the superclass name in parentheses after the class name.

Example:

class Animal:
  def __init__(self, name, color):
    self.name = name
    self.color = color

class Cat(Animal):
  def purr(self):
    print("Purr...")

class Dog(Animal):
  def bark(self):
    print("Woof!")

fido = Dog("Fido", "brown")
print(fido.color)
fido.bark()

Result:

brown

  Woof!

Inheritance-2

A class that inherits from another class is called a subclass.

A class that is inherited from is called a superclass.

If a class inherits from another with the same attributes or methods, it overrides them.

class Wolf:
  def __init__(self, name, color):
    self.name = name
    self.color = color

  def bark(self):
    print("Grr...")

class Dog(Wolf):
  def bark(self):
    print("Woof")

husky = Dog("Max", "grey")
husky.bark()

Result:

Woof

Note: In the example above, Wolf is the superclass, Dog is the subclass.

Inheritance-3

Inheritance can also be indirect. One class can inherit from another, and that class can inherit from a third class.

Example:

class A:
  def method(self):
    print("A method")

class B(A):
  def another_method(self):
    print("B method")

class C(B):
  def third_method(self):
    print("C method")

c = C()
c.method()
c.another_method()
c.third_method()

Result:

A method

  B method

  C method

Note: However, circular inheritance is not possible.

Inheritance-4

The function super is a useful inheritance-related function that refers to the parent class. It can be used to find the method with a certain name in an object's superclass.

Example:

class A:
  def spam(self):
    print(1)

class B(A):
  def spam(self):
    print(2)
    super().spam()

B().spam()

Result:

2

  1

Note: super().spam() calls the spam method of the superclass.

Magic Methods-1

Magic methods are special methods which have double underscores at the beginning and end of their names.

They are also known as dunders.

So far, the only one we have encountered is __init__, but there are several others.

They are used to create functionality that can't be represented as a normal method.

One common use of them is operator overloading.

This means defining operators for custom classes that allow operators such as + and * to be used on them.

An example magic method is __add__ for +.

class Vector2D:
  def __init__(self, x, y):
    self.x = x
    self.y = y
  def __add__(self, other):
    return Vector2D(self.x + other.x, self.y + other.y)

first = Vector2D(5, 7)
second = Vector2D(3, 9)
result = first + second
print(result.x)
print(result.y)

Result:

8

  16

The __add__ method allows for the definition of a custom behavior for the + operator in our class.

As you can see, it adds the corresponding attributes of the objects and returns a new object, containing the result.

Once it's defined, we can add two objects of the class together.

Magic Methods-2

More magic methods for common operators:

__sub__ for -

__mul__ for *

__truediv__ for /

__floordiv__ for //

__mod__ for %

__pow__ for **

__and__ for &

__xor__ for ^

__or__ for |

The expression x + y is translated into x.__add__(y).

However, if x hasn't implemented __add__, and x and y are of different types, then y.__radd__(x) is called.

There are equivalent r methods for all magic methods just mentioned.

Example:

class SpecialString:
  def __init__(self, cont):
    self.cont = cont

  def __truediv__(self, other):
    line = "=" * len(other.cont)
    return "\n".join([self.cont, line, other.cont])

spam = SpecialString("spam")
hello = SpecialString("Hello world!")
print(spam / hello)

Result:

spam
============
Hello world!

Note: In the example above, we defined the division operation for our class SpecialString.

Magic Methods-3

Python also provides magic methods for comparisons.

__lt__ for <

__le__ for <=

__eq__ for ==

__ne__ for !=

__gt__ for >

__ge__ for >=

If __ne__ is not implemented, it returns the opposite of __eq__.

Note: There are no other relationships between the other operators.

Example:

class SpecialString:
  def __init__(self, cont):
    self.cont = cont

  def __gt__(self, other):
    for index in range(len(other.cont)+1):
      result = other.cont[:index] + ">" + self.cont
      result += ">" + other.cont[index:]
      print(result)

spam = SpecialString("spam")
eggs = SpecialString("eggs")
spam > eggs

Result:

>spam>eggs
e>spam>ggs
eg>spam>gs
egg>spam>s
eggs>spam>

Note: As you can see, you can define any custom behavior for the overloaded operators.

Magic Methods-4

There are several magic methods for making classes act like containers.

__len__ for len()

__getitem__ for indexing

__setitem__ for assigning to indexed values

__delitem__ for deleting indexed values

__iter__ for iteration over objects (e.g., in for loops)

__contains__ for in

There are many other magic methods that we won't cover here, such as __call__ for calling objects as functions, and __int__, __str__, and the like, for converting objects to built-in types.

Example:

import random

class VagueList:
  def __init__(self, cont):
    self.cont = cont

  def __getitem__(self, index):
    return self.cont[index + random.randint(-1, 1)]

  def __len__(self):
    return random.randint(0, len(self.cont)*2)

vague_list = VagueList(["A", "B", "C", "D", "E"])
print(len(vague_list))
print(len(vague_list))
print(vague_list[2])
print(vague_list[2])

Result:

6

  7

  D

  C

Note: We have overridden the len() function for the class VagueList to return a random number.

The indexing function also returns a random item in a range from the list, based on the expression.

Object Lifecycle-1

The lifecycle of an object is made up of its creation, manipulation, and destruction.

The first stage of the life-cycle of an object is the definition of the class to which it belongs.

The next stage is the instantiation of an instance, when __init__ is called. Memory is allocated to store the instance. Just before this occurs, the __new__ method of the class is called. This is usually overridden only in special cases.

Note: After this has happened, the object is ready to be used. Other code can then interact with the object, by calling functions on

  it and accessing its attributes.  Eventually, it will finish being

  used, and can be destroyed.

Object Lifecycle-2

When an object is destroyed, the memory allocated to it is freed up, and can be used for other purposes.

Destruction of an object occurs when its reference count reaches zero. Reference count is the number of variables and other elements that refer to an object.

If nothing is referring to it (it has a reference count of zero) nothing can interact with it, so it can be safely deleted.

In some situations, two (or more) objects can be referred to by each other only, and therefore can be deleted as well.

The del statement reduces the reference count of an object by one, and this often leads to its deletion.

The magic method for the del statement is __del__.

The process of deleting objects when they are no longer needed is called garbage collection.

In summary, an object's reference count increases when it is assigned a new name or placed in a container (list, tuple, or dictionary). The object's reference count decreases when it's deleted with del, its reference is reassigned, or its reference goes out of scope. When an object's reference count reaches zero, Python automatically deletes it.

Example:

a = 42  # Create object <42>
b = a  # Increase ref. count  of <42>
c = [a]  # Increase ref. count  of <42>

del a  # Decrease ref. count  of <42>
b = 100  # Decrease ref. count  of <42>
c[0] = -1  # Decrease ref. count  of <42>

Note: Lower level languages like C don't have this kind of automatic memory management.

Data Hiding-1

A key part of object-oriented programming is encapsulation, which involves packaging of related variables and functions into a single easy-to-use object - an instance of a class.

A related concept is data hiding, which states that implementation details of a class should be hidden, and a clean standard interface be presented for those who want to use the class.

In other programming languages, this is usually done with private methods and attributes, which block external access to certain methods and attributes in a class.

The Python philosophy is slightly different. It is often stated as "we are all consenting adults here", meaning that you shouldn't put arbitrary restrictions on accessing parts of a class. Hence there are no ways of enforcing a method or attribute be strictly private.

Note: However, there are ways to discourage people from accessing parts of a class, such as by denoting that it is an implementation

  detail, and should be used at their own risk.

Data Hiding-2

Weakly private methods and attributes have a single underscore at the beginning.

This signals that they are private, and shouldn't be used by external code. However, it is mostly only a convention, and does not stop external code from accessing them.

Its only actual effect is that from module_name import * won't import variables that start with a single underscore.

Example:

class Queue:
  def __init__(self, contents):
    self._hiddenlist = list(contents)

  def push(self, value):
    self._hiddenlist.insert(0, value)

  def pop(self):
    return self._hiddenlist.pop(-1)

  def __repr__(self):
    return "Queue({})".format(self._hiddenlist)

queue = Queue([1, 2, 3])
print(queue)
queue.push(0)
print(queue)
queue.pop()
print(queue)
print(queue._hiddenlist)

Result:

Queue([1, 2, 3])

  Queue([0, 1, 2, 3])

  Queue([0, 1, 2])

  [0, 1, 2]

Note: In the code above, the attribute _hiddenlist is marked as private, but it can still be accessed in the outside code.

The __repr__ magic method is used for string representation of the instance.

Data Hiding-3

Strongly private methods and attributes have a double underscore at the beginning of their names. This causes their names to be mangled, which means that they can't be accessed from outside the class.

The purpose of this isn't to ensure that they are kept private, but to avoid bugs if there are subclasses that have methods or attributes with the same names.

Name mangled methods can still be accessed externally, but by a different name. The method __privatemethod of class Spam could be accessed externally with _Spam__privatemethod.

Example:

class Spam:
  __egg = 7
  def print_egg(self):
    print(self.__egg)

s = Spam()
s.print_egg()
print(s._Spam__egg)
print(s.__egg)

Result:

7

  7

  AttributeError: 'Spam' object has no attribute '__egg'

Note: Basically, Python protects those members by internally changing the name to include the class name.

Class Methods

Methods of objects we've looked at so far are called by an instance of a class, which is then passed to the self parameter of the method.

Class methods are different - they are called by a class, which is passed to the cls parameter of the method.

A common use of these are factory methods, which instantiate an instance of a class, using different parameters than those usually passed to the class constructor.

Class methods are marked with a classmethod decorator.

Example:

class Rectangle:
  def __init__(self, width, height):
    self.width = width
    self.height = height

  def calculate_area(self):
    return self.width * self.height

  @classmethod
  def new_square(cls, side_length):
    return cls(side_length, side_length)

square = Rectangle.new_square(5)
print(square.calculate_area())

Result:

25

new_square is a class method and is called on the class, rather than on an instance of the class. It returns a new object of the class cls.

Technically, the parameters self and cls are just conventions; they could be changed to anything else. However, they are universally followed, so it is wise to stick to using them.

Static Methods

Static methods are similar to class methods, except they don't receive any additional arguments; they are identical to normal functions that belong to a class.

They are marked with the staticmethod decorator.

Example:

class Pizza:
  def __init__(self, toppings):
    self.toppings = toppings

  @staticmethod
  def validate_topping(topping):
    if topping == "pineapple":
      raise ValueError("No pineapples!")
    else:
      return True

ingredients = ["cheese", "onions", "spam"]
if all(Pizza.validate_topping(i) for i in ingredients):
  pizza = Pizza(ingredients)

Note: Static methods behave like plain functions, except for the fact that you can call them from an instance of the class.

Properties-1

Properties provide a way of customizing access to instance attributes.

They are created by putting the property decorator above a method, which means when the instance attribute with the same name as the method is accessed, the method will be called instead.

One common use of a property is to make an attribute read-only.

Example:

class Pizza:
  def __init__(self, toppings):
    self.toppings = toppings

  @property
  def pineapple_allowed(self):
    return False

pizza = Pizza(["cheese", "tomato"])
print(pizza.pineapple_allowed)
pizza.pineapple_allowed = True

Result:

False

AttributeError: can't set attribute

Properties-2

Properties can also be set by defining setter/getter functions.

The setter function sets the corresponding property's value.

The getter gets the value.

To define a setter, you need to use a decorator of the same name as the property, followed by a dot and the setter keyword.

The same applies to defining getter functions.

Example:

class Pizza:
  def __init__(self, toppings):
    self.toppings = toppings
    self._pineapple_allowed = False

  @property
  def pineapple_allowed(self):
    return self._pineapple_allowed

  @pineapple_allowed.setter
  def pineapple_allowed(self, value):
    if value:
      password = input("Enter the password: ")
      if password == "Sw0rdf1sh!":
        self._pineapple_allowed = value
      else:
        raise ValueError("Alert! Intruder!")

pizza = Pizza(["cheese", "tomato"])
print(pizza.pineapple_allowed)
pizza.pineapple_allowed = True
print(pizza.pineapple_allowed)

Result:

False

  Enter the password to permit pineapple: Sw0rdf1sh!

  True

A Simple Game

Object-orientation is very useful when managing different objects and their relations. That is especially useful when you are developing games with different characters and features.

Let's look at an example project that shows how classes are used in game development.

The game to be developed is an old fashioned text-based adventure game.

Below is the function handling input and simple parsing.

def get_input():
  command = input(": ").split()
  verb_word = command[0]
  if verb_word in verb_dict:
    verb = verb_dict[verb_word]
  else:
    print("Unknown verb {}". format(verb_word))
    return

  if len(command) >= 2:
    noun_word = command[1]
    print (verb(noun_word))
  else:
    print(verb("nothing"))

def say(noun):
  return 'You said "{}"'.format(noun)

verb_dict = {
  "say": say,
}

while True:
  get_input()

Result:

: say Hello!
You said "Hello!"
: say Goodbye!
You said "Goodbye!"

: test
Unknown verb test

Note: The code above takes input from the user, and tries to match the first word with a command in verb_dict. If a match is found, the

  corresponding function is called.

The next step is to use classes to represent game objects.

class GameObject:
  class_name = ""
  desc = ""
  objects = {}

  def __init__(self, name):
    self.name = name
    GameObject.objects[self.class_name] = self

  def get_desc(self):
    return self.class_name + "\n" + self.desc

class Goblin(GameObject):
  class_name = "goblin"
  desc = "A foul creature"

goblin = Goblin("Gobbly")

def examine(noun):
  if noun in GameObject.objects:
    return GameObject.objects[noun].get_desc()
  else:
    return "There is no {} here.".format(noun)

We created a Goblin class, which inherits from the GameObjects class.

We also created a new function examine, which returns the objects description.

Now we can add a new "examine" verb to our dictionary and try it out!

verb_dict = {
  "say": say,
  "examine": examine,
}

Combine this code with the one in our previous example, and run the program.

>>>
: say Hello!
You said "Hello!"

: examine goblin
goblin
A foul creature

: examine elf
There is no elf here.
:

This code adds more detail to the Goblin class and allows you to fight goblins.

class Goblin(GameObject):
  def __init__(self, name):
    self.class_name = "goblin"
    self.health = 3
    self._desc = " A foul creature"
    super().__init__(name)

  @property
  def desc(self):
    if self.health >=3:
      return self._desc
    elif self.health == 2:
      health_line = "It has a wound on its knee."
    elif self.health == 1:
      health_line = "Its left arm has been cut off!"
    elif self.health <= 0:
      health_line = "It is dead."
    return self._desc + "\n" + health_line

  @desc.setter
  def desc(self, value):
    self._desc = value

def hit(noun):
  if noun in GameObject.objects:
    thing = GameObject.objects[noun]
    if type(thing) == Goblin:
      thing.health = thing.health - 1
      if thing.health <= 0:
        msg = "You killed the goblin!"
      else:
        msg = "You hit the {}".format(thing.class_name)
  else:
    msg ="There is no {} here.".format(noun)
  return msg

Result:

>>>
: hit goblin
You hit the goblin

: examine goblin
goblin
 A foul creature
It has a wound on its knee.

: hit goblin
You hit the goblin

: hit goblin
You killed the goblin!

: examine goblin
A goblin

goblin
 A foul creature
It is dead.
:

Note: This was just a simple sample. You could create different classes

  (e.g., elves, orcs, humans), fight them, make them fight each other,

  and so on.


text:
<?xml version="1.0" encoding="iso-8859-1"?>

<rss version="2.0" >
<channel>
<item>

<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
<comments>http://example.org</comments>
<title>test</title>

<category domain="foo">bar</category>
<description><![CDATA[I'm headed for France. I wasn't gonna go this year, but then last week Valley Girl came out and I said to myself, Joe Bob, you gotta get out of the country for a while.]]></description>
</item>
</channel>
</rss>

redpajama_set_name: RedPajamaGithub


text:
module.exports = function isBuffer(arg) {
  return arg && typeof arg === 'object'
    && typeof arg.copy === 'function'
    && typeof arg.fill === 'function'
    && typeof arg.readUInt8 === 'function';
}


text:
Tested on CentOS 6.5

### Usage
```bash
$ ansible-playbook -i hosts selenium.yml
```
without chromedriver and phantomjs:
```bash
$ ansible-playbook -i hosts selenium.yml --extra-vars "with_chromedriver=false with_phantomjs=false"
```


text:
import argparse
import os.path
import re
import sys

from . import Grammar

argp = argparse.ArgumentParser(description="Generate a testcase from a grammar")
argp.add_argument("input", type=argparse.FileType('r'), help="Input grammar definition")
argp.add_argument("output", type=argparse.FileType('w'), nargs="?", default=sys.stdout, help="Output testcase")
argp.add_argument("-f", "--function", action="append", nargs=2, help="Function used in the grammar (eg. -f filter lambda x:x.replace('x','y')", default=[])
args = argp.parse_args()
args.function = {func: eval(defn) for (func, defn) in args.function}
args.output.write(Grammar(args.input.read(), path=os.path.dirname(args.input.name), **args.function).generate())


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework.Input;

namespace EmptyKeys.UserInterface.Input
{
    /// <summary>
    /// Implements MonoGame specific mouse state
    /// </summary>
    public class MonoGameMouseState : MouseStateBase
    {
        private MouseState state;

        /// <summary>
        /// Gets a value indicating whether this instance is left button pressed.
        /// </summary>
        /// <value>
        /// <c>true</c> if this instance is left button pressed; otherwise, <c>false</c>.
        /// </value>
        public override bool IsLeftButtonPressed
        {
            get { return state.LeftButton == ButtonState.Pressed; }
        }

        /// <summary>
        /// Gets a value indicating whether this instance is middle button pressed.
        /// </summary>
        /// <value>
        /// <c>true</c> if this instance is middle button pressed; otherwise, <c>false</c>.
        /// </value>
        public override bool IsMiddleButtonPressed
        {
            get { return state.MiddleButton == ButtonState.Pressed; }
        }

        /// <summary>
        /// Gets a value indicating whether this instance is right button pressed.
        /// </summary>
        /// <value>
        /// <c>true</c> if this instance is right button pressed; otherwise, <c>false</c>.
        /// </value>
        public override bool IsRightButtonPressed
        {
            get { return state.RightButton == ButtonState.Pressed; }
        }

        /// <summary>
        /// Gets the normalized x.
        /// </summary>
        /// <value>
        /// The normalized x.
        /// </value>
        public override float NormalizedX
        {
            get
            {
                float width = Engine.Instance.Renderer.NativeScreenWidth;
                return state.Position.X / width;
            }
        }

        /// <summary>
        /// Gets the normalized y.
        /// </summary>
        /// <value>
        /// The normalized y.
        /// </value>
        public override float NormalizedY
        {
            get
            {
                float height = Engine.Instance.Renderer.NativeScreenHeight;
                return state.Position.Y / height;
            }
        }

        /// <summary>
        /// Gets the scroll wheel value.
        /// </summary>
        /// <value>
        /// The scroll wheel value.
        /// </value>
        public override int ScrollWheelValue
        {
            get { return state.ScrollWheelValue; }
        }

        /// <summary>
        /// Gets or sets a value indicating whether mouse is visible.
        /// </summary>
        /// <value>
        ///   <c>true</c> if mouse is visible; otherwise, <c>false</c>.
        /// </value>
        public override bool IsVisible
        {
            get
            {
                return false;
            }
            set
            {
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="MonoGameMouseState"/> class.
        /// </summary>
        public MonoGameMouseState()
            : base()
        {
        }

        /// <summary>
        /// Sets the position.
        /// </summary>
        /// <param name="x">The x.</param>
        /// <param name="y">The y.</param>
        public override void SetPosition(int x, int y)
        {
            Microsoft.Xna.Framework.Input.Mouse.SetPosition(x, y);
        }

        /// <summary>
        /// Updates this instance.
        /// </summary>
        public override void Update()
        {
            state = Microsoft.Xna.Framework.Input.Mouse.GetState();
        }
    }
}


text:
/**
 * Very simple specialization of Ext.Img, just saves the apod.model.Picture that was assigned to it
 */
Ext.define('apod.view.Picture', {
    extend: 'Ext.Img',
    xtype: 'apodimage',

    config: {
        /**
         * @cfg {apod.model.Picture} picture The Picture to show
         */
        picture: null
    },

    updatePicture: function(picture) {
        this.setSrc(picture.get('image') + '&width=' + window.innerWidth +'&height=' + window.innerHeight);
    }
});


text:
/**
 * @fileoverview Generating Lua for dynamic variable blocks.
 */
'use strict';

goog.module('Blockly.Lua.variablesDynamic');

const Lua = goog.require('Blockly.Lua');
/** @suppress {extraRequire} */
goog.require('Blockly.Lua.variables');

// Lua is dynamically typed.
Lua['variables_get_dynamic'] = Lua['variables_get'];
Lua['variables_set_dynamic'] = Lua['variables_set'];


text:
try:
    from asyncio import get_running_loop
except ImportError:  # pragma: no cover
    from asyncio import get_event_loop as get_running_loop  # Python 3.6 compatibility

import re
import os

from ppadb.command.transport_async import TransportAsync
from ppadb.sync_async import SyncAsync

def _get_src_info(src):
    exists = os.path.exists(src)
    isfile = os.path.isfile(src)
    isdir = os.path.isdir(src)
    basename = os.path.basename(src)
    walk = None if not isdir else list(os.walk(src))

    return exists, isfile, isdir, basename, walk

class DeviceAsync(TransportAsync):
    INSTALL_RESULT_PATTERN = "(Success|Failure|Error)\s?(.*)"
    UNINSTALL_RESULT_PATTERN = "(Success|Failure.*|.*Unknown package:.*)"

    def __init__(self, client, serial):
        self.client = client
        self.serial = serial

    async def create_connection(self, set_transport=True, timeout=None):
        conn = await self.client.create_connection(timeout=timeout)

        if set_transport:
            await self.transport(conn)

        return conn

    async def _push(self, src, dest, mode, progress):
        # Create a new connection for file transfer
        sync_conn = await self.sync()
        sync = SyncAsync(sync_conn)

        async with sync_conn:
            await sync.push(src, dest, mode, progress)

    async def push(self, src, dest, mode=0o644, progress=None):
        exists, isfile, isdir, basename, walk = await get_running_loop().run_in_executor(None, _get_src_info, src)
        if not exists:
            raise FileNotFoundError("Cannot find {}".format(src))

        if isfile:
            await self._push(src, dest, mode, progress)

        elif isdir:
            for root, dirs, files in walk:
                root_dir_path = os.path.join(basename, root.replace(src, ""))

                await self.shell("mkdir -p {}/{}".format(dest, root_dir_path))

                for item in files:
                    await self._push(os.path.join(root, item), os.path.join(dest, root_dir_path, item), mode, progress)

    async def pull(self, src, dest):
        sync_conn = await self.sync()
        sync = SyncAsync(sync_conn)

        async with sync_conn:
            return await sync.pull(src, dest)


text:
package com.btoddb.fastpersitentqueue;

import com.btoddb.fastpersitentqueue.exceptions.FpqException;
import com.eaio.uuid.UUID;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 *
 */
public class JournalMgr {
    private static final Logger logger = LoggerFactory.getLogger(JournalMgr.class);

    private File directory;
    private long flushPeriodInMs = 10000;
    private int numberOfFlushWorkers = 4;
    private int numberOfGeneralWorkers = 2;
    private long maxJournalFileSize = 100000000L;
    private long maxJournalDurationInMs = (10 * 60 * 1000); // 10 minutes

    private volatile boolean shutdownInProgress;
    private long journalsLoadedAtStartup;
    private AtomicLong journalsCreated = new AtomicLong();
    private AtomicLong journalsRemoved = new AtomicLong();
    private AtomicLong numberOfEntries = new AtomicLong();

    private volatile JournalDescriptor currentJournalDescriptor;

    ReentrantReadWriteLock journalLock = new ReentrantReadWriteLock();
    private TreeMap<UUID, JournalDescriptor> journalIdMap = new TreeMap<UUID, JournalDescriptor>(new Comparator<UUID>() {
        @Override
        public int compare(UUID uuid, UUID uuid2) {
            return uuid.compareTo(uuid2);
        }
    });

    private ScheduledThreadPoolExecutor flushExec;
    private ExecutorService generalExec;

    /**
     *
     * @throws IOException
     */
    public void init() throws IOException {
        flushExec = new ScheduledThreadPoolExecutor(numberOfFlushWorkers,
                                                    new ThreadFactory() {
                                                        @Override
                                                        public Thread newThread(Runnable runnable) {
                                                            Thread t = new Thread(runnable);
                                                            t.setName("FPQ-FSync");
                                                            return t;
                                                        }
                                                    });
        generalExec = Executors.newFixedThreadPool(numberOfGeneralWorkers,
                                                    new ThreadFactory() {
                                                        @Override
                                                        public Thread newThread(Runnable runnable) {
                                                            Thread t = new Thread(runnable);
                                                            t.setName("FPQ-GeneralWork");
                                                            return t;
                                                        }
                                                    });

        prepareJournaling();

        currentJournalDescriptor = createAndAddNewJournal();
    }

    private void prepareJournaling() throws IOException {
        FileUtils.forceMkdir(directory);
        Collection<File> files = FileUtils.listFiles(directory, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
        if (null == files || 0 == files.size()) {
            logger.info("no previous journal files found");
            return;
        }

        logger.info("loading journal descriptors");
        numberOfEntries.set(0);
        for (File f : files) {
            JournalFile jf = new JournalFile(f);
            jf.initForReading();
            jf.close();

            JournalDescriptor jd = new JournalDescriptor(jf);
            jd.setWritingFinished(true);
            jd.adjustEntryCount(jf.getNumberOfEntries());
            journalIdMap.put(jd.getId(), jd);
            numberOfEntries.addAndGet(jf.getNumberOfEntries());
            logger.info("loaded descriptor, {}, with {} entries", jd.getId(), jd.getNumberOfUnconsumedEntries());
            journalsLoadedAtStartup ++;
        }

        logger.info("completed journal descriptor loading.  found a total of {} entries", numberOfEntries.get());
    }

    public JournalReplayIterable createReplayIterable() throws IOException {
        return new JournalReplayIterable();
    }

    private JournalDescriptor createAndAddNewJournal() throws IOException {
        UUID uid = new UUID();
        String fn = createNewJournalName(uid.toString());
        return addNewJournalToIdMap(uid, fn);
    }

    private JournalDescriptor addNewJournalToIdMap(UUID id, String fn) throws IOException {
        JournalFile jf = new JournalFile(new File(directory, fn));
        jf.initForWriting(id);

        // this could possibly create a race, if the flushPeriodInMs is very very low ;)
        ScheduledFuture future = flushExec.scheduleWithFixedDelay(new FlushRunner(jf), flushPeriodInMs, flushPeriodInMs, TimeUnit.MILLISECONDS);
        JournalDescriptor jd = new JournalDescriptor(id, jf, future);
        journalLock.writeLock().lock();
        try {
            journalIdMap.put(id, jd);
        }
        finally {
            journalLock.writeLock().unlock();
        }

        journalsCreated.incrementAndGet();
        logger.debug("new journal created : {}", jd.getId());
        return jd;
    }

    public FpqEntry append(FpqEntry entry) throws IOException {
        append(Collections.singleton(entry));
        return entry;
    }

    public Collection<FpqEntry> append(Collection<FpqEntry> events) throws IOException {
        if (shutdownInProgress) {
            throw new FpqException("FPQ has been shutdown or is in progress, cannot append");
        }

        // TODO:BTB - optimize this by calling file.append() with collection of data
        List<FpqEntry> entryList = new ArrayList<FpqEntry>(events.size());
        for (FpqEntry entry : events) {
            // TODO:BTB - could use multiple journal files to prevent lock contention - each thread in an "append" pool gets one?
            boolean appended = false;
            while (!appended) {
                JournalDescriptor desc = getCurrentJournalDescriptor();
                if (null == desc) {
                    Utils.logAndThrow(logger, String.format("no current journal descriptor.  did you call %s.init()?", this.getClass().getSimpleName()));
                }
                synchronized (desc) {
                    if (!desc.isWritingFinished()) {
                        desc.getFile().append(entry);
                        entry.setJournalId(desc.getId());
                        entryList.add(entry);

                        if (0 >= desc.getStartTime()) {
                            desc.setStartTime(System.currentTimeMillis());
                        }
                        desc.adjustEntryCount(1);

                        rollJournalIfNeeded();
                        appended = true;
                    }
                }
            }
        }

        numberOfEntries.addAndGet(entryList.size());

        return entryList;
    }

    // this method must be synchronized from above
    private void rollJournalIfNeeded() throws IOException {
        if ( !currentJournalDescriptor.isAnyWritesHappened()) {
            return;
        }

        long fileLength = currentJournalDescriptor.getFile().getFilePosition();
        if (fileLength >= maxJournalFileSize ||
                (0 < fileLength && (currentJournalDescriptor.getStartTime()+maxJournalDurationInMs) < System.currentTimeMillis())) {
            currentJournalDescriptor.setWritingFinished(true);
            currentJournalDescriptor.getFuture().cancel(false);
            currentJournalDescriptor.getFile().close();
            currentJournalDescriptor = createAndAddNewJournal();
        }

    }

    public void reportTake(FpqEntry entry) throws IOException {
        reportTake(Collections.singleton(entry));
    }

    public void reportTake(Collection<FpqEntry> entries) throws IOException {
        if (shutdownInProgress) {
            throw new FpqException("FPQ has been shutdown or is in progress, cannot report TAKE");
        }

        if (null == entries || entries.isEmpty()) {
            logger.debug("provided null or empty collection - ignoring");
            return;
        }

        Map<UUID, Integer> journalIds = new HashMap<UUID, Integer>();
        for (FpqEntry entry : entries) {
            Integer count = journalIds.get(entry.getJournalId());
            if (null == count) {
                count = 0;
            }
            journalIds.put(entry.getJournalId(), count + 1);
        }

        for (Map.Entry<UUID, Integer> entry : journalIds.entrySet()) {
            journalLock.readLock().lock();
            JournalDescriptor desc;
            try {
                desc = journalIdMap.get(entry.getKey());
            }
            finally {
                journalLock.readLock().unlock();
            }

            if (null == desc) {
                logger.error("illegal state - reported consumption of journal entry, but journal descriptor, {}, doesn't exist!", entry.getKey());
                continue;
            }

            long remaining = desc.adjustEntryCount(-entry.getValue());

            // this is therad-safe, because only one thread can decrement down to zero when isWritingFinished
            if (0 == remaining && desc.isWritingFinished()) {
                submitJournalRemoval(desc);
            }
        }
    }

    private void submitJournalRemoval(final JournalDescriptor desc) {
        logger.debug("submitting journal, {}, for removal", desc.getId());
        generalExec.submit(new Runnable() {
            @Override
            public void run() {
                removeJournal(desc);
            }
        });
    }

    private void removeJournal(JournalDescriptor desc) {
        journalLock.writeLock().lock();
        try {
            journalIdMap.remove(desc.getId());
            try {
                FileUtils.forceDelete(desc.getFile().getFile());
            }
            catch (IOException e) {
                logger.error("could not delete journal file, {} - will not try again", desc.getFile().getFile().getAbsolutePath());
            }
        }
        finally {
            journalLock.writeLock().unlock();
        }

        numberOfEntries.addAndGet(-desc.getFile().getNumberOfEntries());
        journalsRemoved.incrementAndGet();
        logger.debug("journal, {}, removed", desc.getId());
    }

    public void shutdown() {
        shutdownInProgress = true;
        if (null != flushExec) {
            flushExec.shutdown();
            try {
                flushExec.awaitTermination(60, TimeUnit.SECONDS);
            }
            catch (InterruptedException e) {
                Thread.interrupted();
                // ignore
            }
        }
        if (null != generalExec) {
            generalExec.shutdown();
            try {
                generalExec.awaitTermination(60, TimeUnit.SECONDS);
            }
            catch (InterruptedException e) {
                Thread.interrupted();
                // ignore
            }
        }

        // for journals that are completely popped, but not removed (because a client still could have pushed)
        Set<JournalDescriptor> removeThese = new HashSet<>();
        try {
            for (JournalDescriptor desc : journalIdMap.values()) {
                if (0 == desc.getNumberOfUnconsumedEntries()) {
                    removeThese.add(desc);
                }
                else if (desc.getFile().isOpen()) {
                    try {
                        desc.getFile().forceFlush();
                    }
                    catch (IOException e) {
                        logger.error("on shutdown - could not fsync journal file, {} -- ignoring", desc.getFile().getFile().getAbsolutePath());
                    }
                }
            }
        }
        finally {
            for (JournalDescriptor desc : removeThese) {
                removeJournal(desc);
            }
        }
    }

    private String createNewJournalName(String id) {
        return "journal-"+id;
    }

    public JournalDescriptor getCurrentJournalDescriptor() {
        return currentJournalDescriptor;
    }

    public long getFlushPeriodInMs() {
        return flushPeriodInMs;
    }

    public void setFlushPeriodInMs(long flushPeriodInMs) {
        this.flushPeriodInMs = flushPeriodInMs;
    }

    public File getDirectory() {
        return directory;
    }

    public void setDirectory(File directory) {
        this.directory = directory;
    }

    public Map<UUID, JournalDescriptor> getJournalFiles() {
        return journalIdMap;
    }

    public int getNumberOfFlushWorkers() {
        return numberOfFlushWorkers;
    }

    public void setNumberOfFlushWorkers(int numberOfFlushWorkers) {
        this.numberOfFlushWorkers = numberOfFlushWorkers;
    }

    public long getMaxJournalFileSize() {
        return maxJournalFileSize;
    }

    public void setMaxJournalFileSize(long maxJournalFileSize) {
        this.maxJournalFileSize = maxJournalFileSize;
    }

    public long getMaxJournalDurationInMs() {
        return maxJournalDurationInMs;
    }

    public void setMaxJournalDurationInMs(long journalMaxDurationInMs) {
        this.maxJournalDurationInMs = journalMaxDurationInMs;
    }

    public long getJournalsCreated() {
        return journalsCreated.get();
    }

    public long getJournalsRemoved() {
        return journalsRemoved.get();
    }

    public TreeMap<UUID, JournalDescriptor> getJournalIdMap() {
        return journalIdMap;
    }

    public long getNumberOfEntries() {
        return numberOfEntries.get();
    }

    public long getJournalsLoadedAtStartup() {
        return journalsLoadedAtStartup;
    }

    // ------------

    public class JournalReplayIterable implements Iterator<FpqEntry>, Iterable<FpqEntry> {
        private Iterator<JournalDescriptor> jdIter = journalIdMap.values().iterator();
        private Iterator<FpqEntry> entryIter = null;
        private JournalDescriptor jd = null;

        public JournalReplayIterable() throws IOException {
            advanceToNextJournalFile();
        }

        @Override
        public Iterator<FpqEntry> iterator() {
            return this;
        }

        @Override
        public boolean hasNext() {
            // if no descriptor, then we are done
            if (null == entryIter) {
                return false;
            }

            if (!entryIter.hasNext()) {
                try {
                    jd.getFile().close();
                    advanceToNextJournalFile();
                }
                catch (IOException e) {
                    logger.error("exception while closing journal file", e);
                }
            }

            return null != entryIter && entryIter.hasNext();
        }

        @Override
        public FpqEntry next() {
            if (hasNext()) {
                return entryIter.next();
            }
            else {
                throw new NoSuchElementException();
            }
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException(JournalMgr.class.getName() + " does not support remove");
        }

        private void advanceToNextJournalFile() throws IOException {
            while (jdIter.hasNext()) {
                jd = jdIter.next();
                if (jd.isWritingFinished()) {
                    entryIter = jd.getFile().iterator();
                    return;
                }
                else {
                    logger.debug("trying to replay a journal that is not 'write finished' : " + jd.getId());
                }
            }
            jd = null;
            entryIter = null;
        }

        public void close() throws IOException {
            if (null != jd) {
                jd.getFile().close();
            }
        }
    }
}


text:
Tekton Triggers follows the Tekton community [release policy][release-policy]
as follows:

- Versions are numbered according to semantic versioning: `vX.Y.Z`
- A new release is produced on a monthly basis, when enough content is available
- Four releases a year are chosen for [long term support (LTS)](https://github.com/tektoncd/community/blob/main/releases.md#support-policy).
  All remaining releases are supported for approximately 1 month (until the next
  release is produced)
    - LTS releases take place in January, April, July and October every year
    - The first Tekton Triggers LTS release will be **v0.22.0** in October 2022
    - Releases usually happen towards the middle of the month, but the exact date
      may vary, depending on week-ends and readiness

Tekton Triggers produces nightly builds, publicly available on
`gcr.io/tekton-nightly`.

### Transition Process

Before release v0.22 Tekton Triggers has worked on the basis of an undocumented
support period of four months, which will be maintained for the release v0.21.

## Release Process

Tekton Triggers releases are made of YAML manifests and container images.
Manifests are published to cloud object-storage as well as
[GitHub][tekton-triggers-releases]. Container images are signed by
[Sigstore][sigstore] via [Tekton Chains][tekton-chains]; signatures can be
verified through the [public key][chains-public-key] hosted by the Tekton Chains
project.

Further documentation available:

- The Tekton Triggers [release process][tekton-releases-docs]
- [Installing Tekton][tekton-installation]
- Standard for [release notes][release-notes-standards]

## Releases

### v0.21

- **Latest Release**: [v0.21.0][v0-21-0] (2022-09-06) ([docs][v0-21-0-docs], [examples][v0-21-0-examples])
- **Initial Release**: [v0.21.0][v0-21-0] (2022-09-06)
- **End of Life**: 2023-01-05
- **Patch Releases**: [v0.21.0][v0-21-0]

## End of Life Releases

Older releases are EOL and available on [GitHub][tekton-triggers-releases].

[release-policy]: https://github.com/tektoncd/community/blob/main/releases.md
[sigstore]: https://sigstore.dev
[tekton-chains]: https://github.com/tektoncd/chains
[tekton-triggers-releases]: https://github.com/tektoncd/triggers/releases
[chains-public-key]: https://github.com/tektoncd/chains/blob/main/tekton.pub
[tekton-releases-docs]: tekton/README.md
[tekton-installation]: docs/install.md
[release-notes-standards]:
    https://github.com/tektoncd/community/blob/main/standards.md#release-notes

[v0-21-0]: https://github.com/tektoncd/triggers/releases/tag/v0.21.0

[v0-21-0-docs]: https://github.com/tektoncd/triggers/tree/v0.21.0/docs#tekton-triggers

[v0-21-0-examples]: https://github.com/tektoncd/triggers/tree/v0.21.0/examples#examples


text:
{% extends "base.html" %}

{% block content %}
{% include 'profile-tabs-snippet.html' with author=user %}

You are about to delete your folder {{ folder.name }}.  Are you sure that you want to do this?  All submissions in the folder are safe; this folder will simply be removed from their list of folders.

    <form method="post">
        {% csrf_token %}

<button class="btn btn-danger" type="submit"> Delete folder</button>

No, take me back

    </form>

Folder contents

        {% for submission in folder.submissions.all %}

                    {% include 'submission-list-snippet.html' with submission=submission author=submission.owner %}

        {% endfor %}

{% endblock %}


text:
<?php
class Sales_InvoiceapproveController extends Zend_Controller_Action
{

    public function init()
    {
    	defined('BASE_URL')	|| define('BASE_URL', Zend_Controller_Front::getInstance()->getBaseUrl());
    	$tr = Application_Form_FrmLanguages::getCurrentlanguage();
    }
    protected function GetuserInfoAction(){
    	$user_info = new Application_Model_DbTable_DbGetUserInfo();
    	$result = $user_info->getUserInfo();
    	return $result;
    }
   	public function indexAction()
	{
		if($this->getRequest()->isPost()){
			$search = $this->getRequest()->getPost();
			$search['start_date']=date("Y-m-d",strtotime($search['start_date']));
			$search['end_date']=date("Y-m-d",strtotime($search['end_date']));
		}
		else{
			$search =array(
					'text_search'=>'',
					'start_date'=>date("Y-m-d"),
					'end_date'=>date("Y-m-d"),
					'branch_id'=>-1,
					'customer_id'=>-1,
					);
		}
		$db = new Sales_Model_DbTable_Dbsalesapprov();
		$rows = $db->getAllSaleOrder($search);
		$columns=array("BRANCH_NAME","CUSTOMER_NAME","SALE_AGENT","SALE_NO", "ORDER_DATE",
				"CURRNECY_TYPE","TOTAL","DISCOUNT","TOTAL_AMOUNT","APPROVED_STATUS","PENDING_STATUS","BY_USER");
		/*$link=array(
				'module'=>'sales','controller'=>'salesapprove','action'=>'add',
		);*/
		$link=array(
				'module'=>'sales','controller'=>'invoiceapprove','action'=>'add',
		);

		$list = new Application_Form_Frmlist();
		$this->view->list=$list->getCheckList(0, $columns, $rows, array('branch_name'=>$link,'customer_name'=>$link,'staff_name'=>$link,'sale_no'=>$link));
		$formFilter = new Sales_Form_FrmSearch();
		$this->view->formFilter = $formFilter;
	    Application_Model_Decorator::removeAllDecorator($formFilter);

		/*if($this->getRequest()->isPost()){
			$search = $this->getRequest()->getPost();
			$search['start_date']=date("Y-m-d",strtotime($search['start_date']));
			$search['end_date']=date("Y-m-d",strtotime($search['end_date']));
		}
		else{
			$search =array(
					'text_search'=>'',
					'start_date'=>date("Y-m-d"),
					'end_date'=>date("Y-m-d"),
					'branch_id'=>-1,
					'customer_id'=>-1,
					);
		}
		$db = new Sales_Model_DbTable_Dbinvoiceapprove();
		$rows = $db->getAllSaleOrder($search);
		$columns=array("BRANCH_NAME","CUSTOMER_NAME","SALE_AGENT","SALE_NO", "ORDER_DATE","SALE_APP_DATE",
				"CURRNECY_TYPE","TOTAL","DISCOUNT","TOTAL_AMOUNT","APPROVED_STATUS","PENDING_STATUS","BY_USER");
		$link=array(
				'module'=>'sales','controller'=>'invoiceapprove','action'=>'add',
		);

		$list = new Application_Form_Frmlist();
		$this->view->list=$list->getCheckList(0, $columns, $rows, array('branch_name'=>$link,'customer_name'=>$link,'staff_name'=>$link,'sale_no'=>$link));
		$formFilter = new Sales_Form_FrmSearch();
		$this->view->formFilter = $formFilter;
	    Application_Model_Decorator::removeAllDecorator($formFilter);*/

	}
	function approvedAction(){
		$db = new Application_Model_DbTable_DbGlobal();
		if($this->getRequest()->isPost()) {
			$data = $this->getRequest()->getPost();
			try {
				$dbq = new Sales_Model_DbTable_Dbinvoiceapprove();
				$returnid = $dbq->addInvoiceApproved($data);
				//Application_Form_FrmMessage::message("APPROVED_SUCESS");
				if(!empty($data["saveprint"])){
					//Application_Form_FrmMessage::Sucessfull("APPROVED_SUCESS", "/report/index/deliverynote/id/".$returnid);
					Application_Form_FrmMessage::Sucessfull("APPROVED_SUCESS", "/report/index/rpt-delivery");

				}else{
					Application_Form_FrmMessage::Sucessfull("APPROVED_SUCESS", "/sales/invoiceapprove");
				}

			}catch (Exception $e){
				$err =$e->getMessage();
				Application_Model_DbTable_DbUserLog::writeMessageError($err);
				Application_Form_FrmMessage::Sucessfull("APPROVED_FAIL", "/sales/invoiceapprove");
			}
		}

	}
	function addAction(){
		$id = ($this->getRequest()->getParam('id'))? $this->getRequest()->getParam('id'): '0';
    	if(empty($id)){
    		$this->_redirect("/sales/salesapprove");
    	}
    	$query = new Sales_Model_DbTable_Dbinvoiceapprove();
    	$this->view->product =  $query->getProductSaleById($id);
		$rs = $query->getProductSaleById($id);
    	if(empty($rs)){
    		$this->_redirect("/sales/salesapprove");
    	}
    	$db= new Application_Model_DbTable_DbGlobal();
    	$this->view->rscondition = $db->getTermConditionByIdIinvocie(3, null);
	}
}


text:
/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.app.util.bin.format.pe.cli.tables;

import java.io.IOException;

import ghidra.app.util.bin.BinaryReader;
import ghidra.app.util.bin.format.pe.cli.streams.CliStreamMetadata;
import ghidra.program.model.data.*;

/**
 * Describes the AssemblyRefOS table. Apparently it is ignored by the CLI and shouldn't be found in an assembly.
 */
public class CliTableAssemblyRefOS extends CliAbstractTable {
	public class CliAssemblyRefOSRow extends CliAbstractTableRow {
		public int osPlatformID;
		public int osMajorVersion;
		public int osMinorVersion;
		public int assemblyRefIndex;

		public CliAssemblyRefOSRow(int osPlatformID, int osMajorVersion, int osMinorVersion, int assemblyRefIndex) {
			super();
			this.osPlatformID = osPlatformID;
			this.osMajorVersion = osMajorVersion;
			this.osMinorVersion = osMinorVersion;
			this.assemblyRefIndex = assemblyRefIndex;
		}

		@Override
		public String getRepresentation() {
			return String.format("%d v%d.%d", osPlatformID, osMajorVersion, osMinorVersion);
		}
	}

	public CliTableAssemblyRefOS(BinaryReader reader, CliStreamMetadata stream, CliTypeTable tableId) throws IOException {
		super(reader, stream, tableId);
		for (int i = 0; i < this.numRows; i++) {
			rows.add(new CliAssemblyRefOSRow(reader.readNextInt(), reader.readNextInt(), reader.readNextInt(), readTableIndex(reader, CliTypeTable.AssemblyRef)));
		}
	}

	@Override
	public DataType getRowDataType() {
		return toDataType();
	}

	@Override
	public DataType toDataType() {
		Structure rowDt = new StructureDataType(new CategoryPath(PATH), "AssemblyRefOS Row", 0);
		rowDt.add(DWORD, "OSPlatformID", null);
		rowDt.add(DWORD, "OSMajorVersion", null);
		rowDt.add(DWORD, "OSMinorVersion", null);
		rowDt.add(metadataStream.getTableIndexDataType(CliTypeTable.AssemblyRef), "AssemblyRef", "index into AssemblyRef table");
		return new ArrayDataType(rowDt, this.numRows, rowDt.getLength());
	}

}


text:
package com.privatecloud.users.dto;

import java.io.Serializable;

public class ResponseObject implements Serializable {

	private static final long serialVersionUID = 2721149645386346602L;

	boolean flag;
	String msg;

	public ResponseObject(){}

	public boolean isFlag() {
		return flag;
	}
	public void setFlag(boolean flag) {
		this.flag = flag;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}

}


text:
using blink::WebFrame;
using blink::WebString;
using blink::WebURLError;
using blink::WebURLLoader;
using blink::WebURLLoaderOptions;
using blink::WebURLRequest;
using blink::WebURLResponse;

namespace media {

// The number of milliseconds to wait before retrying a failed load.
const int kLoaderFailedRetryDelayMs = 250;

// Each retry, add this many MS to the delay.
// total delay is:
// (kLoaderPartialRetryDelayMs +
//  kAdditionalDelayPerRetryMs * (kMaxRetries - 1) / 2) * kMaxretries = 29250 ms
const int kAdditionalDelayPerRetryMs = 50;

// The number of milliseconds to wait before retrying when the server
// decides to not give us all the data at once.
const int kLoaderPartialRetryDelayMs = 25;

const int kHttpOK = 200;
const int kHttpPartialContent = 206;
const int kHttpRangeNotSatisfiable = 416;

ResourceMultiBufferDataProvider::ResourceMultiBufferDataProvider(
    UrlData* url_data,
    MultiBufferBlockId pos)
    : pos_(pos),
      url_data_(url_data),
      retries_(0),
      cors_mode_(url_data->cors_mode()),
      origin_(url_data->url().GetOrigin()),
      weak_factory_(this) {
  DCHECK(url_data_) << " pos = " << pos;
  DCHECK_GE(pos, 0);
}

void ResourceMultiBufferDataProvider::Start() {
  // Prepare the request.
  WebURLRequest request(url_data_->url());
  // TODO(mkwst): Split this into video/audio.
  request.setRequestContext(WebURLRequest::RequestContextVideo);

  DVLOG(1) << __FUNCTION__ << " @ " << byte_pos();
  if (url_data_->length() > 0) {
    DCHECK_LT(byte_pos(), url_data_->length()) << " " << url_data_->url();
  }

  request.setHTTPHeaderField(
      WebString::fromUTF8(net::HttpRequestHeaders::kRange),
      WebString::fromUTF8(
          net::HttpByteRange::RightUnbounded(byte_pos()).GetHeaderValue()));

  url_data_->frame()->setReferrerForRequest(request, blink::WebURL());

  // Disable compression, compression for audio/video doesn't make sense...
  request.setHTTPHeaderField(
      WebString::fromUTF8(net::HttpRequestHeaders::kAcceptEncoding),
      WebString::fromUTF8("identity;q=1, *;q=0"));

  // Check for our test WebURLLoader.
  scoped_ptr<WebURLLoader> loader;
  if (test_loader_) {
    loader = std::move(test_loader_);
  } else {
    WebURLLoaderOptions options;
    if (url_data_->cors_mode() == UrlData::CORS_UNSPECIFIED) {
      options.allowCredentials = true;
      options.crossOriginRequestPolicy =
          WebURLLoaderOptions::CrossOriginRequestPolicyAllow;
    } else {
      options.exposeAllResponseHeaders = true;
      // The author header set is empty, no preflight should go ahead.
      options.preflightPolicy = WebURLLoaderOptions::PreventPreflight;
      options.crossOriginRequestPolicy =
          WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl;
      if (url_data_->cors_mode() == UrlData::CORS_USE_CREDENTIALS)
        options.allowCredentials = true;
    }
    loader.reset(url_data_->frame()->createAssociatedURLLoader(options));
  }

  // Start the resource loading.
  loader->loadAsynchronously(request, this);
  active_loader_.reset(new ActiveLoader(std::move(loader)));
}

ResourceMultiBufferDataProvider::~ResourceMultiBufferDataProvider() {}

/////////////////////////////////////////////////////////////////////////////
// MultiBuffer::DataProvider implementation.
MultiBufferBlockId ResourceMultiBufferDataProvider::Tell() const {
  return pos_;
}

bool ResourceMultiBufferDataProvider::Available() const {
  if (fifo_.empty())
    return false;
  if (fifo_.back()->end_of_stream())
    return true;
  if (fifo_.front()->data_size() == block_size())
    return true;
  return false;
}

scoped_refptr<DataBuffer> ResourceMultiBufferDataProvider::Read() {
  DCHECK(Available());
  scoped_refptr<DataBuffer> ret = fifo_.front();
  fifo_.pop_front();
  ++pos_;
  return ret;
}

void ResourceMultiBufferDataProvider::SetDeferred(bool deferred) {
  if (!active_loader_ || active_loader_->deferred() == deferred)
    return;
  active_loader_->SetDeferred(deferred);
}

/////////////////////////////////////////////////////////////////////////////
// WebURLLoaderClient implementation.

void ResourceMultiBufferDataProvider::willFollowRedirect(
    WebURLLoader* loader,
    WebURLRequest& newRequest,
    const WebURLResponse& redirectResponse) {
  redirects_to_ = newRequest.url();
  url_data_->set_valid_until(base::Time::Now() +
                             GetCacheValidUntil(redirectResponse));

  // This test is vital for security!
  if (cors_mode_ == UrlData::CORS_UNSPECIFIED) {
    // We allow the redirect if the origin is the same.
    if (origin_ != redirects_to_.GetOrigin()) {
      // We also allow the redirect if we don't have any data in the
      // cache, as that means that no dangerous data mixing can occur.
      if (url_data_->multibuffer()->map().empty() && fifo_.empty())
        return;

      url_data_->Fail();
    }
  }
}

void ResourceMultiBufferDataProvider::didSendData(
    WebURLLoader* loader,
    unsigned long long bytes_sent,
    unsigned long long total_bytes_to_be_sent) {
  NOTIMPLEMENTED();
}

void ResourceMultiBufferDataProvider::didReceiveResponse(
    WebURLLoader* loader,
    const WebURLResponse& response) {
#if ENABLE_DLOG
  string version;
  switch (response.httpVersion()) {
    case WebURLResponse::HTTPVersion_0_9:
      version = "0.9";
      break;
    case WebURLResponse::HTTPVersion_1_0:
      version = "1.0";
      break;
    case WebURLResponse::HTTPVersion_1_1:
      version = "1.1";
      break;
    case WebURLResponse::HTTPVersion_2_0:
      version = "2.1";
      break;
  }
  DVLOG(1) << "didReceiveResponse: HTTP/" << version << " "
           << response.httpStatusCode();
#endif
  DCHECK(active_loader_);

  scoped_refptr<UrlData> destination_url_data(url_data_);

  UrlIndex* url_index = url_data_->url_index();

  if (!redirects_to_.is_empty()) {
    if (!url_index) {
      // We've been disconnected from the url index.
      // That means the url_index_ has been destroyed, which means we do not
      // need to do anything clever.
      return;
    }
    destination_url_data = url_index->GetByUrl(redirects_to_, cors_mode_);
    redirects_to_ = GURL();
  }

  base::Time last_modified;
  if (base::Time::FromString(
          response.httpHeaderField("Last-Modified").utf8().data(),
          &last_modified)) {
    destination_url_data->set_last_modified(last_modified);
  }

  destination_url_data->set_valid_until(base::Time::Now() +
                                        GetCacheValidUntil(response));

  uint32_t reasons = GetReasonsForUncacheability(response);
  destination_url_data->set_cacheable(reasons == 0);
  UMA_HISTOGRAM_BOOLEAN("Media.CacheUseful", reasons == 0);
  int shift = 0;
  int max_enum = base::bits::Log2Ceiling(kMaxReason);
  while (reasons) {
    DCHECK_LT(shift, max_enum);  // Sanity check.
    if (reasons & 0x1) {
      UMA_HISTOGRAM_ENUMERATION("Media.UncacheableReason", shift,
                                max_enum);  // PRESUBMIT_IGNORE_UMA_MAX
    }

    reasons >>= 1;
    ++shift;
  }

  // Expected content length can be |kPositionNotSpecified|, in that case
  // |content_length_| is not specified and this is a streaming response.
  int64_t content_length = response.expectedContentLength();

  // We make a strong assumption that when we reach here we have either
  // received a response from HTTP/HTTPS protocol or the request was
  // successful (in particular range request). So we only verify the partial
  // response for HTTP and HTTPS protocol.
  if (destination_url_data->url().SchemeIsHTTPOrHTTPS()) {
    bool partial_response = (response.httpStatusCode() == kHttpPartialContent);
    bool ok_response = (response.httpStatusCode() == kHttpOK);

    // Check to see whether the server supports byte ranges.
    std::string accept_ranges =
        response.httpHeaderField("Accept-Ranges").utf8();
    if (accept_ranges.find("bytes") != std::string::npos)
      destination_url_data->set_range_supported();

    // If we have verified the partial response and it is correct.
    // It's also possible for a server to support range requests
    // without advertising "Accept-Ranges: bytes".
    if (partial_response && VerifyPartialResponse(response)) {
      destination_url_data->set_range_supported();
    } else if (ok_response && pos_ == 0) {
      // We accept a 200 response for a Range:0- request, trusting the
      // Accept-Ranges header, because Apache thinks that's a reasonable thing
      // to return.
      destination_url_data->set_length(content_length);
    } else if (response.httpStatusCode() == kHttpRangeNotSatisfiable) {
      // Really, we should never request a range that doesn't exist, but
      // if we do, let's handle it in a sane way.
      // Unsatisfiable range
      fifo_.push_back(DataBuffer::CreateEOSBuffer());
      destination_url_data->multibuffer()->OnDataProviderEvent(this);
      return;
    } else {
      destination_url_data->Fail();
      return;
    }
  } else {
    destination_url_data->set_range_supported();
    if (content_length != kPositionNotSpecified) {
      destination_url_data->set_length(content_length + byte_pos());
    }
  }

  if (url_index) {
    destination_url_data = url_index->TryInsert(destination_url_data);
  }

  if (destination_url_data != url_data_) {
    // At this point, we've encountered a redirect, or found a better url data
    // instance for the data that we're about to download.

    // First, let's take a ref on the current url data.
    scoped_refptr<UrlData> old_url_data(url_data_);
    destination_url_data->Use();

    // Take ownership of ourselves. (From the multibuffer)
    scoped_ptr<DataProvider> self(
        url_data_->multibuffer()->RemoveProvider(this));
    url_data_ = destination_url_data.get();
    // Give the ownership to our new owner.
    url_data_->multibuffer()->AddProvider(std::move(self));

    // Call callback to let upstream users know about the transfer.
    // This will merge the data from the two multibuffers and
    // cause clients to start using the new UrlData.
    old_url_data->RedirectTo(destination_url_data);
  }
}

void ResourceMultiBufferDataProvider::didReceiveData(WebURLLoader* loader,
                                                     const char* data,
                                                     int data_length,
                                                     int encoded_data_length) {
  DVLOG(1) << "didReceiveData: " << data_length << " bytes";
  DCHECK(!Available());
  DCHECK(active_loader_);
  DCHECK_GT(data_length, 0);

  // When we receive data, we allow more retries.
  retries_ = 0;

  while (data_length) {
    if (fifo_.empty() || fifo_.back()->data_size() == block_size()) {
      fifo_.push_back(new DataBuffer(block_size()));
      fifo_.back()->set_data_size(0);
    }
    int last_block_size = fifo_.back()->data_size();
    int to_append = std::min<int>(data_length, block_size() - last_block_size);
    DCHECK_GT(to_append, 0);
    memcpy(fifo_.back()->writable_data() + last_block_size, data, to_append);
    data += to_append;
    fifo_.back()->set_data_size(last_block_size + to_append);
    data_length -= to_append;
  }

  if (Available())
    url_data_->multibuffer()->OnDataProviderEvent(this);

  // Beware, this object might be deleted here.
}

void ResourceMultiBufferDataProvider::didDownloadData(WebURLLoader* loader,
                                                      int dataLength,
                                                      int encoded_data_length) {
  NOTIMPLEMENTED();
}

void ResourceMultiBufferDataProvider::didReceiveCachedMetadata(
    WebURLLoader* loader,
    const char* data,
    int data_length) {
  NOTIMPLEMENTED();
}

void ResourceMultiBufferDataProvider::didFinishLoading(
    WebURLLoader* loader,
    double finishTime,
    int64_t total_encoded_data_length) {
  DVLOG(1) << "didFinishLoading";
  DCHECK(active_loader_.get());
  DCHECK(!Available());

  // We're done with the loader.
  active_loader_.reset();

  // If we didn't know the |instance_size_| we do now.
  int64_t size = byte_pos();
  if (!fifo_.empty())
    size += fifo_.back()->data_size();

  // This request reports something smaller than what we've seen in the past,
  // Maybe it's transient error?
  if (url_data_->length() != kPositionNotSpecified &&
      size < url_data_->length()) {
    if (retries_ < kMaxRetries) {
      DVLOG(1) << " Partial data received.... @ pos = " << size;
      retries_++;
      base::MessageLoop::current()->PostDelayedTask(
          FROM_HERE, base::Bind(&ResourceMultiBufferDataProvider::Start,
                                weak_factory_.GetWeakPtr()),
          base::TimeDelta::FromMilliseconds(kLoaderPartialRetryDelayMs));
      return;
    } else {
      scoped_ptr<ActiveLoader> active_loader = std::move(active_loader_);
      url_data_->Fail();
      return;
    }
  }

  url_data_->set_length(size);
  fifo_.push_back(DataBuffer::CreateEOSBuffer());

  DCHECK(Available());
  url_data_->multibuffer()->OnDataProviderEvent(this);

  // Beware, this object might be deleted here.
}

void ResourceMultiBufferDataProvider::didFail(WebURLLoader* loader,
                                              const WebURLError& error) {
  DVLOG(1) << "didFail: reason=" << error.reason
           << ", isCancellation=" << error.isCancellation
           << ", domain=" << error.domain.utf8().data()
           << ", localizedDescription="
           << error.localizedDescription.utf8().data();
  DCHECK(active_loader_.get());

  if (retries_ < kMaxRetries && pos_ != 0) {
    retries_++;
    base::MessageLoop::current()->PostDelayedTask(
        FROM_HERE, base::Bind(&ResourceMultiBufferDataProvider::Start,
                              weak_factory_.GetWeakPtr()),
        base::TimeDelta::FromMilliseconds(
            kLoaderFailedRetryDelayMs + kAdditionalDelayPerRetryMs * retries_));
  } else {
    // We don't need to continue loading after failure.
    // Note that calling Fail() will most likely delete this object.
    url_data_->Fail();
  }
}

bool ResourceMultiBufferDataProvider::ParseContentRange(
    const std::string& content_range_str,
    int64_t* first_byte_position,
    int64_t* last_byte_position,
    int64_t* instance_size) {
  const std::string kUpThroughBytesUnit = "bytes ";
  if (content_range_str.find(kUpThroughBytesUnit) != 0)
    return false;
  std::string range_spec =
      content_range_str.substr(kUpThroughBytesUnit.length());
  size_t dash_offset = range_spec.find("-");
  size_t slash_offset = range_spec.find("/");

  if (dash_offset == std::string::npos || slash_offset == std::string::npos ||
      slash_offset < dash_offset || slash_offset + 1 == range_spec.length()) {
    return false;
  }
  if (!base::StringToInt64(range_spec.substr(0, dash_offset),
                           first_byte_position) ||
      !base::StringToInt64(
          range_spec.substr(dash_offset + 1, slash_offset - dash_offset - 1),
          last_byte_position)) {
    return false;
  }
  if (slash_offset == range_spec.length() - 2 &&
      range_spec[slash_offset + 1] == '*') {
    *instance_size = kPositionNotSpecified;
  } else {
    if (!base::StringToInt64(range_spec.substr(slash_offset + 1),
                             instance_size)) {
      return false;
    }
  }
  if (*last_byte_position < *first_byte_position ||
      (*instance_size != kPositionNotSpecified &&
       *last_byte_position >= *instance_size)) {
    return false;
  }

  return true;
}

int64_t ResourceMultiBufferDataProvider::byte_pos() const {
  int64_t ret = pos_;
  ret += fifo_.size();
  ret = ret << url_data_->multibuffer()->block_size_shift();
  if (!fifo_.empty()) {
    ret += fifo_.back()->data_size() - block_size();
  }
  return ret;
}

int64_t ResourceMultiBufferDataProvider::block_size() const {
  int64_t ret = 1;
  return ret << url_data_->multibuffer()->block_size_shift();
}

bool ResourceMultiBufferDataProvider::VerifyPartialResponse(
    const WebURLResponse& response) {
  int64_t first_byte_position, last_byte_position, instance_size;
  if (!ParseContentRange(response.httpHeaderField("Content-Range").utf8(),
                         &first_byte_position, &last_byte_position,
                         &instance_size)) {
    return false;
  }

  if (url_data_->length() == kPositionNotSpecified) {
    url_data_->set_length(instance_size);
  }

  if (byte_pos() != first_byte_position) {
    return false;
  }

  return true;
}

}  // namespace media


text:
(function(){
  //A service that manages the logout of an organization or an employee
  var service = function($location,$cookies){
    return {
      logout : function(url){
        function InvalidArgumentException(msg,argumentIndex){
          this.message = msg;
          this.argumentIndex = argumentIndex;
        }
        if(!angular.isString(url)){
          throw new InvalidArgumentException("This method's unique argument must be a string",0);

        }
        else{
          window.localStorage.removeItem('auth_token');
          $location.path(url);
        }
      }
    }
  };

  var app = angular.module('Plunner');
  app.factory('logoutService',service);
}());


text:
using System;

namespace SoftwarePatterns.Core.Command
{
	public class UpdateQuantityCommand : ICommand
	{
		public int NewQuantity { get; set; }

		private const int oldQuantity = 5;

		public void Execute()
		{
			//simulate updating db
			Console.WriteLine("Database updated");

			//simulate logging
			Console.WriteLine("LOG: Updated order quantity from {0} to {1}", oldQuantity, NewQuantity);
		}
	}
}


text:
class ChromeDirectSocketsDelegate : public content::DirectSocketsDelegate {
 public:
  // content::DirectSocketsDelegate:
  bool ValidateAddressAndPort(
      content::RenderFrameHost*,
      const std::string& address,
      uint16_t port,
      blink::mojom::DirectSocketProtocolType protocol) const override;
  bool ShouldSkipPostResolveChecks(content::RenderFrameHost*) const override;
};

#endif  // CHROME_BROWSER_DIRECT_SOCKETS_CHROME_DIRECT_SOCKETS_DELEGATE_H_


text:
<?php
/**
 * @author @jenschude <jens.schulze@commercetools.de>
 */

namespace Commercetools\Core\Request\Products;

use Commercetools\Core\Model\Product\ProductProjection;
use Commercetools\Core\RequestTestCase;

/**
 * Class ProductProjectionByIdGetRequestTest
 * @package Commercetools\Core\Request\Products
 */
class ProductProjectionByIdGetRequestTest extends RequestTestCase
{
    const PRODUCT_PROJECTION_BY_ID_GET_REQUEST = ProductProjectionByIdGetRequest::class;

    public function testMapResult()
    {
        $result = $this->mapResult(ProductProjectionByIdGetRequest::ofId('id'));
        $this->assertInstanceOf(ProductProjection::class, $result);
    }

    public function testMapEmptyResult()
    {
        $result = $this->mapEmptyResult(ProductProjectionByIdGetRequest::ofId('id'));
        $this->assertNull($result);
    }

    public function testHttpRequestPath()
    {
        $request = ProductProjectionByIdGetRequest::ofId('id');
        $httpRequest = $request->httpRequest();

        $this->assertSame('product-projections/id', (string)$httpRequest->getUri());
    }
}


text:
<ion-view view-title="Groups" can-swipe-back="false">

    <ion-nav-bar class="bar-stable">

        <ion-nav-buttons side="right">
            <button class="button button-icon icon ion-ios-search-strong" ng-click="ctrl.showFilterBar()">
            </button>
        </ion-nav-buttons>

        <ion-nav-buttons side="secondary">
            <button class="button button-icon icon ion-android-more-vertical"
                    ng-click="ctrl.showSideMenu()">
            </button>
        </ion-nav-buttons>

    </ion-nav-bar>

    <ion-content scroll="true" overflow-scroll="true">

        <ion-list>

                <ion-item
                        class="item-avatar item-icon-left item-remove-animate"
                        type="item-text-wrap"
                        href="#/tab/contactables/{{contactable.$$instanceId}}" >

                        {{contactable.name}}

{{contactable.company}}

{{contactable.country}}

                </ion-item>

        </ion-list>

 {{ ctrl.message }}

    </ion-content>
</ion-view>