text:
Basic Python Coding
===================

In this course you will learn basic programming in Python, but there is also
excellent Python Language reference material available on the internet freely.
You can download the book `Dive Into Python <http://www.diveintopython.org/>`_
or there are a host of `Beginners Guides <http://wiki.python.org/moin/BeginnersGuide>`_
to Python on the Python Website. Follow the links to either:

+ `BeginnersGuide/NonProgrammers <http://wiki.python.org/moin/BeginnersGuide/NonProgrammers>`_
+ `BeginnersGuide/Programmers <http://wiki.python.org/moin/BeginnersGuide/Programmers>`_

depending on your level of current programming knowledge. The code sections
below assume a knowledge of fundamental programming principles and mainly
focus on Syntax specific to programming in Python.

Note: >>> represents a Python command line prompt.

Loops in Python
---------------

for Loop
~~~~~~~~

The general format is:

.. code-block::  python

    for variable in sequence:
        #some commands
    #other commands after for loop

Note that the formatting (indents and new lines) governs the end of the for
loop, whereas the start of the loop is the colon :.

Observe the loop below, which is similar to loops you will be using in the
course. The variable i moves through the string list becoming each string in
turn. The top section is the code in a .py file and the bottom section shows
the output

.. code-block::  python

    #The following code demonstrates a list with strings
    ingredientslist = ["Rice","Water","Jelly"]
    for i in ingredientslist:
        print i
    print "No longer in the loop"

gives

.. code-block::  python

    Rice
    Water
    Jelly
    No longer in the loop

while Loop
~~~~~~~~~~

These are similar to for loops except they continue to loop until the specified
condition is no longer true. A while loop is not told to work through any
specific sequence.

.. code-block::  python

    i = 3
    while i <= 15:
        # some commands
        i = i + 1 # a command that will eventually end the loop is naturally
        required
    # other commands after while loop

For this specific simple while loop, it would have been better to do as a for
loop but it demonstrates the syntax. while loops are useful if the number of
iterations before the loop needs to end, is unknown.

The if statement
~~~~~~~~~~~~~~~~

This is performed in much the same way as the loops above. The key identifier is
the colon : to start the statements and the end of indentation to end it.

.. code-block::  python

    if j in testlist:
        # some commands
    elif j == 5:
        # some commands
    else:
        # some commands

Here it is shown that "elif" (else if) and "else" can also be used after an if
statement. "else" can in fact be used after both the loops in the same way.

Array types in python
--------------------------

Lists
~~~~~

A list is simply a sequence of variables grouped together. The range function is
often used to create lists of integers, with the general format of
range(start,stop,step). The default for start is 0 and the default for step is
1.

>>> range(3,8)
[3,4,5,6,7]

This is a list/sequence. As well as integers, lists can also have strings in
them or a mix of integers, floats and strings. They can be created by a loop
(as shown in the next section) or by explicit creation (below). Note that the
print statement will display a string/variable/list/... to the user

>>> a = [5,8,"pt"]
>>> print a
[5,8,'pt']
>>> print a[0]
5

Tuples
~~~~~~

Tuples are basically the same as lists, but with the important difference that
they cannot be modified once they have been created. They are assigned by:

>>> x = (4,1,8,"string",[1,0],("j",4,"o"),14)

Tuples can have any type of number, strings, lists, other tuples, functions and
objects, inside them. Also note that the first element in the tuple is numbered
as element "zero". Accessing this data is done by:

>>> x[0]
4
>>> x[3]
"string"

Dictionaries
~~~~~~~~~~~~

A Dictionary is a list of reference keys each with associated data, whereby the
order does not affect the operation of the dictionary at all. With dictionaries,
the keys are not consecutive integers (unlike lists), and instead could be
integers, floats or strings. This will become clear:

>>> x = {} # creates a new empty dictionary - note the curly brackets denoting the creation of a dictionary
>>> x[4] = "programming" # the string "programming" is added to the dictionary x, with "4" as it's reference
>>> x["games"] = 12
>>> print x["games"]
12

In a dictionary, the reference keys and the stored values can be any type of
input. New dictionary elements are added as they are created (with a list, you
cannot access or write to a place in the list that exceeds the initially defined
list dimensions).

.. code-block::  python

    costs = {"CHICKEN": 1.3, "BEEF": 0.8, "MUTTON": 12}
    print "Cost of Meats"
    for i in costs:
        print i
        print costs[i]
    costs["LAMB"] = 5
    print "Updated Costs of Meats"
    for i in costs:
        print i
        print costs[i]

gives

.. code-block::  python

    Cost of Meats
    CHICKEN
    1.3
    MUTTON
    12
    BEEF
    0.8
    Updated Costs of Meats
    LAMB
    5
    CHICKEN
    1.3
    MUTTON
    12
    BEEF
    0.8

In the above example, the dictionary is created using curly brackets and colons
to represent the assignment of data to the dictionary keys. The variable i is
assigned to each of the keys in turn (in the same way it would be for a list
with

>>> for i in range(1,10)

). Then the dictionary is called with this key, and
it returns the data stored under that key name. These types of for loops using
dictionaries will be highly relevant in using PuLP to model LPs in this course.

List/Tuple/Dictionary Syntax Note
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Note that the creation of a:

- list is done with square brackets [];
- tuple is done with round brackets and a comma (,);
- dictionary is done with parentheses{}.

After creation however, when accessing elements in the list/tuple/dictionary,
the operation is always performed with square brackets (i.e a[3]?). If a was a
list or tuple, this would return the fourth element. If a was a dictionary it
would return the data stored with a reference key of 3.

List Comprehensions
~~~~~~~~~~~~~~~~~~~

Python supports List Comprehensions which are a fast and concise way to create
lists without using multiple lines. They are easily understandable when simple,
and you will be using them in your code for this course.

>>> a = [i for i in range(5)]
>>> a
[0, 1, 2, 3, 4]

This statement above will create the list [0,1,2,3,4] and assign it to the
variable "a".

>>> odds = [i for i in range(25) if i%2==1]
>>> odds
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23]

This statement above uses the if statement and the modulus operator(%) so that
only odd numbers are included in the list: [1,3,5,...,19,21,23]. (Note: The
modulus operator calculates the remainder from an integer division.)

>>> fifths = [i for i in range(25) if i%5==0]
>>> fifths
[0, 5, 10, 15, 20]

This will create a list with every fifth value in it [0,5,10,15,20]. Existing
lists can also be used in the creation of new lists below:

>>> a = [i for i in range(25) if (i in odds and i not in fifths)]

Note that this could also have been done in one step from scratch:

>>> a = [i for i in range(25) if (i%2==1 and i%5==0)]

For a challenge you can try creating

a. a list of prime numbers up to 100, and
#. a list of all "perfect" numbers.

`More List Comprehensions Examples <http://www.secnetix.de/olli/Python/list_comprehensions.hawk>`_

`Wikipedia: Perfect Numbers <http://en.wikipedia.org/wiki/Perfect_numbers>`_.

Other important language features
---------------------------------

Commenting in Python
~~~~~~~~~~~~~~~~~~~~
Commenting at the top of a file is done using """ to start and to end the
comment section. Commenting done throughout the code is done using the hash
# symbol at the start of the line.

Import Statement
~~~~~~~~~~~~~~~~

At the top of all your Python coding that you intend to use PuLP to model, you
will need the import statement. This statement makes the contents of another
module (file of program code) available in the module you are currently writing
i.e. functions and values defined in pulp.py that you will be required to call,
become usable. In this course you will use:

>>> from pulp import *

The asterisk represents that you are importing all names from the module of
pulp. Calling a function defined in pulp.py now can be done as if they were
defined in your own module.

Functions
~~~~~~~~~

Functions in Python are defined by: (def is short for define)

.. code-block::  python

    def name(inputparameter1, inputparameter2, . . .):
        #function body

For a real example, note that if inputs are assigned a value in the function
definition, that is the default value, and will be used only if no other value
is passed in. The order of the input parameters (in the definition) does not
matter at all, as long as when the function is called, the positional parameters
are entered in the corresponding order. If keywords are used the order of the
parameters does not matter at all:

.. code-block::  python

    def string_appender(head='begin', tail='end', end_message='EOL'):
        result = head + tail + end_message
        return result

>>> string_appender('newbegin', end_message = 'StringOver')
newbeginendStringOver

In the above example, the output from the function call is printed. The default
value for head is 'begin', but instead the input of 'newbegin' was used. The
default value for tail of 'end' was used. And the input value of endmessage was
used. Note that end_message must be specified as a key word argument as no
value is given for tail

Classes
~~~~~~~

To demonstrate how classes work in Python, look at the following class structure.

The class name is Pattern, and it contains several class variables which are
relevant to any instance of the Pattern class (i.e a Pattern). The functions are

__init__
    function which creates an instance of the Pattern
    class and assigns the attributes of name and lengthsdict using self.

__str__
    function defines what to return if the class instance is printed.

trim
    function acts like any normal function, except as with all class functions,
    self must be in the input brackets.

.. code-block::  python

    class Pattern:
        """
        Information on a specific pattern in the SpongeRoll Problem
        """
        cost = 1
        trimValue = 0.04
        totalRollLength = 20
        lenOpts = [5, 7, 9]

    def __init__(self,name,lengths = None):
        self.name = name
        self.lengthsdict = dict(zip(self.lenOpts,lengths))

    def __str__(self):
        return self.name

    def trim(self):
    return Pattern.totalRollLength - sum([int(i)*self.lengthsdict[i] for i in self.lengthsdict])

This class could be used as follows:

>>> Pattern.cost # The class attributes can be accessed without making an instance of the class
1
>>> a = Pattern("PatternA",[1,0,1])
>>> a.cost # a is now an instance of the Pattern class and is associated with Pattern class variables
1
>>> print a # This calls the Pattern.__str__() function
"PatternA"
>>> a.trim() # This calls the Pattern.trim() function. Note that no input is required.

The self in the function definition is an implied input


text:
namespace
{
struct Results
{
  bool empty = true;
  std::ostringstream values;
};
}  // namespace

namespace generator
{
static int callback(void * results_ptr, int argc, char ** argv, char ** azColName)
{
  Results & results = *reinterpret_cast<Results *>(results_ptr);
  for (size_t i = 0; i < argc; i++)
  {
    if (results.empty)
      results.empty = false;
    else
      results.values << ",";

    results.values << (argv[i] ? argv[i] : "{}");
  }
  return 0;
}

UGCDB::UGCDB(std::string const & path)
{
  int rc = sqlite3_open(path.c_str(), &m_db);
  if (rc)
  {
    LOG(LERROR, ("Can't open database:", sqlite3_errmsg(m_db)));
    sqlite3_close(m_db);
    m_db = nullptr;
  }
}

UGCDB::~UGCDB()
{
  if (m_db)
    sqlite3_close(m_db);
}

bool UGCDB::Get(osm::Id const & id, std::vector<uint8_t> & blob)
{
  if (!m_db)
    return false;

  Results results;
  results.values << "[";

  std::ostringstream cmd;
  cmd << "SELECT data FROM agg WHERE id=" << id.OsmId() << ";";

  char * zErrMsg = nullptr;
  auto rc = sqlite3_exec(m_db, cmd.str().c_str(), callback, &results, &zErrMsg);
  if (rc != SQLITE_OK)
  {
    LOG(LERROR, ("SQL error:", zErrMsg));
    sqlite3_free(zErrMsg);
    return false;
  }
  results.values << "]";

  return ValueToBlob(results.values.str(), blob);
}

bool UGCDB::Exec(std::string const & statement)
{
  if (!m_db)
    return false;

  char * zErrMsg = nullptr;
  auto rc = sqlite3_exec(m_db, statement.c_str(), nullptr, nullptr, &zErrMsg);
  if (rc != SQLITE_OK)
  {
    LOG(LERROR, ("SQL error:", zErrMsg));
    sqlite3_free(zErrMsg);
    return false;
  }
  return true;
}

bool UGCDB::ValueToBlob(std::string const & src, std::vector<uint8_t> & blob)
{
  blob.assign(src.cbegin(), src.cend());
  return true;
}

}  // namespace generator

redpajama_set_name: RedPajamaGithub


text:
package k8s

import (
	"fmt"

	"github.com/skydive-project/skydive/topology/graph"

	"k8s.io/api/core/v1"
	"k8s.io/client-go/kubernetes"
)

type replicationControllerHandler struct {
}

func (h *replicationControllerHandler) Dump(obj interface{}) string {
	rc := obj.(*v1.ReplicationController)
	return fmt.Sprintf("replicationController{Name: %s}", rc.GetName())
}

func (h *replicationControllerHandler) Map(obj interface{}) (graph.Identifier, graph.Metadata) {
	rc := obj.(*v1.ReplicationController)
	return graph.Identifier(rc.GetUID()), NewMetadata(Manager, "replicationcontroller", rc, rc.Name, rc.Namespace)
}

func newReplicationControllerProbe(clientset *kubernetes.Clientset, g *graph.Graph) Subprobe {
	return NewResourceCache(clientset.CoreV1().RESTClient(), &v1.ReplicationController{}, "replicationcontrollers", g, &replicationControllerHandler{})
}


text:
<?php

return array(
    'welcome' => 'Добре дошли в началната страница.',
    'information' => 'Тук можете да намерите информация за структурата.',
    'pictures_table' => 'Pictures таблица'
);


text:
const x = (foo: string)
: number => {}


text:
NGX_HOME=/etc/nginx

for DOMAIN in "$@"
do

  CONFIG_PATH="/resources/app/nginx.conf"
  DOMAIN_CONFIG="include $CONFIG_PATH;"

  if [ -a $CONFIG_PATH ]; then

    if [ -a "${NGX_HOME}/sites-available/${DOMAIN}" ]; then
      sudo rm ${NGX_HOME}/sites-available/${DOMAIN}
    fi
    sudo echo -e "$DOMAIN_CONFIG" >> ${NGX_HOME}/sites-available/${DOMAIN}

    if ! [ -a "${NGX_HOME}/sites-enabled/${DOMAIN}" ]; then
      sudo ln -s ${NGX_HOME}/sites-available/${DOMAIN} ${NGX_HOME}/sites-enabled/${DOMAIN}
    fi

  fi

  cd /home/apps/${DOMAIN}/current/
  npm install
done

sudo service nginx restart


text:
# Security

Sutra CMS is not a stand alone application in and of itself. It is more
accurately described as a set of modules that add CMS functionality to
larger applications.

As such, the architecture of security is meant to hook into another
module that handles that sort of thing. When run on the [Data Sutra](http://www.data-sutra.com) application platform, Data Sutra's Access and Control application controls security for Sutra CMS.

<!-- toc -->

## Overview

End result is one place to control security for large applications in
one place. This includes SaaS deployments, login and organization
management, password management, and group security model that operates
on three levels:

1.  What screens a group can access
2.  What records a group can see
3.  What workflow actions a group can trigger

The first two items are handled without any input from Sutra CMS.

## Workflow control

### 1. Publish actions

The third item—workflow actions—works by "publishing" various CMS
actions in the CMS module initialization method
(`scopes.CMS.init.items()`):

```js
/**
    * Registry actions for app
    *
    * @return {Object[]}
    */
this.items =  new function() {
    return [
        {name: 'Block version editable', registry: 'cms edit block version', description: 'Allow scrapbook versions to be re-opened for editing', uuid: '0016790E-70BB-4B13-B6FE-39E641E98121'},
        {name: 'Page version editable', registry: 'cms edit version', description: 'Allow versions to be re-opened for editing', uuid: '0016790E-70BB-4B13-B6FE-39E641E98122'},
        {name: 'Add a new page', registry: 'cms page add', description: 'Allow a new page to be created', uuid: '0016790E-70BB-4B13-B6FE-39E641E98123'},
        {name: 'Delete selected page', registry: 'cms page delete', description: 'Allow the selected page to be deleted', uuid: '0016790E-70BB-4B13-B6FE-39E641E98124'},
        {name: 'Create duplicate of selected page', registry: 'cms page duplicate', description: 'Allow duplication of selected page', uuid: '0016790E-70BB-4B13-B6FE-39E641E98125'},
        {name: 'Page setup: Real mode v. GUI', registry: 'cms page mode toggle', description: 'Allow viewing the selected page as it will appear on the web', uuid: '0016790E-70BB-4B13-B6FE-39E641E98126'},
        {name: 'Reorder pages within a site', registry: 'cms page reorder', description: 'Allow the positionment of pages within a site to be changed', uuid: '0016790E-70BB-4B13-B6FE-39E641E98127'},
        {name: 'Only show full-screen page', registry: 'cms page sitemap', description: 'Show sitemap only when needed', uuid: '0016790E-70BB-4B13-B6FE-39E641E98128'},
        {name: 'Update all pages', registry: 'cms site page update', description: 'Add missing areas to all pages in a site. Useful for when a major template change occurs.', uuid: '0016790E-70BB-4B13-B6FE-39E641E98129'},
        {name: 'Refresh all theme pages', registry: 'cms theme layout page update', description: 'Update all pages using a theme', uuid: '0016790E-70BB-4B13-B6FE-39E641E9812A'}
    ]
}
```

### 2. Registry

The Data Sura Access and Control application picks up all modules that
publish actions and creates workflow registry items:

![](../assets/ac-registry.png)

### 3. Group actions

Once in the registry, workflow actions can be assigned to groups:

![](../assets/ac-group-actions.png)

### 4. Action validation

Finally, Data Sutra exposes an API method for validating a particular
workflow action against the currently logged in user. `True/false` is
returned:

```js
globals.TRIGGER_registered_action_authenticate('cms page delete')
```

## Summary

While the workflow actions list isn't massive or particularly granular,
Sutra CMS has many places where it checks to see if a user has
permission to do something.

The combination of workflow actions and the capabilities of Data Sutra's
Access and Control application makes it extremely flexible to define
security on the fly for users. Without having different logins for
various parts of an entire application.

Additionally, when [extending Sutra CMS](developer/extending-cms.html) with your own modules and
applications—this system makes it very easy for you to define, code and
configure your own security rules.


text:
struct S {};

int (S::*mp0) = nullptr;
void (*fp0)() = nullptr;
void* p0 = nullptr;

int (S::*mp1) = 0; // expected-warning{{zero as null pointer constant}}
void (*fp1)() = 0; // expected-warning{{zero as null pointer constant}}
void* p1 = 0; // expected-warning{{zero as null pointer constant}}

// NULL is an integer constant expression, so warn on it too:
void* p2 = __null; // expected-warning{{zero as null pointer constant}}
void (*fp2)() = __null; // expected-warning{{zero as null pointer constant}}
int (S::*mp2) = __null; // expected-warning{{zero as null pointer constant}}

void f0(void* v = MACRO); // expected-warning{{zero as null pointer constant}}
void f1(void* v = NULL); // expected-warning{{zero as null pointer constant}}
void f2(void* v = MCRO(0)); // expected-warning{{zero as null pointer constant}}
void f3(void* v = MCRO(NULL)); // expected-warning{{zero as null pointer constant}}
void f4(void* v = 0); // expected-warning{{zero as null pointer constant}}
void f5(void* v);

void g() {
  f1(0); // expected-warning{{zero as null pointer constant}}
}

// Warn on these too. Matches gcc and arguably makes sense.
void* pp = (decltype(nullptr))0; // expected-warning{{zero as null pointer constant}}
void* pp2 = static_cast<decltype(nullptr)>(0); // expected-warning{{zero as null pointer constant}}

// Shouldn't warn.
namespace pr34362 {
struct A { operator int*() { return nullptr; } };
void func() { if (nullptr == A()) {} }
void func2() { if ((nullptr) == A()) {} }
}

template <typename T> void TmplFunc0(T var) {}
void Func0Test() {
  TmplFunc0<int>(0);
  TmplFunc0<int*>(0); // expected-warning {{zero as null pointer constant}}
  TmplFunc0<void*>(0); // expected-warning {{zero as null pointer constant}}
}

// FIXME: this one probably should not warn.
template <typename T> void TmplFunc1(int a, T default_value = 0) {} // expected-warning{{zero as null pointer constant}} expected-warning{{zero as null pointer constant}}
void FuncTest() {
  TmplFunc1<int>(0);
  TmplFunc1<int*>(0); // expected-note {{in instantiation of default function argument expression for 'TmplFunc1<int *>' required here}}
  TmplFunc1<void*>(0);  // expected-note {{in instantiation of default function argument expression for 'TmplFunc1<void *>' required here}}
}

template<typename T>
class TemplateClass0 {
 public:
  explicit TemplateClass0(T var) {}
};
void TemplateClass0Test() {
  TemplateClass0<int> a(0);
  TemplateClass0<int*> b(0); // expected-warning {{zero as null pointer constant}}
  TemplateClass0<void*> c(0); // expected-warning {{zero as null pointer constant}}
}

template<typename T>
class TemplateClass1 {
 public:
// FIXME: this one should *NOT* warn.
  explicit TemplateClass1(int a, T default_value = 0) {} // expected-warning{{zero as null pointer constant}} expected-warning{{zero as null pointer constant}}
};
void IgnoreSubstTemplateType1() {
  TemplateClass1<int> a(1);
  TemplateClass1<int*> b(1); // expected-note {{in instantiation of default function argument expression for 'TemplateClass1<int *>' required here}}
  TemplateClass1<void*> c(1); // expected-note {{in instantiation of default function argument expression for 'TemplateClass1<void *>' required here}}
}

#ifndef SYSTEM_WARNINGS
// Do not warn on *any* other macros from system headers, even if they
// expand to/their expansion contains NULL.
void* sys_init = SYSTEM_MACRO;
void* sys_init2 = OTHER_SYSTEM_MACRO;
#else
void* sys_init = SYSTEM_MACRO; // expected-warning {{zero as null pointer constant}}
void* sys_init2 = OTHER_SYSTEM_MACRO; // expected-warning {{zero as null pointer constant}}
#endif


text:
package crconfig

import (
	"context"
	"database/sql"
	"database/sql/driver"
	"encoding/json"
	"reflect"
	"testing"
	"time"

	"github.com/apache/trafficcontrol/lib/go-tc"
	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/monitoring"
	"gopkg.in/DATA-DOG/go-sqlmock.v1"
)

func ExpectedGetSnapshot(crc *tc.CRConfig) ([]byte, error) {
	return json.Marshal(crc)
}

func ExpectedGetMontioringSnapshot(crc *tc.CRConfig, tx *sql.Tx) ([]byte, error) {
	tm, _ := monitoring.GetMonitoringJSON(tx, *crc.Stats.CDNName)
	return json.Marshal(tm)
}

func MockGetSnapshot(mock sqlmock.Sqlmock, expected []byte, cdn string) {
	rows := sqlmock.NewRows([]string{"snapshot"})
	rows = rows.AddRow(expected)
	rows = rows.AddRow(expected)
	mock.ExpectQuery("SELECT").WithArgs(cdn).WillReturnRows(rows)
}

func TestGetSnapshot(t *testing.T) {
	db, mock, err := sqlmock.New()
	if err != nil {
		t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
	}
	defer db.Close()

	cdn := "mycdn"

	crc := &tc.CRConfig{}
	crc.Stats.CDNName = &cdn

	mock.ExpectBegin()
	expected, err := ExpectedGetSnapshot(crc)
	if err != nil {
		t.Fatalf("GetSnapshot creating expected err expected: nil, actual: %v", err)
	}
	MockGetSnapshot(mock, expected, cdn)
	mock.ExpectCommit()

	dbCtx, _ := context.WithTimeout(context.TODO(), time.Duration(10)*time.Second)
	tx, err := db.BeginTx(dbCtx, nil)
	if err != nil {
		t.Fatalf("creating transaction: %v", err)
	}
	defer tx.Commit()

	actual, exists, err := GetSnapshot(tx, cdn)
	if err != nil {
		t.Fatalf("GetSnapshot err expected: nil, actual: %v", err)
	}
	if !exists {
		t.Fatalf("GetSnapshot exists expected: true, actual: false")
	}

	if !reflect.DeepEqual(string(expected), actual) {
		t.Errorf("GetSnapshot expected: %+v, actual: %+v", string(expected), actual)
	}
}

type AnyTime struct{}

// Match satisfies sqlmock.Argument interface
func (a AnyTime) Match(v driver.Value) bool {
	_, ok := v.(time.Time)
	return ok
}

type Any struct{}

// Match satisfies sqlmock.Argument interface
func (a Any) Match(v driver.Value) bool {
	return true
}

func MockSnapshot(mock sqlmock.Sqlmock, expected []byte, expectedtm []byte, cdn string) {
	mock.ExpectExec("insert").WithArgs(cdn, expected, AnyTime{}, expectedtm).WillReturnResult(sqlmock.NewResult(1, 1))
}

func TestSnapshot(t *testing.T) {
	db, mock, err := sqlmock.New()
	if err != nil {
		t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
	}
	defer db.Close()

	cdn := "mycdn"

	crc := &tc.CRConfig{}
	crc.Stats.CDNName = &cdn
	mock.ExpectBegin()

	dbCtx, _ := context.WithTimeout(context.TODO(), time.Duration(10)*time.Second)
	tx, err := db.BeginTx(dbCtx, nil)
	if err != nil {
		t.Fatalf("creating transaction: %v", err)
	}

	expected, err := ExpectedGetSnapshot(crc)
	if err != nil {
		t.Fatalf("GetSnapshot creating expected err expected: nil, actual: %v", err)
	}

	expectedtm, err := ExpectedGetMontioringSnapshot(crc, tx)
	if err != nil {
		t.Fatalf("GetSnapshotMonitor creating expected err expected: nil, actual: %v", err)
	}

	tm, _ := monitoring.GetMonitoringJSON(tx, *crc.Stats.CDNName)
	MockSnapshot(mock, expected, expectedtm, cdn)
	mock.ExpectCommit()

	defer tx.Commit()

	if err := Snapshot(tx, crc, tm); err != nil {
		t.Fatalf("GetSnapshot err expected: nil, actual: %v", err)
	}
}


text:
<?
use yii\widgets\ActiveForm;
use yii\helpers\Html;
?>

Index

<?if(Yii::$app->session->hasFlash('success')):?>

        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
        <?=Yii::$app->session->getFlash('success')?>

<?endif;?>
<?if(Yii::$app->session->hasFlash('error')):?>

        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
        <?=Yii::$app->session->getFlash('error')?>

<?endif;?>

<?$form = ActiveForm::begin();?>
<?=$form->field($model, 'name')?>
<?=$form->field($model, 'email')->input('email')?>
<?=$form->field($model, 'text')->textarea(['rows' => 5])?>
<?=Html::submitButton('Отправить', ['class' => 'btn btn-success'])?>
<?ActiveForm::end();?>


text:
// Copyright (c) 2017 Colectica. All rights reserved
// See the LICENSE file in the project root for more information.
using Cogs.Model;
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Threading;
using Cogs.Common;

namespace Cogs.Publishers
{
    /// <summary>
    /// Generate an xml schema using the Garden of Eden approach, all elements and type definitions are declared globally
    /// </summary>
    public class XmlSchemaPublisher
    {
        public List<CogsError> Errors { get; } = new List<CogsError>();

        public string CogsLocation { get; set; }
        public string TargetDirectory { get; set; }
        public bool Overwrite { get; set; }

        public string TargetNamespace { get; set; }
        public string TargetNamespacePrefix { get; set; }

        Dictionary<string, string> createdElements = new Dictionary<string, string>();

        private CogsModel CogsModel { get; set; }
        private XmlSchema CogsSchema { get; set; }

        public void Publish(CogsModel model2)
        {
            if (CogsLocation == null)
            {
                throw new InvalidOperationException("Cogs location must be specified");
            }
            if (TargetDirectory == null)
            {
                throw new InvalidOperationException("Target directory must be specified");
            }

            if (Overwrite && Directory.Exists(TargetDirectory))
            {
                Directory.Delete(TargetDirectory, true);
                Thread.Sleep(50);
            }

            Directory.CreateDirectory(TargetDirectory);

            CogsModel = model2;
            CogsSchema = new XmlSchema();

            CogsSchema.TargetNamespace = TargetNamespace;
            CogsSchema.Namespaces.Add(TargetNamespacePrefix, TargetNamespace);
            CogsSchema.ElementFormDefault = XmlSchemaForm.Qualified;
            CogsSchema.AttributeFormDefault = XmlSchemaForm.Unqualified;

            // create built in types
            XmlSchemaComplexType referenceType = CreateReferenceType();

            // Create the container
            /*
            XmlSchemaComplexType containerType = new XmlSchemaComplexType();
            containerType.Name = "FragmentInstance";
            containerType.AddSchemaDocumentation("A Fragment Instance is used to transfer items plus any associated notes and other material. TopLevelReference provides a record of the main item of the FragmentInstance.");
            cogsSchema.Items.Add(containerType);

            XmlSchemaSequence containerSequence = new XmlSchemaSequence();
            containerType.Particle = containerSequence;
            */

            XmlSchemaChoice itemChoices = null;
            XmlSchemaComplexType containerType = CreateItemContainerType(out itemChoices);
            CogsSchema.Items.Add(containerType);

            XmlSchemaElement container = new XmlSchemaElement();
            container.Name = "ItemContainer";
            container.AddSchemaDocumentation("A Item Container is used to transfer items plus any associated notes and other material. TopLevelReference provides a record of the main item of the Item Container.");
            container.SchemaTypeName = new XmlQualifiedName("ItemContainerType", TargetNamespace);
            CogsSchema.Items.Add(container);

            foreach (var item in CogsModel.ItemTypes)
            {

                CreateDataType(item);

                // create a usage for the container
                XmlSchemaElement element = new XmlSchemaElement();
                element.Name = item.Name;
                element.SchemaTypeName = new XmlQualifiedName(item.Name, TargetNamespace);
                CogsSchema.Items.Add(element);

                // include item in container via element reference
                XmlSchemaElement elementRef = new XmlSchemaElement();
                elementRef.RefName = new XmlQualifiedName(item.Name, TargetNamespace);
                itemChoices.Items.Add(elementRef);
            }

            CreateCogsDataType();

            foreach (var dataType in CogsModel.ReusableDataTypes)
            {
                CreateDataType(dataType);
            }

            XmlSchemaSet schemaSet = new XmlSchemaSet();
            schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
            schemaSet.Add(CogsSchema);
            schemaSet.Compile();

            foreach (XmlSchema schema in schemaSet.Schemas())
            {
                CogsSchema = schema;
            }

            // Write the complete schema
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Encoding = Encoding.UTF8;
            settings.Indent = true;
            settings.IndentChars = "    ";
            using (XmlWriter writer = XmlWriter.Create(Path.Combine(TargetDirectory, "schema.xsd"), settings))
            {

                CogsSchema.Write(writer);
            }

        }

        public XmlSchemaSimpleType CreateCogsDataType()
        {
            XmlSchemaSimpleType simpleType = new XmlSchemaSimpleType();
            simpleType.Name = "cogsDate";
            simpleType.AddSchemaDocumentation("A union of dateTime, date, gYearMonth, gYear, and duration which allows for the use of a date-time combination (YYYY-MM-DDTHH:MM:SS), date (YYYYY-MM-DD), year-month (YYYY-MM), year (YYYY), and duration (PnYnMnDnHnMnS) as valid values.");

            XmlSchemaSimpleTypeUnion simpleTypeUnion = new XmlSchemaSimpleTypeUnion();
            simpleType.Content = simpleTypeUnion;

            simpleTypeUnion.MemberTypes = new XmlQualifiedName[]
            {
                XmlSchemaSimpleType.GetBuiltInSimpleType(XmlTypeCode.DateTime).QualifiedName,
                XmlSchemaSimpleType.GetBuiltInSimpleType(XmlTypeCode.Date).QualifiedName,
                XmlSchemaSimpleType.GetBuiltInSimpleType(XmlTypeCode.GYearMonth).QualifiedName,
                XmlSchemaSimpleType.GetBuiltInSimpleType(XmlTypeCode.GYear).QualifiedName,
                XmlSchemaSimpleType.GetBuiltInSimpleType(XmlTypeCode.Duration).QualifiedName
            };
            /*
            simpleTypeUnion.BaseTypes.Add(XmlSchemaSimpleType.GetBuiltInSimpleType(XmlTypeCode.DateTime));
            simpleTypeUnion.BaseTypes.Add(XmlSchemaSimpleType.GetBuiltInSimpleType(XmlTypeCode.Date));
            simpleTypeUnion.BaseTypes.Add(XmlSchemaSimpleType.GetBuiltInSimpleType(XmlTypeCode.GYearMonth));
            simpleTypeUnion.BaseTypes.Add(XmlSchemaSimpleType.GetBuiltInSimpleType(XmlTypeCode.GYear));
            simpleTypeUnion.BaseTypes.Add(XmlSchemaSimpleType.GetBuiltInSimpleType(XmlTypeCode.Duration));
            */
            CogsSchema.Items.Add(simpleType);

            return simpleType;
        }

        public XmlSchemaComplexType CreateDataType(DataType dataType)
        {
            // create types

            XmlSchemaComplexType complexType = new XmlSchemaComplexType();
            complexType.Name = dataType.Name;
            complexType.AddSchemaDocumentation(dataType.Description);
            CogsSchema.Items.Add(complexType);

            XmlSchemaSequence itemElements = new XmlSchemaSequence();

            if (dataType.IsAbstract)
            {
                complexType.IsAbstract = true;
            }
            if (!string.IsNullOrWhiteSpace(dataType.ExtendsTypeName))
            {
                XmlSchemaComplexContent complexContent = new XmlSchemaComplexContent();
                complexType.ContentModel = complexContent;

                XmlSchemaComplexContentExtension contentExtension = new XmlSchemaComplexContentExtension();
                complexContent.Content = contentExtension;
                contentExtension.BaseTypeName = new XmlQualifiedName(dataType.ExtendsTypeName, TargetNamespace);

                contentExtension.Particle = itemElements;
            }
            else
            {
                complexType.Particle = itemElements;
            }

            foreach (var property in dataType.Properties)
            {

                if (property.Name == "space")
                {
                    continue;//TODO
                }

                CreateElementReference(itemElements, property);
            }

            return complexType;
        }

        private void CreateElementReference(XmlSchemaSequence itemElements, Property property)
        {
            // TODO refactor the model so base classes are used here
            var dataTypes = property.DataTypeName.Split(' ');

            if (!createdElements.ContainsKey(property.Name))
            {
                XmlSchemaElement element = new XmlSchemaElement();
                element.Name = property.Name;

                // if a reference to an item
                if (CogsModel.ItemTypes.Exists(x => dataTypes.Contains(x.Name)))
                {
                    element.SchemaTypeName = new XmlQualifiedName("ReferenceType", TargetNamespace);
                }
                else if(CogsTypes.SimpleTypeNames.Contains(property.DataTypeName))
                {
                    if(string.Equals(property.DataTypeName, CogsTypes.CogsDate, StringComparison.OrdinalIgnoreCase))
                    {
                        // make sure we use the right casing for the xs: type
                        string xsTypeName = CogsTypes.SimpleTypeNames.First(x => x.Equals(property.DataTypeName, StringComparison.OrdinalIgnoreCase));

                        element.SchemaTypeName = new XmlQualifiedName(xsTypeName, TargetNamespace);
                    }
                    else
                    {
                        element.SchemaTypeName = new XmlQualifiedName(property.DataTypeName, XmlSchema.Namespace);
                    }
                }
                else
                {
                    element.SchemaTypeName = new XmlQualifiedName(property.DataTypeName, TargetNamespace);
                }
                CogsSchema.Items.Add(element);
                createdElements[property.Name] = property.DataTypeName;
            }

            // include reference to datatype property
            XmlSchemaElement datatypeRef = new XmlSchemaElement();
            datatypeRef.RefName = new XmlQualifiedName(property.Name, TargetNamespace);
            datatypeRef.MinOccursString = property.MinCardinality == "" ? "0" : property.MinCardinality ?? "0";
            datatypeRef.MaxOccursString = property.MaxCardinality == "n" ? "unbounded" : property.MaxCardinality ?? "unbounded";
            datatypeRef.AddSchemaDocumentation(property.Description);
            itemElements.Items.Add(datatypeRef);
        }

        XmlSchemaComplexType CreateItemContainerType(out XmlSchemaChoice itemChoices)
        {
            // Item Container type
            XmlSchemaComplexType containerType = new XmlSchemaComplexType();
            containerType.Name = "ItemContainerType";
            containerType.AddSchemaDocumentation("Used for serializing a set of items.");

            var sequence = new XmlSchemaSequence();
            containerType.Particle = sequence;

            // Top level reference element
            XmlSchemaElement element = new XmlSchemaElement();
            element.Name = "TopLevelReference";
            element.SchemaTypeName = new XmlQualifiedName("ReferenceType", TargetNamespace);
            element.AddSchemaDocumentation("Denote which items in the Fragment Instance are the main items of interest.");
            CogsSchema.Items.Add(element);

            // include top level reference
            XmlSchemaElement elementRef = new XmlSchemaElement();
            elementRef.RefName = new XmlQualifiedName("TopLevelReference", TargetNamespace);
            elementRef.MinOccurs = 0;
            elementRef.MaxOccursString = "unbounded";
            sequence.Items.Add(elementRef);

            itemChoices = new XmlSchemaChoice();
            itemChoices.MinOccurs = 0;
            itemChoices.MaxOccursString = "unbounded";
            sequence.Items.Add(itemChoices);

            return containerType;
        }

        XmlSchemaComplexType CreateReferenceType()
        {

            DataType reference = new DataType();
            reference.Name = "ReferenceType";
            reference.Description = "Used for referencing an identified item, by lookup of the URN and/or an IRDI identification sequence.";

            reference.Properties.AddRange(CogsModel.Identification);

            Property p = new Property()
            {
                DataTypeName = "string",
                Description = "Strongly typed name of the item which is being referenced.",
                MinCardinality = "1",
                MaxCardinality = "1",
                Name = "TypeOfObject"
            };

            reference.Properties.Add(p);

            return CreateDataType(reference);
        }

        void ValidationCallback(object sender, ValidationEventArgs args)
        {
            if (args.Severity == XmlSeverityType.Warning)
            {
                Errors.Add(new CogsError(ErrorLevel.Warning, args.Message));
            }
            else if (args.Severity == XmlSeverityType.Error)
            {
                Errors.Add(new CogsError(ErrorLevel.Error, args.Message));
            }
        }

        public static XmlNode[] TextToNodeArray(string text)
        {
            XmlDocument doc = new XmlDocument();
            return new XmlNode[1] { doc.CreateTextNode(text) };
        }

    }

    public static class Extensions
    {
        public static void AddSchemaDocumentation(this XmlSchemaAnnotated item, params string[] texts)
        {
            var annotation = new XmlSchemaAnnotation();
            foreach(var text in texts)
            {
                var documentation = new XmlSchemaDocumentation();
                documentation.Language = "en";

                XmlDocument doc = new XmlDocument();
                documentation.Markup = new XmlNode[1] { doc.CreateTextNode(text) };

                annotation.Items.Add(documentation);
            }

            item.Annotation = annotation;
        }

        public static string ToLowerFirstLetter(this string str)
        {
            if (string.IsNullOrWhiteSpace(str))
            {
                return string.Empty;
            }

            if (str.Length == 1)
            {
                return str.ToLower();
            }

            return char.ToLower(str[0]) + str.Substring(1);
        }
    }
}


text:
package org.apache.camel.component.velocity;

import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Test;

public class VelocityDynamicTemplateTest extends CamelTestSupport {

    private Exchange createLetter() {
        Exchange exchange = context.getEndpoint("direct:a").createExchange();
        Message msg = exchange.getIn();
        msg.setHeader("firstName", "Claus");
        msg.setHeader("lastName", "Ibsen");
        msg.setHeader("item", "Camel in Action");
        msg.setBody("PS: Next beer is on me, James");
        return exchange;
    }

    @Test
    public void testVelocityLetter() throws Exception {
        MockEndpoint mock = getMockEndpoint("mock:result");
        mock.expectedMessageCount(1);
        mock.message(0).body(String.class).contains("Thanks for the order of Camel in Action");

        template.send("direct:a", createLetter());

        mock.assertIsSatisfied();

        mock.reset();

        mock.expectedMessageCount(1);
        mock.message(0).body(String.class).contains("Regards Apache Camel Riders Bookstore");

        template.send("direct:a", createLetter());

        mock.assertIsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() throws Exception {
                MyBean bean = new MyBean();
                from("direct:a").bean(bean).to("mock:result");
            }
        };
    }

    public static class MyBean {
        ProducerTemplate template;
        boolean useLetter2;

        public void sendToNewTemplate(Exchange exchange) throws Exception {
            if (template == null) {
                template = exchange.getContext().createProducerTemplate();
            }
            template.send("velocity:" + getNewTemplate(), exchange);
            useLetter2 = !useLetter2;
        }

        private String getNewTemplate() {
            if (useLetter2) {
                return "org/apache/camel/component/velocity/letter2.vm";
            } else {
                return "org/apache/camel/component/velocity/letter.vm";
            }
        }
    }
}


text:
<ion-view view-title="Kronos iKonnect" class="main-pane" cache-view="false" ng-class="vm.dayColor">
  <ion-content>

    <ion-refresher
            pulling-text="Pull to refresh..."
            on-refresh="vm.doRefresh()">
    </ion-refresher>

      Good {{vm.dayColor}}, {{::vm.user.firstname}}
      Here's a look at what's happening.

    <ion-list>

        <ion-item class="item-stable"
                  ng-click="vm.toggleGroup(key)"
                  ng-class="{active: vm.groups[key]}">

          {{key | dayCompare }}
        </ion-item>
        <ion-item class="item-accordion" ng-show="vm.groups[key]">

                Scheduled In: {{ segment.in.time }}

                  Punched @ {{ segment.in.timestamp }}

                  Transferred @ {{ segment.in.timestamp }}

                In {{ segment.location.label }}

                Scheduled Out: {{ segment.out.time }}

                  Punched @ {{ segment.out.timestamp }}

                  Transferred @ {{ segment.out.timestamp }}

              <button class="button button-block button-positive" ng-click="vm.punchIn(key)" ng-switch-when="punch-in">
                I'm ready to punch-in
              </button>
              <button class="button button-block button-positive" ng-click="vm.punchOut(key)" ng-switch-when="punch-out">
                I'm ready to punch-out
              </button>
              <button class="button button-block button-positive" ng-click="vm.transfer('planned')" ng-switch-when="planned-transfer">
                I'm ready to transfer
              </button>

              <button class="button button-block button-positive" ng-click="vm.takeSurvey(key)" ng-switch-when="survey">
                Take me to the survey
              </button>
              <button class="button button-block button-positive" ng-click="vm.transfer('new')" ng-switch-when="new-transfer">
                Transfer to new area
              </button>

              Currently can't punch - searching, but no InTouch detected.

              <button class="button button-block button-positive" ng-click="vm.turnOffMonitoring()">
                Stop searching for InTouch
              </button>

              <button class="button button-block button-positive" ng-click="vm.takeSurvey(key)">
                Take me to the survey
              </button>

        </ion-item>

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


text:
namespace DashCI.Resources.Github {

    export interface IGithubResource extends ng.resource.IResourceClass<any> {
        repository_list(): IRepository[];
        issue_count(param: { owner: string, repository: string; labels: string; state: string }): ICount;
    }

    DashCI.app.factory('githubResources',
        ['$resource', 'globalOptions',
            ($resource: ng.resource.IResourceService, globalOptions: Models.IOptions) => (username: string): IGithubResource => {

            if (!globalOptions || !globalOptions.github || globalOptions.github.length == 0)
                return null;

            var accounts = globalOptions.github.filter((item) => item.username == username);
            if (!accounts || accounts.length != 1)
                return null;
            var host = "https://api.github.com";

            var headers = {
                "Authorization": <string>null,
                //"Access-Control-Request-Headers": "X-Total, X-Page, X-Total-Pages"
            };
            if (accounts[0].privateToken)
                headers.Authorization = "Basic " + btoa(accounts[0].username + ":" + accounts[0].privateToken);
            else
                delete headers.Authorization;

            var transform = (data: any, headers: any) => {
                var data = angular.fromJson(data);
                if (data && typeof(data) === "object")
                    data.headers = headers();

                return data;
                };
            var countParser = (data: any, getHeaders: Function, status: number) => {
                if (status == 200) {
                    data = angular.fromJson(data);
                    var headers = getHeaders();

                    var parsedCount = parseInt(headers["X-Total"]);
                    if (isNaN(parsedCount)) {
                        parsedCount = 0;
                        //cannot access X-Total today, let's parse
                        var links = (<string>headers.link).split('>');
                        angular.forEach(links, (item) => {
                            var matches = item.match(/&page=(\d*)/);
                            if (matches && matches.length > 1) {
                                var page = Number(matches[1]);
                                if (page > parsedCount)
                                    parsedCount = page;
                            }
                        });
                    }
                    var ret = <ICount>{
                        count: parsedCount
                    };
                    return ret;
                }
                else
                    return data;

            };

            // Return the resource, include your custom actions
            return <IGithubResource>$resource(host, {}, {
                repository_list: <ng.resource.IActionDescriptor>{
                    method: 'GET',
                    isArray: true,
                    url: host + "/user/repos?sort=updated&direction=desc&per_page=100",
                    headers: headers,
                    transformResponse: transform,
                    cache: true
                },

                issue_count: <ng.resource.IActionDescriptor>{
                    method: 'GET',
                    isArray: false,
                    url: host + "/repos/:owner/:repository/issues?labels=:labels&state=:state&per_page=1",
                    headers: headers,
                    cache: false,
                    transformResponse: countParser
                },
            });
    }])
}


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/core/loader/http_equiv.h"

#include "services/network/public/mojom/content_security_policy.mojom-blink-forward.h"
#include "third_party/blink/public/platform/web_content_settings_client.h"
#include "third_party/blink/renderer/core/css/style_engine.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/scriptable_document_parser.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/html/html_meta_element.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
#include "third_party/blink/renderer/core/origin_trials/origin_trial_context.h"
#include "third_party/blink/renderer/platform/bindings/v8_binding.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/network/http_names.h"
#include "third_party/blink/renderer/platform/network/http_parsers.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/weborigin/reporting_disposition.h"

namespace blink {

void HttpEquiv::Process(Document& document,
                        const AtomicString& equiv,
                        const AtomicString& content,
                        bool in_document_head_element,
                        Element* element) {
  DCHECK(!equiv.IsNull());
  DCHECK(!content.IsNull());

  if (EqualIgnoringASCIICase(equiv, "default-style")) {
    ProcessHttpEquivDefaultStyle(document, content);
  } else if (EqualIgnoringASCIICase(equiv, "refresh")) {
    ProcessHttpEquivRefresh(document.domWindow(), content, element);
  } else if (EqualIgnoringASCIICase(equiv, "set-cookie")) {
    ProcessHttpEquivSetCookie(document, content, element);
  } else if (EqualIgnoringASCIICase(equiv, "content-language")) {
    document.SetContentLanguage(content);
  } else if (EqualIgnoringASCIICase(equiv, "x-dns-prefetch-control")) {
    document.ParseDNSPrefetchControlHeader(content);
  } else if (EqualIgnoringASCIICase(equiv, "x-frame-options")) {
    document.AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>(
        mojom::ConsoleMessageSource::kSecurity,
        mojom::ConsoleMessageLevel::kError,
        "X-Frame-Options may only be set via an HTTP header sent along with a "
        "document. It may not be set inside <meta>."));
  } else if (EqualIgnoringASCIICase(equiv, http_names::kAcceptCH)) {
    HTMLMetaElement::ProcessMetaAcceptCH(document, content,
                                         /*is_http_equiv*/ true,
                                         /*is_preload_or_sync_parser*/ true);
  } else if (EqualIgnoringASCIICase(equiv, "content-security-policy") ||
             EqualIgnoringASCIICase(equiv,
                                    "content-security-policy-report-only")) {
    if (in_document_head_element) {
      ProcessHttpEquivContentSecurityPolicy(document.domWindow(), equiv,
                                            content);
    } else if (auto* window = document.domWindow()) {
      window->GetContentSecurityPolicy()->ReportMetaOutsideHead(content);
    }
  } else if (EqualIgnoringASCIICase(equiv, http_names::kOriginTrial)) {
    if (in_document_head_element) {
      ProcessHttpEquivOriginTrial(document.domWindow(), content);
    }
  }
}

void HttpEquiv::ProcessHttpEquivContentSecurityPolicy(
    LocalDOMWindow* window,
    const AtomicString& equiv,
    const AtomicString& content) {
  if (!window || !window->GetFrame())
    return;
  if (window->GetFrame()->GetSettings()->GetBypassCSP())
    return;
  if (EqualIgnoringASCIICase(equiv, "content-security-policy")) {
    Vector<network::mojom::blink::ContentSecurityPolicyPtr> parsed =
        ParseContentSecurityPolicies(
            content, network::mojom::blink::ContentSecurityPolicyType::kEnforce,
            network::mojom::blink::ContentSecurityPolicySource::kMeta,
            *(window->GetSecurityOrigin()));
    window->GetContentSecurityPolicy()->AddPolicies(mojo::Clone(parsed));
    window->GetPolicyContainer()->AddContentSecurityPolicies(std::move(parsed));
  } else if (EqualIgnoringASCIICase(equiv,
                                    "content-security-policy-report-only")) {
    window->GetContentSecurityPolicy()->ReportReportOnlyInMeta(content);
  } else {
    NOTREACHED();
  }
}

void HttpEquiv::ProcessHttpEquivDefaultStyle(Document& document,
                                             const AtomicString& content) {
  document.GetStyleEngine().SetHttpDefaultStyle(content);
}

void HttpEquiv::ProcessHttpEquivOriginTrial(LocalDOMWindow* window,
                                            const AtomicString& content) {
  if (!window)
    return;
  // For meta tags injected by script, process the token with the origin of the
  // external script, if available. Get the top 3 script urls from the stack, as
  // the script that injected the meta tag might not be topmost. For example,
  // due to a script that overrides builtin functions, like Node.appendChild().
  // See crbug.com/1193888.
  // NOTE: The external script origin is not considered security-critical. See
  // the comment thread in the design doc for details:
  // https://docs.google.com/document/d/1xALH9W7rWmX0FpjudhDeS2TNTEOXuPn4Tlc9VmuPdHA/edit?disco=AAAAJyG8StI
  Vector<String> candidate_scripts =
      GetScriptUrlsFromCurrentStack(/*unique_url_count=*/3);
  Vector<scoped_refptr<SecurityOrigin>> external_origins;
  for (const String& external_script : candidate_scripts) {
    KURL external_script_url(external_script);
    if (!external_script_url.IsValid())
      continue;
    external_origins.push_back(SecurityOrigin::Create(external_script_url));
  }

  if (external_origins.size() > 0) {
    window->GetOriginTrialContext()->AddTokenFromExternalScript(
        content, external_origins);
    return;
  }

  // Process token as usual, without an external script origin.
  window->GetOriginTrialContext()->AddToken(content);
}

void HttpEquiv::ProcessHttpEquivRefresh(LocalDOMWindow* window,
                                        const AtomicString& content,
                                        Element* element) {
  if (!window)
    return;
  UseCounter::Count(window, WebFeature::kMetaRefresh);
  if (!window->GetContentSecurityPolicy()->AllowInline(
          ContentSecurityPolicy::InlineType::kScript, element, "" /* content */,
          "" /* nonce */, NullURL(), OrdinalNumber::First(),
          ReportingDisposition::kSuppressReporting)) {
    UseCounter::Count(window,
                      WebFeature::kMetaRefreshWhenCSPBlocksInlineScript);
  }

  window->document()->MaybeHandleHttpRefresh(content,
                                             Document::kHttpRefreshFromMetaTag);
}

void HttpEquiv::ProcessHttpEquivSetCookie(Document& document,
                                          const AtomicString& content,
                                          Element* element) {
  document.AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>(
      mojom::ConsoleMessageSource::kSecurity,
      mojom::ConsoleMessageLevel::kError,
      String::Format("Blocked setting the `%s` cookie from a `<meta>` tag.",
                     content.Utf8().c_str())));
}

}  // namespace blink


text:
var gulp = require("gulp"),
modernizr = require("gulp-modernizr");

gulp.task("modernizr", function(){
	return gulp.src(["./user/themes/savage/assets/styles/**/*.css", "./user/themes/savage/assets/scripts/**/*.js"])
		.pipe(modernizr({
			"options": [
				"setClasses"
			]
		}))
		.pipe(gulp.dest("./user/themes/savage/assets/temp/scripts/"));
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>

    <extension point="org.jkiss.dbeaver.expressions">
        <namespace id="geo" class="org.jkiss.dbeaver.model.gis.GisExpressionFunctions" description="GIS functions"/>
    </extension>

    <extension point="org.jkiss.dbeaver.dataTypeProvider">
        <!-- Spatial transformer -->
        <transformer
            class="org.jkiss.dbeaver.data.gis.handlers.GeometryAttributeTransformer"
            id="GeometryAttributeTransformer"
            name="Geometry"
            description="Shows string (WKT) or binary (WKB) value as Geometry (spatial data type)"
            applyByDefault="false"
            custom="true">
            <type kind="STRING"/>
            <type kind="BINARY"/>
            <propertyGroup label="Properties">
                <property id="srid" label="SRID" type="string" description="CRS identifier of source value" defaultValue="4326" required="false" validValues=""/>
                <property id="invertCoordinates" label="Invert coordinates" type="boolean" description="Invert latitude/longitude coordinates" defaultValue="false" required="false"/>
            </propertyGroup>
        </transformer>

    </extension>

</plugin>


text:
get_filename_component(GLSLANG_DIR ${COMPRESSONATOR_PROJECT_DIR}/external/vulkan/vulkan-submodule/${CMAKE_SYSTEM_NAME}/glslang ABSOLUTE)

set(GLSLANG_BUILD_DIR ${CMAKE_CURRENT_BINARY_DIR}/glslang)
file(MAKE_DIRECTORY ${GLSLANG_BUILD_DIR})

if(${shared})
    set(OUTPUT_EXTENSION ".dll")
else()
    set(OUTPUT_EXTENSION ".lib")
endif()
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
    set(GLSLANG_INSTALL_PREFIX ${GLSLANG_INSTALL_PREFIX}d)
    set(GLSLANG_OUTPUTS ${DEPENDENCIES_INSTALL_DIR}/lib/glslangd${OUTPUT_EXTENSION})
else()
    set(GLSLANG_OUTPUTS ${DEPENDENCIES_INSTALL_DIR}/lib/glslang${OUTPUT_EXTENSION})
endif()

add_custom_command(OUTPUT ${GLSLANG_OUTPUTS}
    PRE_BUILD

    COMMENT "Compiling Glslang"

    WORKING_DIRECTORY ${GLSLANG_BUILD_DIR}
    COMMAND ${CMAKE_COMMAND} ${GLSLANG_DIR}
            -DCMAKE_BUILD_TYPE:STRING=${type}
            -DBUILD_SHARED_LIBS:BOOL=${shared}
            -DCMAKE_MSVC_RUNTIME_LIBRARY:STRING="${CMAKE_MSVC_RUNTIME_LIBRARY}"
            -DCMAKE_INSTALL_PREFIX:STRING=${DEPENDENCIES_INSTALL_DIR}
        COMMAND ${CMAKE_COMMAND} --build . --config ${CMAKE_BUILD_TYPE} --parallel ${NUM_PARALLEL_JOBS}
        COMMAND ${CMAKE_COMMAND} --install . --config ${CMAKE_BUILD_TYPE}
)

add_custom_target(glslang

    DEPENDS ${GLSLANG_OUTPUTS}
)


text:
Alter table members ADD column photo_url text;
Alter table activities ADD column city_id integer;


text:
package org.ldp4j.generic.security;

import org.apache.commons.codec.binary.Base64;
import org.ldp4j.generic.core.Handler;
import org.ldp4j.generic.core.HandlerResponse;
import org.ldp4j.generic.core.LDPContext;
import org.ldp4j.generic.core.LDPFault;
import org.ldp4j.generic.http.HttpHeader;
import org.ldp4j.generic.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.StringTokenizer;

public class BasicAuthHandler implements Handler {

    private static final Logger logger = LoggerFactory.getLogger(BasicAuthHandler.class);

    private static final String NAME = "BasicAuthHandler";

    private static String BASIC_AUTH_PREFIX = "Basic ";

    @Override
    public HandlerResponse invoke(LDPContext context) throws LDPFault {

        HttpServletRequest request = context.getServletRequest();
        HttpServletResponse response = context.getServletResponse();

        String authorization = request.getHeader(HttpHeader.AUTHORIZATION.name());

        //No authorization header
        if(authorization == null){
            String msg = "User needs to be authenticated to access this resource.";
            logger.error(msg);
            response.setStatus(HttpStatus.UNAUTHORIZED.code());
            response.setHeader(HttpHeader.WWW_AUTHENTICATE.name(), BASIC_AUTH_PREFIX + "realm=\"LDP4j\"");

            return HandlerResponse.ABORT;
        }

        //Check if value is a basic auth value
        if (!authorization.contains(BASIC_AUTH_PREFIX)) {
            String msg = "User needs to user HTTP Basic Authentication";
            response.setStatus(HttpStatus.UNAUTHORIZED.code());
            response.setHeader(HttpHeader.WWW_AUTHENTICATE.name(), BASIC_AUTH_PREFIX + "realm=\"LDP4j\"");
        }

        // Remove the basic auth prefix
        String basicAuth = authorization.replaceFirst(BASIC_AUTH_PREFIX, "");
        //Decode Base64
        String usernamePassword = new String(Base64.decodeBase64(basicAuth));

        //Split username and password tokens
        StringTokenizer tokenizer = new StringTokenizer(usernamePassword, ":");
        String username = tokenizer.nextToken();
        String password = tokenizer.nextToken();

            return null;
    }

    @Override
    public String getName() {
        return NAME;
    }
}


text:
import { Injectable } from '@angular/core';
import { NgbDateAdapter, NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
import { parseISO } from 'date-fns';

@Injectable({
  providedIn: 'root',
})
export class CustomNgbDateNativeUTCAdapter extends NgbDateAdapter<Date> {
  fromModel(date: Date | string): NgbDateStruct {
    if (date instanceof Date) {
      return {
        year: date.getUTCFullYear(),
        month: date.getUTCMonth() + 1,
        day: date.getUTCDate(),
      };
    }

    if (typeof date === 'string') {
      const parsedDate = parseISO(date);
      return {
        year: parsedDate.getUTCFullYear(),
        month: parsedDate.getUTCMonth() + 1,
        day: parsedDate.getUTCDate(),
      };
    }

    return null;
  }

  toModel(date: NgbDateStruct): Date {
    return date && date.year && date.month ? new Date(Date.UTC(date.year, date.month - 1, date.day)) : null;
  }
}


text:
package net.floodlightcontroller.dcm;

import org.restlet.Context;
import org.restlet.Restlet;
import org.restlet.routing.Router;

import net.floodlightcontroller.restserver.RestletRoutable;

public class DCMWebRoutable implements RestletRoutable {

    @Override
    public Restlet getRestlet(Context context) {
        Router router = new Router(context);
        router.attach("/table/{switch}/json", DCMTable.class);
        return router;
    }

    @Override
    public String basePath() {
        return "/wm/dcm";
    }
}


text:
package org.apache.camel.model.rest.springboot;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import org.apache.camel.CamelContext;
import org.apache.camel.model.rest.RestConstants;
import org.apache.camel.spi.RestConfiguration;
import org.apache.camel.spring.boot.util.CamelPropertiesHelper;
import org.apache.camel.support.IntrospectionSupport;
import org.apache.camel.util.CollectionHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

/**
 * Generated by camel-package-maven-plugin - do not edit this file!
 */
@Generated("org.apache.camel.maven.packaging.SpringBootAutoConfigurationMojo")
@Configuration
@ConditionalOnBean(type = "org.apache.camel.spring.boot.CamelAutoConfiguration")
@ConditionalOnProperty(name = "camel.rest.enabled", matchIfMissing = true)
@AutoConfigureAfter(name = "org.apache.camel.spring.boot.CamelAutoConfiguration")
@EnableConfigurationProperties(RestConfigurationDefinitionProperties.class)
public class RestConfigurationDefinitionAutoConfiguration {

    @Autowired
    private CamelContext camelContext;
    @Autowired
    private RestConfigurationDefinitionProperties config;

    @Lazy
    @Bean(name = RestConstants.DEFAULT_REST_CONFIGURATION_ID)
    @ConditionalOnClass(CamelContext.class)
    @ConditionalOnMissingBean
    public RestConfiguration configureRestConfigurationDefinition()
            throws Exception {
        Map<String, Object> properties = new HashMap<>();
        IntrospectionSupport.getProperties(config, properties, null, false);
        // These options is configured specially further below, so remove them first
        properties.remove("enableCors");
        properties.remove("apiProperty");
        properties.remove("componentProperty");
        properties.remove("consumerProperty");
        properties.remove("dataFormatProperty");
        properties.remove("endpointProperty");
        properties.remove("corsHeaders");

        RestConfiguration definition = new RestConfiguration();
        CamelPropertiesHelper.setCamelProperties(camelContext, definition, properties, true);

        // Workaround for spring-boot properties name as It would appear
        // as enable-c-o-r-s if left uppercase in Configuration
        definition.setEnableCORS(config.getEnableCors());

        if (config.getApiProperty() != null) {
            definition.setApiProperties(new HashMap<>(CollectionHelper.flattenKeysInMap(config.getApiProperty(), ".")));
        }
        if (config.getComponentProperty() != null) {
            definition.setComponentProperties(new HashMap<>(CollectionHelper.flattenKeysInMap(config.getComponentProperty(), ".")));
        }
        if (config.getConsumerProperty() != null) {
            definition.setConsumerProperties(new HashMap<>(CollectionHelper.flattenKeysInMap(config.getConsumerProperty(), ".")));
        }
        if (config.getDataFormatProperty() != null) {
            definition.setDataFormatProperties(new HashMap<>(CollectionHelper.flattenKeysInMap(config.getDataFormatProperty(), ".")));
        }
        if (config.getEndpointProperty() != null) {
            definition.setEndpointProperties(new HashMap<>(CollectionHelper.flattenKeysInMap(config.getEndpointProperty(), ".")));
        }
        if (config.getCorsHeaders() != null) {
            Map<String, Object> map = CollectionHelper.flattenKeysInMap(config.getCorsHeaders(), ".");
            Map<String, String> target = new HashMap<>();
            map.forEach((k, v) -> target.put(k, v.toString()));
            definition.setCorsHeaders(target);
        }
        return definition;
    }
}


text:
package webinvoice

import (
	"math/rand"
	"time"
)

// Kernmerk returns a unique identifier for this invoice.
func Kenmerk(now time.Time) string {
	rand.Seed(time.Now().UnixNano())

	t := now.Format("02012006")
	letters := randString()

	kenmerk := t + letters
	return kenmerk
}

func randString() string {
	b := make([]rune, length)
	for i := range b {
		b[i] = letterRunes[rand.Intn(len(letterRunes))]
	}
	return string(b)
}

var letterRunes = []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ")

const length = 2


text:
warning:     "This is a dynamically generated file. Do not edit manually."
layout:      "default"
title:       "var-name-mixedcase | Solhint"
---

# var-name-mixedcase
![Recommended Badge](https://img.shields.io/badge/-Recommended-brightgreen)
![Category Badge](https://img.shields.io/badge/-Style%20Guide%20Rules-informational)
![Default Severity Badge warn](https://img.shields.io/badge/Default%20Severity-warn-yellow)
> The {"extends": "solhint:recommended"} property in a configuration file enables this rule.

## Description
Variable name must be in mixedCase.

## Options
This rule accepts a string option of rule severity. Must be one of "error", "warn", "off". Default to warn.

### Example Config
```json
{
  "rules": {
    "var-name-mixedcase": "warn"
  }
}
```

## Examples
This rule does not have examples.

## Version
This rule was introduced in [Solhint 2.0.0-alpha.0](https://github.com/protofire/solhint/tree/v2.0.0-alpha.0)

## Resources
- [Rule source](https://github.com/protofire/solhint/tree/master/lib/rules/naming/var-name-mixedcase.js)
- [Document source](https://github.com/protofire/solhint/tree/master/docs/rules/naming/var-name-mixedcase.md)
- [Test cases](https://github.com/protofire/solhint/tree/master/test/rules/naming/var-name-mixedcase.js)


text:
package test

import (
	"reflect"
	"testing"
	"time"

	"github.com/nats-io/go-nats"

	"github.com/nats-io/go-nats/encoders/protobuf"
	pb "github.com/nats-io/go-nats/encoders/protobuf/testdata"
)

func NewProtoEncodedConn(tl TestLogger) *nats.EncodedConn {
	ec, err := nats.NewEncodedConn(NewConnection(tl, TEST_PORT), protobuf.PROTOBUF_ENCODER)
	if err != nil {
		tl.Fatalf("Failed to create an encoded connection: %v\n", err)
	}
	return ec
}

func TestEncProtoMarshalStruct(t *testing.T) {
	s := RunServerOnPort(TEST_PORT)
	defer s.Shutdown()

	ec := NewProtoEncodedConn(t)
	defer ec.Close()
	ch := make(chan bool)

	me := &pb.Person{Name: "derek", Age: 22, Address: "140 New Montgomery St"}
	me.Children = make(map[string]*pb.Person)

	me.Children["sam"] = &pb.Person{Name: "sam", Age: 19, Address: "140 New Montgomery St"}
	me.Children["meg"] = &pb.Person{Name: "meg", Age: 17, Address: "140 New Montgomery St"}

	ec.Subscribe("protobuf_test", func(p *pb.Person) {
		if !reflect.DeepEqual(p, me) {
			t.Fatal("Did not receive the correct protobuf response")
		}
		ch <- true
	})

	ec.Publish("protobuf_test", me)
	if e := Wait(ch); e != nil {
		t.Fatal("Did not receive the message")
	}
}

func TestEncProtoNilRequest(t *testing.T) {
	s := RunServerOnPort(TEST_PORT)
	defer s.Shutdown()

	ec := NewProtoEncodedConn(t)
	defer ec.Close()

	testPerson := &pb.Person{Name: "Anatolii", Age: 25, Address: "Ukraine, Nikolaev"}

	//Subscribe with empty interface shouldn't failed on empty message
	ec.Subscribe("nil_test", func(_, reply string, _ interface{}) {
		ec.Publish(reply, testPerson)
	})

	resp := new(pb.Person)

	//Request with nil argument shouldn't failed with nil argument
	err := ec.Request("nil_test", nil, resp, 100*time.Millisecond)
	ec.Flush()

	if err != nil {
		t.Error("Fail to send empty message via encoded proto connection")
	}

	if !reflect.DeepEqual(testPerson, resp) {
		t.Error("Fail to receive encoded response")
	}
}

func BenchmarkProtobufMarshalStruct(b *testing.B) {
	me := &pb.Person{Name: "derek", Age: 22, Address: "140 New Montgomery St"}
	me.Children = make(map[string]*pb.Person)

	me.Children["sam"] = &pb.Person{Name: "sam", Age: 19, Address: "140 New Montgomery St"}
	me.Children["meg"] = &pb.Person{Name: "meg", Age: 17, Address: "140 New Montgomery St"}

	encoder := &protobuf.ProtobufEncoder{}
	for n := 0; n < b.N; n++ {
		if _, err := encoder.Encode("protobuf_test", me); err != nil {
			b.Fatal("Couldn't serialize object", err)
		}
	}
}

func BenchmarkPublishProtobufStruct(b *testing.B) {
	// stop benchmark for set-up
	b.StopTimer()

	s := RunServerOnPort(TEST_PORT)
	defer s.Shutdown()

	ec := NewProtoEncodedConn(b)
	defer ec.Close()
	ch := make(chan bool)

	me := &pb.Person{Name: "derek", Age: 22, Address: "140 New Montgomery St"}
	me.Children = make(map[string]*pb.Person)

	me.Children["sam"] = &pb.Person{Name: "sam", Age: 19, Address: "140 New Montgomery St"}
	me.Children["meg"] = &pb.Person{Name: "meg", Age: 17, Address: "140 New Montgomery St"}

	ec.Subscribe("protobuf_test", func(p *pb.Person) {
		if !reflect.DeepEqual(p, me) {
			b.Fatalf("Did not receive the correct protobuf response")
		}
		ch <- true
	})

	// resume benchmark
	b.StartTimer()

	for n := 0; n < b.N; n++ {
		ec.Publish("protobuf_test", me)
		if e := Wait(ch); e != nil {
			b.Fatal("Did not receive the message")
		}
	}
}


text:
#ifndef ALKES_GRAPH_GRAPHICS_CONTEXT_H_INCLUDED_
#define ALKES_GRAPH_GRAPHICS_CONTEXT_H_INCLUDED_

#include "alkes/graph/internal.h"
#include "alkes/graph/ScissorStack.h"
#include "alkes/gfx/IGraphics2DDevice.h"

namespace alkes {

class IGraphics3DDevice;

/// \addtogroup scenegraph
//@{

class AL_GRAPH_EXPORT GraphicsContext
{
public:
    GraphicsContext(IGraphics2DDevice* device);
    virtual ~GraphicsContext();

    IGraphics2DDevice* getGraphics2DDevice();
    IGraphics3DDevice* getGraphics3DDevice();

    void pushGlobalScissor(const Rect& scissor);
    void pushLocalScissor(const Rect& scissor);

    void addOffset(int16_t x, int16_t y);
    void minusOffset(int16_t x, int16_t y);

    void pushScissorSize(int16_t w, int16_t h);
    void popScissorRect();
    const Rect& getCurrentScissorRect();
    const Rect& getPrevScissorRect();

    void setOpacity(int16_t opacity);
    int16_t getOpacity() const;
    const Color& modulateColor(Color& color);

private:
    IGraphics2DDevice* device_;
    ScissorStack scissor_;
    int16_t opacity_;
};

//@}

}

#endif


text:
package org.apache.sftp.protocol.packetdata;

import org.apache.sftp.protocol.PacketData;
import org.apache.sftp.protocol.impl.SftpFileAttributes;

public interface BaseAttrs<T> extends PacketData<T> {
    public SftpFileAttributes getFileAttributes();

    public T setFileAttributes( SftpFileAttributes fileAttributes );
}


text:
import bluebird from 'bluebird';

import { SQS } from 'aws-sdk';
import nullLogger from 'null-logger';
import BaseRunner from '../base/base_runner';
import { getContext } from './utils';
import sqsConf from '../config/sqs';

import {
  Hooks,
  IRunner,
  Configuration,
  Pool,
  Logger,
  IRegistry,
  CreateSqsTopic,
  SQSConfiguration,
} from '../common';
import { Steveo } from '..';

const safeParseInt = (concurrency: string, fallback = 1) => {
  if (!concurrency) {
    return fallback;
  }

  const result = parseInt(concurrency, 10);
  if (Number.isNaN(result)) {
    return fallback;
  }

  return result;
};

type DeleteMessage = {
  instance: SQS;
  topic: string;
  message: any;
  sqsUrls: any;
  logger: Logger;
};

/* istanbul ignore next */
const deleteMessage = async ({
  instance,
  topic,
  message,
  sqsUrls,
  logger,
}: DeleteMessage) => {
  const deleteParams = {
    QueueUrl: sqsUrls[topic],
    ReceiptHandle: message.ReceiptHandle,
  };
  try {
    logger.debug('Deleting Message from Queue URL', deleteParams);
    const data = await instance.deleteMessage(deleteParams).promise();
    logger.debug('returned data', data);
    return data;
  } catch (ex) {
    logger.error('sqs deletion error', ex, topic, message);
    throw ex;
  }
};

class SqsRunner extends BaseRunner implements IRunner {
  config: Configuration<SQSConfiguration>;

  logger: Logger;

  registry: IRegistry;

  sqsUrls: any;

  sqs: SQS;

  pool: Pool<any>;

  concurrency: number;

  hooks?: Hooks;

  currentTimeout?: ReturnType<typeof setTimeout>;

  constructor(steveo: Steveo) {
    super(steveo);
    this.hooks = steveo?.hooks;
    this.config = steveo?.config || {};
    this.registry = steveo?.registry;
    this.logger = steveo?.logger ?? nullLogger;
    this.sqsUrls = {};
    this.sqs = sqsConf.sqs(steveo.config);
    this.pool = steveo.pool;
    this.concurrency = safeParseInt(steveo.config.workerConfig?.max, 1);
  }

  async receive(messages: SQS.MessageList, topic: string): Promise<any> {
    this.registry.emit('runner_messages', topic, messages);

    return bluebird.map(
      messages,
      async m => {
        let params;
        let resource;
        try {
          resource = await this.pool.acquire();
          params = JSON.parse(m.Body);
          const runnerContext = getContext(params);

          this.registry.emit('runner_receive', topic, params, runnerContext);
          this.logger.debug('Deleting message', topic, params);

          await deleteMessage({ // eslint-disable-line
            instance: this.sqs,
            topic,
            message: m,
            sqsUrls: this.sqsUrls,
            logger: this.logger,
          });

          this.logger.debug('Message Deleted', topic, params);
          const task = this.registry.getTask(topic);
          this.logger.debug('Start subscribe', topic, params);
          if (!task) {
            this.logger.error(`Unknown Task ${topic}`);
            return;
          }
          if (this.hooks?.preTask) {
            await this.hooks.preTask(params);
          }
          const { context = null, ...value } = params;
          const result = await task.subscribe(value, context);
          if (this.hooks?.postTask) {
            await this.hooks.postTask({ ...(params ?? {}), result });
          }
          this.logger.debug('Completed subscribe', topic, params);
          const completedContext = getContext(params);
          this.registry.emit(
            'runner_complete',
            topic,
            params,
            completedContext
          );
        } catch (ex) {
          this.logger.error('Error while executing consumer callback ', {
            params,
            topic,
            error: ex,
          });
          this.registry.emit('runner_failure', topic, ex, params);
        }
        if (resource) await this.pool.release(resource);
      },
      { concurrency: this.concurrency }
    );
  }

  async dequeue(topic: string, params: SQS.ReceiveMessageRequest) {
    const data = await this.sqs
      .receiveMessage(params)
      .promise()
      .catch(e => {
        this.logger.error('Error while receiving message from queue', e);
        return null;
      });

    if (data?.Messages) {
      this.logger.debug('Message from sqs', data);
      try {
        await this.receive(data.Messages, topic);
      } catch (ex) {
        this.logger.error('Error while invoking receive', ex);
      }
    }
  }

  async process(topics?: string[]) {
    const loop = () => {
      if (this.steveo.exiting) return;
      if (this.currentTimeout) clearTimeout(this.currentTimeout);

      this.currentTimeout = setTimeout(
        this.process.bind(this, topics),
        this.config.consumerPollInterval ?? 1000
      );
    };

    if (this.paused) {
      this.logger.debug(`paused processing`);
      loop();
      return;
    }

    const subscriptions = this.getActiveSubsciptions(topics);
    this.logger.debug(
      `Polling for messages (${topics ? topics.join(',') : 'all'})`
    );

    await bluebird.map(
      subscriptions,
      async topic => {
        const queueURL = await this.getQueueUrl(topic);
        if (queueURL) {
          this.logger.debug(`starting processing of ${topic} with ${queueURL}`);

          const params = {
            MaxNumberOfMessages: this.config.maxNumberOfMessages,
            QueueUrl: queueURL,
            VisibilityTimeout: this.config.visibilityTimeout,
            WaitTimeSeconds: this.config.waitTimeSeconds,
          };
          await this.dequeue(topic, params);
        } else {
          this.logger.error(`Queue URL ${topic} not found`);
        }
      },
      { concurrency: this.concurrency }
    );
    loop();
  }

  healthCheck = async function() {
    // get a random registered queue
    const items = this.registry.getTopics();
    const item = items[Math.floor(Math.random() * items.length)];
    await this.sqs.getQueueUrl({ QueueName: item }).promise();
  };

  async getQueueUrl(topic: string) {
    if (!this.sqsUrls[topic]) {
      this.logger.debug(`url not cached for ${topic}`);
      const url = await this.getUrl(topic);
      if (url) {
        this.sqsUrls[topic] = url;
      }
    }

    return this.sqsUrls[topic];
  }

  getUrl(topic: string) {
    return this.sqs
      .getQueueUrl({ QueueName: topic })
      .promise()
      .then(data => data && data?.QueueUrl)
      .catch(e => {
        this.logger.error(e);
        return null;
      });
  }

  async createQueue({
    topic,
    receiveMessageWaitTimeSeconds = '20',
    messageRetentionPeriod = '604800',
  }: CreateSqsTopic) {
    const params = {
      QueueName: topic,
      Attributes: {
        ReceiveMessageWaitTimeSeconds: receiveMessageWaitTimeSeconds,
        MessageRetentionPeriod: messageRetentionPeriod,
      },
    };
    await this.sqs.createQueue(params).promise();
  }

  async disconnect() {
    if (this.currentTimeout) clearTimeout(this.currentTimeout);
  }

  async reconnect() {}
}

export default SqsRunner;


text:
angular.module('MyApp')
  .controller('ReviewsCtrl', ['$scope', 'reviewService', function($scope, reviewService) {
    $scope.reviews = reviewService.getReviews();

    $scope.addUpvote = function(review, currentUpvote) {
      reviewService.addUpvote(review, currentUpvote);
    };

    $scope.predicate = 'reviewDate';
    $scope.order = function(predicate) {
      $scope.predicate = predicate;
    };

    $scope.expand = false;

    $scope.voted = false;

    //Check to see if the window is top if not then display button
    var toTopButton = $('#scrollToTop');
    var mobileToTopButton = $('#mobile-scrollToTop');

    // hide both mobile or desktop version immediately at first load
    toTopButton.hide();
    mobileToTopButton.hide();

    // Check the scrollTop and check the width to show diff button
    $(window).scroll(function() {
      if ($(this).scrollTop() > 130) {
        if ($(this).width() > 700) {
          toTopButton.fadeIn();
        } else {
          mobileToTopButton.fadeIn();
        }
      } else {
        toTopButton.hide();
        mobileToTopButton.hide();
      }
    });

    // Click event to both toTop buttons
    // $('.class1').add('.class2').click(some_function);
    toTopButton.add(mobileToTopButton).click(function() {
      $('html, body').animate({
        scrollTop: 0
      }, 800);
      return false;
    });

  }]);


text:
<?php

// list all fields from a given template, with edit-links, type, name, label and indication if set to required

$tpl 		= $page->template;
$f 			= $tpl->fields;
$adminUrl 	= $config->urls->admin;

echo "

name	label	type	required?	id

";
foreach($f as $ff) {
    $required = '';
    if($ff->required) {
        $required = 'x';
    }
    echo "
{$ff->name}	{$ff->label}	{$ff->type}	$required	id}'>{$ff->id}
";
}
echo "

";


text:
package org.momentumjs.gradle.js.engine.plugins;

import org.gradle.api.Incubating;
import org.momentumjs.gradle.js.engine.JsEngine;
import org.momentumjs.gradle.js.engine.JsEngineDescriptor;

/**
 * Base class available for JsEngine implementations
 */
@Incubating
public abstract class AbstractJsEngine implements JsEngine {

    private final JsEngineDescriptor descriptor;

    public AbstractJsEngine(JsEngineDescriptor descriptor) {
        if (descriptor == null) {
            throw new IllegalArgumentException("JsEngine descriptor cannot be null");
        }
        this.descriptor = descriptor;
    }

    @Override
    public String getName() {
        return descriptor.getEngineName() + "-" + descriptor.getEngineVersion();
    }

    @Override
    public JsEngineDescriptor getDescriptor() {
        return descriptor;
    }

}


text:
int main(int argc, char** argv) {
   return be::service<o::Game>()(argc, argv).run();
}


text:
require 'spec/spec_helper'

describe ThinkingSphinx::Index::Builder do
  describe ".generate without source scope" do
    before :each do
      @index = ThinkingSphinx::Index::Builder.generate(Person) do
        indexes first_name, last_name
        has birthday
        has id, :as => :internal_id

        set_property :sql_range_step => 1000

        where "birthday <= NOW()"
        group_by "first_name"
      end

      @source = @index.sources.first
    end

    it "should return an index" do
      @index.should be_a_kind_of(ThinkingSphinx::Index)
    end

    it "should have one source for the index" do
      @index.sources.length.should == 1
    end

    it "should have two fields" do
      @source.fields.length.should == 2
      @source.fields[0].unique_name.should == :first_name
      @source.fields[1].unique_name.should == :last_name
    end

    it "should have two attributes alongside the four internal ones" do
      @source.attributes.length.should == 6
      @source.attributes[4].unique_name.should == :birthday
      @source.attributes[5].unique_name.should == :internal_id
    end

    it "should have one condition" do
      @source.conditions.length.should == 1
      @source.conditions.first.should == "birthday <= NOW()"
    end

    it "should have one grouping" do
      @source.groupings.length.should == 1
      @source.groupings.first.should == "first_name"
    end

    it "should have one option" do
      @source.options.length.should == 1
      @source.options[:sql_range_step].should == 1000
    end
  end

  describe "sortable field" do
    before :each do
      @index = ThinkingSphinx::Index::Builder.generate(Person) do
        indexes first_name, :sortable => true
      end

      @source = @index.sources.first
    end

    it "should have one field" do
      @source.fields.length.should == 1
    end

    it "should have one attribute alongside the four internal ones" do
      @source.attributes.length.should == 5
    end

    it "should set the attribute name to have the _sort suffix" do
      @source.attributes.last.unique_name.should == :first_name_sort
    end

    it "should set the attribute column to be the same as the field" do
      @source.attributes.last.columns.length.should == 1
      @source.attributes.last.columns.first.__name.should == :first_name
    end
  end

  describe "faceted field" do
    before :each do
      @index = ThinkingSphinx::Index::Builder.generate(Person) do
        indexes first_name, :facet => true
      end

      @source = @index.sources.first
    end

    after :each do
      Person.sphinx_facets.delete_at(-1)
    end

    it "should have one field" do
      @source.fields.length.should == 1
    end

    it "should have one attribute alongside the four internal ones" do
      @source.attributes.length.should == 5
    end

    it "should set the attribute name to have the _facet suffix" do
      @source.attributes.last.unique_name.should == :first_name_facet
    end

    it "should set the attribute type to integer" do
      @source.attributes.last.type.should == :integer
    end

    it "should set the attribute column to be the same as the field" do
      @source.attributes.last.columns.length.should == 1
      @source.attributes.last.columns.first.__name.should == :first_name
    end
  end

  describe "faceted integer attribute" do
    before :each do
      @index = ThinkingSphinx::Index::Builder.generate(Alpha) do
        indexes :name
        has value, :facet => true
      end

      @source = @index.sources.first
    end

    after :each do
      Alpha.sphinx_facets.delete_at(-1)
    end

    it "should have just one attribute alongside the four internal ones" do
      @source.attributes.length.should == 5
    end
  end

  describe "faceted timestamp attribute" do
    before :each do
      @index = ThinkingSphinx::Index::Builder.generate(Person) do
        indexes first_name
        has birthday, :facet => true
      end

      @source = @index.sources.first
    end

    after :each do
      Person.sphinx_facets.delete_at(-1)
    end

    it "should have just one attribute alongside the four internal ones" do
      @source.attributes.length.should == 5
    end
  end

  describe "faceted boolean attribute" do
    before :each do
      @index = ThinkingSphinx::Index::Builder.generate(Beta) do
        indexes :name
        has delta, :facet => true
      end

      @source = @index.sources.first
    end

    after :each do
      Beta.sphinx_facets.delete_at(-1)
    end

    it "should have just one attribute alongside the four internal ones" do
      @source.attributes.length.should == 5
    end
  end

  describe "faceted float attribute" do
    before :each do
      @index = ThinkingSphinx::Index::Builder.generate(Alpha) do
        indexes :name
        has cost, :facet => true
      end

      @source = @index.sources.first
    end

    after :each do
      Alpha.sphinx_facets.delete_at(-1)
    end

    it "should have just one attribute alongside the four internal ones" do
      @source.attributes.length.should == 5
    end
  end

  describe "faceted string attribute" do
    before :each do
      @index = ThinkingSphinx::Index::Builder.generate(Person) do
        indexes first_name
        has last_name, :facet => true
      end

      @source = @index.sources.first
    end

    after :each do
      Person.sphinx_facets.delete_at(-1)
    end

    it "should have two attributes alongside the four internal ones" do
      @source.attributes.length.should == 6
    end

    it "should set the facet attribute name to have the _facet suffix" do
      @source.attributes.last.unique_name.should == :last_name_facet
    end

    it "should set the attribute type to integer" do
      @source.attributes.last.type.should == :integer
    end

    it "should set the attribute column to be the same as the field" do
      @source.attributes.last.columns.length.should == 1
      @source.attributes.last.columns.first.__name.should == :last_name
    end
  end

  describe "no fields" do
    it "should raise an exception" do
      lambda {
        ThinkingSphinx::Index::Builder.generate(Person) do
          #
        end
      }.should raise_error
    end
  end

  describe "explicit source" do
    before :each do
      @index = ThinkingSphinx::Index::Builder.generate(Person) do
        define_source do
          indexes first_name, last_name
          has birthday
          has id, :as => :internal_id

          set_property :delta => true

          where "birthday <= NOW()"
          group_by "first_name"
        end
      end

      @source = @index.sources.first
    end

    it "should return an index" do
      @index.should be_a_kind_of(ThinkingSphinx::Index)
    end

    it "should have one source for the index" do
      @index.sources.length.should == 1
    end

    it "should have two fields" do
      @source.fields.length.should == 2
      @source.fields[0].unique_name.should == :first_name
      @source.fields[1].unique_name.should == :last_name
    end

    it "should have two attributes alongside the four internal ones" do
      @source.attributes.length.should == 6
      @source.attributes[4].unique_name.should == :birthday
      @source.attributes[5].unique_name.should == :internal_id
    end
  end

  describe "multiple sources" do
    before :each do
      @index = ThinkingSphinx::Index::Builder.generate(Person) do
        define_source do
          indexes first_name
          has birthday
        end

        define_source do
          indexes last_name
          has :id, :as => :internal_id
        end
      end
    end

    it "should have two sources" do
      @index.sources.length.should == 2
    end

    it "should have two fields" do
      @index.fields.length.should == 2
    end

    it "should have one field in each source" do
      @index.sources.each do |source|
        source.fields.length.should == 1
      end
    end

    it "should have two attributes alongside the eight internal ones" do
      @index.attributes.length.should == 10
    end

    it "should have one attribute in each source alongside the four internal ones" do
      @index.sources.each do |source|
        source.attributes.length.should == 5
      end
    end
  end

  describe "index options" do
    before :each do
      @index = ThinkingSphinx::Index::Builder.generate(Person) do
        indexes first_name

        set_property :charset_type => "utf16"
        set_property :group_concat_max_len => 1024
      end
    end

    it "should store the index setting for the index" do
      @index.local_options[:charset_type].should == "utf16"
    end

    it "should store non-Sphinx settings for the index" do
      @index.local_options[:group_concat_max_len].should == 1024
    end
  end

  describe "delta options" do
    before :each do
      @index = ThinkingSphinx::Index::Builder.generate(Person) do
        indexes first_name

        set_property :delta => true
      end
    end

    it "should not keep the delta setting in source options" do
      @index.sources.first.options.should be_empty
    end

    it "should not keep the delta setting in index options" do
      @index.local_options.should be_empty
    end

    it "should set the index delta object set" do
      @index.delta_object.should be_a_kind_of(ThinkingSphinx::Deltas::DefaultDelta)
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="de.greenrobot.performance.realm">

    <application>
        <!-- empty application tag -->
    </application>
</manifest>


text:
require File.join(File.dirname(__FILE__), '..', '..', 'spec_helper')

describe Yad::Framework::Rails do

  it "should build the setup command" do
    cmd = Yad::Framework::Rails.build_setup_command('path/to/shared/directory', :umask => '02')
    cmd.should eql("umask 02 && mkdir -p path/to/shared/directory/log path/to/shared/directory/pids path/to/shared/directory/system")
  end

  it "should build the update command" do
    cmd = Yad::Framework::Rails.build_update_command('path/to/new/release', 'path/to/shared/directory', :app_env => 'production', :framework_update_db_config_via => 'none')
    cmd.should eql("rm -rf path/to/new/release/log path/to/new/release/public/system path/to/new/release/tmp/pids && mkdir -p path/to/new/release/tmp && ln -s path/to/shared/directory/log path/to/new/release/log && ln -s path/to/shared/directory/pids path/to/new/release/tmp/pids && ln -s path/to/shared/directory/system path/to/new/release/public/system")
  end

  it "should build the update command with db config setup via copy" do
    cmd = Yad::Framework::Rails.build_update_command('path/to/new/release', 'path/to/shared/directory', :app_env => 'production', :framework_update_db_config_via => 'copy')
    cmd.should eql("rm -rf path/to/new/release/log path/to/new/release/public/system path/to/new/release/tmp/pids && mkdir -p path/to/new/release/tmp && ln -s path/to/shared/directory/log path/to/new/release/log && ln -s path/to/shared/directory/pids path/to/new/release/tmp/pids && ln -s path/to/shared/directory/system path/to/new/release/public/system && cp -f path/to/new/release/config/database_production.yml path/to/new/release/config/database.yml")
  end

  it "should build the update command with db config setup via symlink" do
    cmd = Yad::Framework::Rails.build_update_command('path/to/new/release', 'path/to/shared/directory', :app_env => 'production', :framework_update_db_config_via => 'symlink')
    cmd.should eql("rm -rf path/to/new/release/log path/to/new/release/public/system path/to/new/release/tmp/pids && mkdir -p path/to/new/release/tmp && ln -s path/to/shared/directory/log path/to/new/release/log && ln -s path/to/shared/directory/pids path/to/new/release/tmp/pids && ln -s path/to/shared/directory/system path/to/new/release/public/system && ln -nfs path/to/shared/directory/config/database.yml path/to/new/release/config/database.yml")
  end

end


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Petrophile sessilis Sieber ex Schult.

### Remarks
null