text:
// -*- C++ -*-

//=============================================================================
/**
 *  @file    Based_Pointer_T.h
 *
 *  @author Dietrich Quehl <Dietrich.Quehl@med.siemens.de>
 *  @author Douglas C. Schmidt <schmidt@.cs.wustl.edu>
 */
//=============================================================================

#ifndef ACE_BASED_POINTER_T_H
#define ACE_BASED_POINTER_T_H

#include /**/ "ace/pre.h"

#include /**/ "ace/config-all.h"
#include "ace/Basic_Types.h"

#if defined (_MSC_VER)
// Suppress warning e.g. "return type for
// 'ACE_Based_Pointer<long>::operator ->' is 'long *' (i.e., not a UDT
// or reference to a UDT.  Will produce errors if applied using infix
// notation)"
#pragma warning(disable: 4284)
#endif /* _MSC_VER */

ACE_BEGIN_VERSIONED_NAMESPACE_DECL

/**
 * @class ACE_Based_Pointer_Basic
 *
 * @brief A proxy that keeps track of the relative offset of a "pointer"
 * from its base address.
 * This class makes it possible to transparently use "pointers" in
 * shared memory as easily as programming with pointers to local
 * memory.  In particular, we don't need to ensure that the base
 * addresses of all the pointers are mapped into separate
 * processes at the same absolute memory base address.
 */
template <class CONCRETE>
class ACE_Based_Pointer_Basic
{
public:
  /**
   * This constructor initializes the <base_offset_> by asking the
   * <ACE_BASED_POINTER_REPOSITORY> Singleton for the base address of
   * the memory region within which it is instantiated.  Two results
   * are possible:
   *
   * 1. An <ACE_*_Memory_Pool> has stored a base address/size pair and the
   *    new based-pointer instance is located between the base address and
   *    the base address + size - 1.  In this case, the repository
   *    returns the base address.
   *
   * 2. No suitable address/size pair was found.  The repository
   *    assumes an address in the regular (not mapped) virtual address
   *    space of the process and returns 0.  In this case, the
   *    based-pointer uses its address as an offset to it's base
   *    address 0.
   */
  ACE_Based_Pointer_Basic (void);

  /**
   * Initialize this object using the @a initial pointer.  This
   * constructor initializes the <base_offset_> by asking the
   * <ACE_BASED_POINTER_REPOSITORY> Singleton for the base address of
   * the memory region within which it is instantiated.  Three results
   * are possible:
   *
   * 1. An <ACE_*_Memory_Pool> has stored a base address/size pair and the
   *    new based-pointer instance is located between the base address and
   *    the base address + size - 1.  In this case, the repository
   *    returns the base address.
   *
   * 2. No suitable address/size pair was found.  The repository
   *    assumes an address in the regular (not mapped) virtual address
   *    space of the process and returns 0.  In this case, the
   *    based-pointer uses its address as an offset to its base
   *    address 0.
   *
   * 3. If @a initial is 0 then set the value of <target_> to -1, which
   *    indicates a "NULL" pointer.
   */
  ACE_Based_Pointer_Basic (CONCRETE *initial);

  /// Copy constructor.
  ACE_Based_Pointer_Basic (const ACE_Based_Pointer_Basic<CONCRETE> &);

  /// Constructor for know base address. @a o is only used to
  /// resolve overload ambiguity.
  ACE_Based_Pointer_Basic (const void *base_addr, int o);

  /// Pseudo-assignment operator.
  void operator = (CONCRETE *from);

  /// Pseudo-assignment operator.
  void operator = (const ACE_Based_Pointer_Basic<CONCRETE> &);

  /// Dereference operator.
  CONCRETE operator * (void) const;

  /// Less than operator.
  bool operator < (const ACE_Based_Pointer_Basic<CONCRETE> &) const;

  /// Less than or equal operator.
  bool operator <= (const ACE_Based_Pointer_Basic<CONCRETE> &) const;

  /// Greater than operator.
  bool operator > (const ACE_Based_Pointer_Basic<CONCRETE> &) const;

  /// Greater than or equal operator.
  bool operator >= (const ACE_Based_Pointer_Basic<CONCRETE> &) const;

  /// Equality operator.
  bool operator == (const ACE_Based_Pointer_Basic<CONCRETE> &) const;

  /// Inequality operator.
  bool operator != (const ACE_Based_Pointer_Basic<CONCRETE> &) const;

  /// Subscript operator.
  CONCRETE operator [](int index) const;

  /// Increment operator.
  void operator+= (int index);

  /// Returns the underlying memory address of the smart pointer.
  operator CONCRETE *() const;

  /// Returns the underlying memory address of the smart pointer.
  CONCRETE *addr (void) const;

  /// Declare the dynamic allocation hooks.
  ACE_ALLOC_HOOK_DECLARE;

  /// Dump the state of the object.
  void dump (void) const;

protected:
  ptrdiff_t target_;

  /// Keep track of our offset from the base pointer.
  ptrdiff_t base_offset_;
};

/**
 * @class ACE_Based_Pointer
 *
 * @brief A smart proxy that keeps track of the relative offset of a
 * "pointer" from its base address.
 *
 * This class makes it possible to transparently use "pointers" in
 * shared memory as easily as programming with pointers to local
 * memory by overloading the C++ delegation operator ->().
 */
template <class CONCRETE>
class ACE_Based_Pointer : public ACE_Based_Pointer_Basic<CONCRETE>
{
public:
  // = Initialization method.
  /// Constructor.  See constructor for ACE_Based_Pointer_Basic for
  /// details.
  ACE_Based_Pointer (void);

  /// Initialize this object using the <initial> pointer.  See
  /// constructor for ACE_Based_Pointer_Basic for details.
  ACE_Based_Pointer (CONCRETE *initial);

  /// Initialize this object with known @a base_addr.  @a dummy is
  /// a dummy value used to resolve overload ambiguity and it
  /// otherwise ignored.
  ACE_Based_Pointer (const void *base_addr, int dummy);

  /// Copy constructor (not implemented yet).
  ACE_Based_Pointer (const ACE_Based_Pointer<CONCRETE> &);

  /// Assignment operator.
  void operator = (const ACE_Based_Pointer<CONCRETE> &);

  /// Pseudo-assignment operator.
  void operator = (CONCRETE *from);

  /// The C++ "delegation operator".
  CONCRETE *operator-> (void);
};

ACE_END_VERSIONED_NAMESPACE_DECL

#if defined (__ACE_INLINE__)
#include "ace/Based_Pointer_T.inl"
#endif /* __ACE_INLINE__ */

#if defined (ACE_TEMPLATES_REQUIRE_SOURCE)
#include "ace/Based_Pointer_T.cpp"
#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */

#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA)
#pragma implementation ("Based_Pointer_T.cpp")
#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */

#include /**/ "ace/post.h"

#endif /* ACE_BASED_POINTER_T_H */


text:
<title>Fluffs</title>
<link rel="stylesheet" type="text/css" href="style.css"/>

Fluffs

This site is fucking awesome. We are fucking awesome. We made a game called Dookie. It's in VR and shit.

Click above to buy Dookie, the best game ever

1996 Fluffs Inc

redpajama_set_name: RedPajamaGithub


text:
require "calculator"

describe Calculator do

  let(:calc){ Calculator.new }

  describe "#add" do
    it "returns an integer" do
      expect(calc.add 1, 1).to be_an Integer
    end

    context "when adding zero to an integer" do
      it "returns the integer" do
        expect(calc.add 4, 0).to eq 4
      end
    end

    it "is NOT dependent on the operation order" do
      expect(calc.add 1, 2).to eq calc.add(2, 1)
    end

    it "accepts more than 2 arguments" do
      expect(calc.add 2, 4, 3).to eq 9
    end
  end

  describe "#subtract" do
    it "returns an integer" do
      expect(calc.subtract 3, 2).to be_an Integer
    end

    context "when subtracting zero" do
      it "returns the integer" do
        expect(calc.subtract 5, 0).to eq 5
      end
    end

    context "when subracting an integer from itself" do
      it "returns zero" do
        expect(calc.subtract 5, 5).to eq 0
      end
    end

    it "IS dependent on the operation order" do
      expect(calc.subtract 5,4).not_to eq calc.subtract(4,5)
    end

    it "accepts more than 2 arguments" do
      expect(calc.subtract 5,1,2).to eq 2
    end

  end

  describe "#multiply" do

    it "returns an integer" do
      expect(calc.multiply 1, 2).to be_an Integer
    end

    context "when multiplying by zero" do
      it "returns zero" do
        expect(calc.multiply 5, 0).to eq 0
      end
    end

    it "is NOT dependent on the operation order" do
      expect(calc.multiply 3, 4).to eq calc.multiply(4, 3)
    end

    context "when multiplying an integer by one" do
      it "returns the first integer" do
        expect(calc.multiply 5, 1).to eq 5
      end
    end

      it "should accept more than two numbers" do
        expect(calc.multiply 5, 3, 2).to eq 30
      end
  end

  describe "#divide"

    it "should return and integer" do
      expect(calc.divide 4, 2).to be_an Integer
    end

    it "IS dependent on the order of operation" do
      expect(calc.divide 4, 2).not_to eq calc.divide(2, 4)
    end

    context "when dividing an integer by one" do
      it "returns the first integer" do
        expect(calc.divide 4, 1).to eq 4
      end
    end

    context "when dividing zero by an integer" do
      it "returns zero" do
        expect(calc.divide 0, 3).to eq 0
      end
    end

    context "when divizing an integer by zero" do
      it "returns an error" do
        expect{(calc.divide 3, 0)}.to raise_exception{ZeroDivisionError}
      end
    end

    it "should accept more than two numbers" do
      expect(calc.divide 8, 2, 2).to eq 2
    end

end


text:
The following tags should be usable just as they are in regular HTML:

<html-enumerate-all-tags />

Attributes are passed through verbatim and not checked.

## Table of contents

The Table of Contents plugin introduces one new tag:

```html
<table-of-contents
  max-depth=3
  include-heading=true />
```

The table of contents takes the top level of its hierarchy from your config
file. See
[Defining table of contents structure with `file_hierarchy`](configuration.html#Defining-table-of-contents-structure-with-file_hierarchy)
for details.

The titles and intra-document structure are taken from the heading nodes.

The output looks like this:

```html
<h1>Table of Contents</h1>
<nav class="table-of-contents">
  <ol>
    <li>
      Heading 1
      <ol>
        <li>Subheading 1</li>
      </ol>
    </li>
  </ol>
</nav>
```

You can optionally customize the text of the title ("Table of Contents") by
adding content to the tag:

```
<table-of-contents>Table of Comp-Tents</table-of-contents>
```

## Callouts

You can call out a note or a warning using—wait for it—`<note>` and
`<warning>`. Use `no-prefix=true` to omit the automatic first line of bold
text.

<warning>If you want to put multiple paragraphs in an aside, you need to put
the opening and closing tags in their own paragraphs. See
<heading-link name="parser-bugs" />.
</warning>

### Example 1

```html
<note>This is a note.</note>

<note no-prefix=true>
This is another note.
</note>
```

<note>This is a note.</note>

### Example 2

```html
<note no-prefix=true>

**Another note**

This is a multi-paragraph note with a custom first line.

</note>
```

<note no-prefix=true>

**Another note**

This is a multi-paragraph note with a custom first line.

</note>

### Example 3

```html
<warning>This is a warning.</warning>
```

<warning>This is a warning.</warning>

## Linking to sections

You can define a "heading alias" like this:

```html
<heading-alias name="configuration" />
# Configuring Foobar
```

You can then link to the section like this:

```html
Check out the <heading-link name="configuration" /> section.
```

This will automatically include the heading's contents and link to it:

> Check out the [Configuring Foobar](#not-a-real-link) section.

You can set custom link text by just using the non-self-closing version:

```html
Check out the
<heading-link name="configuration">Configuration</heading-link>
```

> Check out the [Configuration](#not-a-real-link) section.

## Python documentation

Computer Words supports including documentation from *symbol files*. These
can be generated for Python 3.5 like this:

```sh
python3 -m computerwords.source_parsers.python35 . mymodule \
  > docs/symbols.json
```

<note>
Computer words currently supports *only* Python 3.5 for source parsing. Adding
support for more parsers is probably one of the easier things to contribute,
though! To add a new Python source parser, just copy
[this file](https://github.com/irskep/computerwords/blob/master/computerwords/source_parsers/python35.py),
make the necessary tweaks for the version you want to support, and send a
pull request.
</note>

Then tell Computer Words where to find the symbol file in your config like
this:

```js
{
    "python": {
        "symbols_path": "./symbols.json"
    }
}
```

(Remember, all paths in the config file are relative to the config file's
directory.)

Now you can use the `<autodoc-python />` tag to include source docs in your
Markdown files:

```html
<autodoc-python
    module="my.module"
    include-children=True
    render-absolute-path=True
    heading-level=2 />
```

### Attributes

* `module`/`class`/`method`/`function`: path to the symbol to be included
* `include-children`: If `True`, also show definitions and docstrings of all
  classes and functions in the module
* `render-absolute-path`: If `True` (default), show the fully qualified path
  for the symbol (e.g. `computerwords.plugin.CWPlugin` rather than just
  `CWPlugin`). Children, if included, will be rendered with this value as
  `False`.
* `heading-level`: If you don't want the module's name to be a top-level
  heading, set this to 2 to use `h2`, 3 to use `h3`, etc.

### Missing features

* Including individual classes and functions
* Convenient linking to symbols

### Why the intermediate JSON step?

Because the general interface with source parsers needs to work for languages
besides Python. Languages tend to have parsers for themselves in their standard
libraries; Computer Words should make use of them.


text:
from netforce.model import Model, fields, get_model
from netforce.database import get_connection
import time
from datetime import *
from collections import deque
import heapq
from netforce.utils import print_color

class ComputeCost(Model):
    _name="stock.compute.cost"
    _transient=True

    def compute_cost(self,ids,context={}):
        print_color("COMPUTING COST...","green")
        self.compute_cost_standard(context=context);
        self.compute_cost_fifo(context=context);
        self.compute_cost_avg(context=context);
        self.compute_cost_lifo(context=context);
        get_model("field.cache").clear_cache(model="stock.location")
        return {
            "next": {
                "name": "stock_board",
            },
            "flash": "Inventory cost updated successfully.",
        }

    def compute_cost_standard(self,context={}):
        uoms={}
        for uom in get_model("uom").search_browse([]):
            uoms[uom.id]=uom.ratio
        locations={}
        for loc in get_model("stock.location").search_browse([["type","=","internal"]]):
            locations[loc.id]={}
        db=get_connection()
        print("reading...")
        q="SELECT m.id,m.date,m.product_id,p.cost_method,p.uom_id as prod_uom_id,m.qty,m.uom_id,m.cost_amount,m.location_from_id,m.location_to_id,m.move_id,p.cost_price AS prod_cost_price FROM stock_move m,product p WHERE p.cost_method='standard' AND p.type='stock' AND p.id=m.product_id AND m.state='done'"
        args=[]
        product_ids=context.get("product_ids")
        if product_ids:
            q+=" AND m.product_id IN %s"
            args.append(tuple(product_ids))
        q+=" ORDER BY m.date,m.id"
        res=db.query(q,*args)
        moves=[]
        prod_ids=set([])
        for r in res:
            #print("MOVE date=%s prod=%s from=%s to=%s qty=%s method=%s"%(r.date,r.product_id,r.location_from_id,r.location_to_id,r.qty,r.cost_method))
            loc_from=locations.get(r.location_from_id)
            loc_to=locations.get(r.location_to_id)
            move={
                "id": r.id,
                "qty": r.qty,
                "old_cost_amount": r.cost_amount,
            }
            if loc_from:
                ratio=uoms[r.uom_id]/uoms[r.prod_uom_id]
                move["cost_amount"]=(r.prod_cost_price or 0)*ratio*r.qty
            else:
                move["cost_amount"]=r.cost_amount
            moves.append(move)
            prod_ids.add(r.product_id)
        print("writing...")
        for m in moves:
            if m["cost_amount"]!=m["old_cost_amount"]:
                cost_price=m["cost_amount"]/m["qty"] if m["qty"] and m["cost_amount"] else 0
                db.execute("UPDATE stock_move SET cost_amount=%s,cost_price=%s WHERE id=%s",m["cost_amount"],cost_price,m["id"])
        prod_ids=list(prod_ids)
        if prod_ids:
            db.execute("UPDATE product SET update_balance=true WHERE id IN %s",tuple(prod_ids))

    def compute_cost_avg(self,context={}):
        print("compute_cost_avg")
        uoms={}
        for uom in get_model("uom").search_browse([]):
            uoms[uom.id]=uom.ratio
        locations={}
        for loc in get_model("stock.location").search_browse([["type","=","internal"]]):
            locations[loc.id]={}
        db=get_connection()
        print("reading...")
        q="SELECT m.id,m.date,m.product_id,p.cost_method,p.uom_id as prod_uom_id,m.qty,m.uom_id,m.cost_amount,m.location_from_id,m.location_to_id,m.move_id,m.cost_fixed FROM stock_move m,product p WHERE p.cost_method='average' AND p.type='stock' AND p.id=m.product_id AND m.state='done'"
        args=[]
        product_ids=context.get("product_ids")
        if product_ids:
            q+=" AND m.product_id IN %s"
            args.append(tuple(product_ids))
        q+=" ORDER BY m.date,m.id"
        res=db.query(q,*args)
        prod_moves={}
        for r in res:
            #print("MOVE date=%s prod=%s from=%s to=%s qty=%s method=%s"%(r.date,r.product_id,r.location_from_id,r.location_to_id,r.qty,r.cost_method))
            prod_id=r.product_id
            ratio=uoms[r.uom_id]/uoms[r.prod_uom_id]
            move={
                "id": r.id,
                "date": r.date,
                "qty": r.qty,
                "conv_qty": r.qty*ratio,
                "old_cost_amount": r.cost_amount,
                "cost_amount": r.cost_amount or 0,
                "loc_from_id": r.location_from_id,
                "loc_to_id": r.location_to_id,
                "cost_fixed": r.cost_fixed,
            }
            prod_moves.setdefault(prod_id,[]).append(move)
        prod_ids=sorted(prod_moves.keys())
        print("computing...")
        for prod_id in prod_ids:
            print("START prod_id",prod_id)
            for loc in locations.values():
                loc["qty"]=0
                loc["amt"]=0
            moves=prod_moves[prod_id]
            for m in moves:
                loc_from=locations.get(m["loc_from_id"])
                if loc_from:
                    if not m["cost_fixed"]:
                        if loc_from["qty"]>0 and loc_from["amt"]>0:
                            m["cost_amount"]=round(min(m["conv_qty"],loc_from["qty"])*loc_from["amt"]/loc_from["qty"],2)
                        else:
                            m["cost_amount"]=0
                    loc_from["qty"]-=m["conv_qty"]
                    loc_from["amt"]-=m["cost_amount"]
                #print("[%s] move #%s: %s -> %s, %s @ %s (%s)"%(m["date"],m["id"],m["loc_from_id"],m["loc_to_id"],m["conv_qty"],m["cost_amount"],"calc" if loc_from else "read"))
                loc_to=locations.get(m["loc_to_id"])
                if loc_to:
                    loc_to["qty"]+=m["conv_qty"]
                    loc_to["amt"]+=m["cost_amount"]
        print("writing...")
        for prod_id in prod_ids:
            moves=prod_moves[prod_id]
            for m in moves:
                if m["cost_amount"]!=m["old_cost_amount"]:
                    cost_price=m["cost_amount"]/m["conv_qty"] if m["conv_qty"] else 0
                    db.execute("UPDATE stock_move SET cost_amount=%s, cost_price=%s WHERE id=%s",m["cost_amount"],cost_price,m["id"])
        if prod_ids:
            db.execute("UPDATE product SET update_balance=true WHERE id IN %s",tuple(prod_ids))

    def compute_cost_fifo(self,context={}):
        print("compute_cost_fifo")
        uoms={}
        for uom in get_model("uom").search_browse([]):
            uoms[uom.id]=uom.ratio
        int_locs={}
        for loc in get_model("stock.location").search_browse([["type","=","internal"]]):
            int_locs[loc.id]=True
        db=get_connection()
        print("reading...")
        q="SELECT m.id,m.date,m.product_id,p.cost_method,p.uom_id as prod_uom_id,m.qty,m.uom_id,m.cost_amount,m.location_from_id,m.location_to_id,m.move_id FROM stock_move m,product p WHERE p.cost_method='fifo' AND p.type='stock' AND p.id=m.product_id AND m.state='done'"
        args=[]
        product_ids=context.get("product_ids")
        if product_ids:
            q+=" AND m.product_id IN %s"
            args.append(tuple(product_ids))
        res=db.query(q,*args)
        prod_moves={}
        for r in res:
            print("MOVE date=%s prod=%s from=%s to=%s qty=%s method=%s"%(r.date,r.product_id,r.location_from_id,r.location_to_id,r.qty,r.cost_method))
            prod_id=r.product_id
            ratio=uoms[r.uom_id]/uoms[r.prod_uom_id]
            conv_qty=r.qty*ratio
            move={
                "id": r.id,
                "date": r.date,
                "qty": r.qty,
                "conv_qty": conv_qty,
                "location_from_id": r.location_from_id,
                "location_to_id": r.location_to_id,
                "old_cost_amount": r.cost_amount,
            }
            loc_from=int_locs.get(r.location_from_id)
            if not loc_from: #FIXME
                move["qty_in"]=conv_qty
                unit_price=r.cost_amount/conv_qty if conv_qty else 0
                move["unit_price"]=unit_price
                move["cost"]=conv_qty*unit_price
            else:
                move["qty_in"]=0
                move["unit_price"]=None
                move["cost"]=0
            prod_moves.setdefault(prod_id,[]).append(move)
        prod_ids=sorted(prod_moves.keys())
        print("computing...")
        for prod_id in prod_ids:
            print("START prod_id",prod_id)
            moves=prod_moves[prod_id]
            inputs=[]
            loc_outputs={}
            for m in moves:
                loc_from=int_locs.get(m["location_from_id"])
                loc_to=int_locs.get(m["location_to_id"])
                if loc_to and m["unit_price"]:
                    inputs.append((m["date"],m["id"],m))
                if loc_from:
                    loc_outputs.setdefault(m["location_from_id"],[]).append((m["date"],m["id"],m))
            heapq.heapify(inputs)
            for outputs in loc_outputs.values():
                heapq.heapify(outputs)
            loc_queues={}
            def _print_moves():
                print("=== moves ================================")
                for m in moves:
                    print("id=%(id)s date=%(date)s qty=%(qty)s unit_price=%(unit_price)s loc_from=%(loc_from_id)s loc_to=%(loc_to_id)s qty_in=%(qty_in)s cost=%(cost)s"%m)
            def _get_first_input():
                if not inputs:
                    return None
                return inputs[0][2]
            def _get_first_output(loc_id):
                outputs=loc_outputs.get(loc_id)
                if not outputs:
                    return None
                return outputs[0][2]
            def _transfer_to_loc(qty,price,loc_id):
                q=loc_queues.setdefault(loc_id,deque())
                q.append((qty,price))
                _transfer_to_output(loc_id)
            def _transfer_to_output(loc_id):
                q=loc_queues.get(loc_id)
                while q:
                    m=_get_first_output(loc_id)
                    if not m:
                        break
                    print("OUT %s"%m["id"])
                    qty_remain=m["qty"]-m["qty_in"]
                    (first_qty,first_price)=q[0]
                    if first_qty>qty_remain:
                        use_qty=qty_remain
                        q[0]=(first_qty-use_qty,first_price)
                    else:
                        use_qty=first_qty
                        q.popleft()
                    use_cost=use_qty*first_price
                    m["qty_in"]+=use_qty
                    m["cost"]+=use_cost
                    if m["qty_in"]>=m["qty"]:
                        m["unit_price"]=m["cost"]/m["qty"] if m["qty"] else 0
                        outputs=loc_outputs[loc_id]
                        heapq.heappop(outputs)
                        loc_to=int_locs.get(m["location_to_id"])
                        if loc_to:
                            heapq.heappush(inputs,(m["date"],m["id"],m))
            while 1:
                #_print_moves()
                m=_get_first_input()
                if not m:
                    break
                print("IN %s"%m["id"])
                _transfer_to_loc(m["qty_in"],m["unit_price"],m["location_to_id"])
                m["qty_in"]=0
                heapq.heappop(inputs)
            print("DONE prod_id",prod_id)
            #_print_moves()
        print("writing...")
        for prod_id in prod_ids:
            moves=prod_moves[prod_id]
            for m in moves:
                if m["qty"]==0: # XXX: don't overwrite LC stock moves
                    continue
                if m["unit_price"] is not None:
                    new_cost_amount=m["unit_price"]*m["conv_qty"]
                else:
                    new_cost_amount=0
                if new_cost_amount!=m["old_cost_amount"]:
                    new_cost_price=new_cost_amount/m["qty"] if m["qty"] else 0
                    db.execute("UPDATE stock_move SET cost_amount=%s, cost_price=%s WHERE id=%s",new_cost_amount,new_cost_price,m["id"])
        if prod_ids:
            db.execute("UPDATE product SET update_balance=true WHERE id IN %s",tuple(prod_ids))

    def compute_cost_lifo(self,context={}):
        print("compute_cost_lifo")
        # XXX: add this

ComputeCost.register()


text:
namespace AnimalHierarchy
{
    public class Tomcat : Cat, ISound, ICat, IAnimal
    {
        public Tomcat(string name, double age)
            : base(name, age, SexTypes.Male)
        {
        }

        public override string Speak()
        {
            return "Meow-tommy!";
        }
    }
}


text:
/* jshint maxparams:false */

var $ = require('jquery');

/**
 * @param  {String} name
 *
 * @return {Function}
 */
module.exports = function ( name ) {

	/**
	 * @param  {Object}   ctx
	 * @param  {String}   eventName
	 * @param  {Array}    data
	 * @param  {jQuery}   triggerEl
	 */
	return function ( ctx, eventName, data, triggerEl ) {
		var el = (ctx.dom && ctx.dom.el) || ctx.$el || $({});
		if ( ctx.options[eventName] ) {
			ctx.options[eventName].apply((el.length === 1 ? el[0] : el.toArray()), data);
		}
		(triggerEl || el).trigger(((name || '') + eventName).toLowerCase(), data);
	};

};


text:
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->

<link rel="import" href="../../polymer/polymer.html">
<link rel="import" href="../../paper-icon-button/paper-icon-button.html">
<link rel="import" href="../../iron-icons/iron-icons.html">
<link rel="import" href="../../paper-styles/color.html">
<link rel="import" href="../paper-badge.html">

<dom-module id="test-button">
  <style>
    :host {
      display: inline-block;
      position: relative;
    }

    paper-icon-button {
      padding: 0;
      margin: 0;
    }

    paper-badge {
      --paper-badge-background: var(--paper-light-blue-300);
    }
  </style>
  <template>
      <paper-icon-button icon="menu" alt="menu"></paper-icon-button>
      <paper-badge label="♠"></paper-badge>
  </template>

  <script>
    Polymer({
      is: 'test-button'
    });
  </script>
</dom-module>


text:
module Azure::SQL::Mgmt::V2017_03_01_preview
  #
  # The Azure SQL Database management API provides a RESTful set of web
  # services that interact with Azure SQL Database services to manage your
  # databases. The API enables you to create, retrieve, update, and delete
  # databases.
  #
  class JobTargetExecutions
    include MsRestAzure

    #
    # Creates and initializes a new instance of the JobTargetExecutions class.
    # @param client service class for accessing basic functionality.
    #
    def initialize(client)
      @client = client
    end

    # @return [SqlManagementClient] reference to the SqlManagementClient
    attr_reader :client

    #
    # Lists target executions for all steps of a job execution.
    #
    # @param resource_group_name [String] The name of the resource group that
    # contains the resource. You can obtain this value from the Azure Resource
    # Manager API or the portal.
    # @param server_name [String] The name of the server.
    # @param job_agent_name [String] The name of the job agent.
    # @param job_name [String] The name of the job to get.
    # @param job_execution_id The id of the job execution
    # @param create_time_min [DateTime] If specified, only job executions created
    # at or after the specified time are included.
    # @param create_time_max [DateTime] If specified, only job executions created
    # before the specified time are included.
    # @param end_time_min [DateTime] If specified, only job executions completed at
    # or after the specified time are included.
    # @param end_time_max [DateTime] If specified, only job executions completed
    # before the specified time are included.
    # @param is_active [Boolean] If specified, only active or only completed job
    # executions are included.
    # @param skip [Integer] The number of elements in the collection to skip.
    # @param top [Integer] The number of elements to return from the collection.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [Array<JobExecution>] operation results.
    #
    def list_by_job_execution(resource_group_name, server_name, job_agent_name, job_name, job_execution_id, create_time_min:nil, create_time_max:nil, end_time_min:nil, end_time_max:nil, is_active:nil, skip:nil, top:nil, custom_headers:nil)
      first_page = list_by_job_execution_as_lazy(resource_group_name, server_name, job_agent_name, job_name, job_execution_id, create_time_min:create_time_min, create_time_max:create_time_max, end_time_min:end_time_min, end_time_max:end_time_max, is_active:is_active, skip:skip, top:top, custom_headers:custom_headers)
      first_page.get_all_items
    end

    #
    # Lists target executions for all steps of a job execution.
    #
    # @param resource_group_name [String] The name of the resource group that
    # contains the resource. You can obtain this value from the Azure Resource
    # Manager API or the portal.
    # @param server_name [String] The name of the server.
    # @param job_agent_name [String] The name of the job agent.
    # @param job_name [String] The name of the job to get.
    # @param job_execution_id The id of the job execution
    # @param create_time_min [DateTime] If specified, only job executions created
    # at or after the specified time are included.
    # @param create_time_max [DateTime] If specified, only job executions created
    # before the specified time are included.
    # @param end_time_min [DateTime] If specified, only job executions completed at
    # or after the specified time are included.
    # @param end_time_max [DateTime] If specified, only job executions completed
    # before the specified time are included.
    # @param is_active [Boolean] If specified, only active or only completed job
    # executions are included.
    # @param skip [Integer] The number of elements in the collection to skip.
    # @param top [Integer] The number of elements to return from the collection.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def list_by_job_execution_with_http_info(resource_group_name, server_name, job_agent_name, job_name, job_execution_id, create_time_min:nil, create_time_max:nil, end_time_min:nil, end_time_max:nil, is_active:nil, skip:nil, top:nil, custom_headers:nil)
      list_by_job_execution_async(resource_group_name, server_name, job_agent_name, job_name, job_execution_id, create_time_min:create_time_min, create_time_max:create_time_max, end_time_min:end_time_min, end_time_max:end_time_max, is_active:is_active, skip:skip, top:top, custom_headers:custom_headers).value!
    end

    #
    # Lists target executions for all steps of a job execution.
    #
    # @param resource_group_name [String] The name of the resource group that
    # contains the resource. You can obtain this value from the Azure Resource
    # Manager API or the portal.
    # @param server_name [String] The name of the server.
    # @param job_agent_name [String] The name of the job agent.
    # @param job_name [String] The name of the job to get.
    # @param job_execution_id The id of the job execution
    # @param create_time_min [DateTime] If specified, only job executions created
    # at or after the specified time are included.
    # @param create_time_max [DateTime] If specified, only job executions created
    # before the specified time are included.
    # @param end_time_min [DateTime] If specified, only job executions completed at
    # or after the specified time are included.
    # @param end_time_max [DateTime] If specified, only job executions completed
    # before the specified time are included.
    # @param is_active [Boolean] If specified, only active or only completed job
    # executions are included.
    # @param skip [Integer] The number of elements in the collection to skip.
    # @param top [Integer] The number of elements to return from the collection.
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def list_by_job_execution_async(resource_group_name, server_name, job_agent_name, job_name, job_execution_id, create_time_min:nil, create_time_max:nil, end_time_min:nil, end_time_max:nil, is_active:nil, skip:nil, top:nil, custom_headers:nil)
      fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
      fail ArgumentError, 'server_name is nil' if server_name.nil?
      fail ArgumentError, 'job_agent_name is nil' if job_agent_name.nil?
      fail ArgumentError, 'job_name is nil' if job_name.nil?
      fail ArgumentError, 'job_execution_id is nil' if job_execution_id.nil?
      fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
      fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?

      request_headers = {}
      request_headers['Content-Type'] = 'application/json; charset=utf-8'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
      path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/jobs/{jobName}/executions/{jobExecutionId}/targets'

      request_url = @base_url || @client.base_url

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          path_params: {'resourceGroupName' => resource_group_name,'serverName' => server_name,'jobAgentName' => job_agent_name,'jobName' => job_name,'jobExecutionId' => job_execution_id,'subscriptionId' => @client.subscription_id},
          query_params: {'createTimeMin' => create_time_min,'createTimeMax' => create_time_max,'endTimeMin' => end_time_min,'endTimeMax' => end_time_max,'isActive' => is_active,'$skip' => skip,'$top' => top,'api-version' => @client.api_version},
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = @client.make_request_async(:get, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 200
          error_model = JSON.load(response_content)
          fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
        result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
        # Deserialize Response
        if status_code == 200
          begin
            parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
            result_mapper = Azure::SQL::Mgmt::V2017_03_01_preview::Models::JobExecutionListResult.mapper()
            result.body = @client.deserialize(result_mapper, parsed_response)
          rescue Exception => e
            fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
          end
        end

        result
      end

      promise.execute
    end

    #
    # Lists the target executions of a job step execution.
    #
    # @param resource_group_name [String] The name of the resource group that
    # contains the resource. You can obtain this value from the Azure Resource
    # Manager API or the portal.
    # @param server_name [String] The name of the server.
    # @param job_agent_name [String] The name of the job agent.
    # @param job_name [String] The name of the job to get.
    # @param job_execution_id The id of the job execution
    # @param step_name [String] The name of the step.
    # @param create_time_min [DateTime] If specified, only job executions created
    # at or after the specified time are included.
    # @param create_time_max [DateTime] If specified, only job executions created
    # before the specified time are included.
    # @param end_time_min [DateTime] If specified, only job executions completed at
    # or after the specified time are included.
    # @param end_time_max [DateTime] If specified, only job executions completed
    # before the specified time are included.
    # @param is_active [Boolean] If specified, only active or only completed job
    # executions are included.
    # @param skip [Integer] The number of elements in the collection to skip.
    # @param top [Integer] The number of elements to return from the collection.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [Array<JobExecution>] operation results.
    #
    def list_by_step(resource_group_name, server_name, job_agent_name, job_name, job_execution_id, step_name, create_time_min:nil, create_time_max:nil, end_time_min:nil, end_time_max:nil, is_active:nil, skip:nil, top:nil, custom_headers:nil)
      first_page = list_by_step_as_lazy(resource_group_name, server_name, job_agent_name, job_name, job_execution_id, step_name, create_time_min:create_time_min, create_time_max:create_time_max, end_time_min:end_time_min, end_time_max:end_time_max, is_active:is_active, skip:skip, top:top, custom_headers:custom_headers)
      first_page.get_all_items
    end

    #
    # Lists the target executions of a job step execution.
    #
    # @param resource_group_name [String] The name of the resource group that
    # contains the resource. You can obtain this value from the Azure Resource
    # Manager API or the portal.
    # @param server_name [String] The name of the server.
    # @param job_agent_name [String] The name of the job agent.
    # @param job_name [String] The name of the job to get.
    # @param job_execution_id The id of the job execution
    # @param step_name [String] The name of the step.
    # @param create_time_min [DateTime] If specified, only job executions created
    # at or after the specified time are included.
    # @param create_time_max [DateTime] If specified, only job executions created
    # before the specified time are included.
    # @param end_time_min [DateTime] If specified, only job executions completed at
    # or after the specified time are included.
    # @param end_time_max [DateTime] If specified, only job executions completed
    # before the specified time are included.
    # @param is_active [Boolean] If specified, only active or only completed job
    # executions are included.
    # @param skip [Integer] The number of elements in the collection to skip.
    # @param top [Integer] The number of elements to return from the collection.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def list_by_step_with_http_info(resource_group_name, server_name, job_agent_name, job_name, job_execution_id, step_name, create_time_min:nil, create_time_max:nil, end_time_min:nil, end_time_max:nil, is_active:nil, skip:nil, top:nil, custom_headers:nil)
      list_by_step_async(resource_group_name, server_name, job_agent_name, job_name, job_execution_id, step_name, create_time_min:create_time_min, create_time_max:create_time_max, end_time_min:end_time_min, end_time_max:end_time_max, is_active:is_active, skip:skip, top:top, custom_headers:custom_headers).value!
    end

    #
    # Lists the target executions of a job step execution.
    #
    # @param resource_group_name [String] The name of the resource group that
    # contains the resource. You can obtain this value from the Azure Resource
    # Manager API or the portal.
    # @param server_name [String] The name of the server.
    # @param job_agent_name [String] The name of the job agent.
    # @param job_name [String] The name of the job to get.
    # @param job_execution_id The id of the job execution
    # @param step_name [String] The name of the step.
    # @param create_time_min [DateTime] If specified, only job executions created
    # at or after the specified time are included.
    # @param create_time_max [DateTime] If specified, only job executions created
    # before the specified time are included.
    # @param end_time_min [DateTime] If specified, only job executions completed at
    # or after the specified time are included.
    # @param end_time_max [DateTime] If specified, only job executions completed
    # before the specified time are included.
    # @param is_active [Boolean] If specified, only active or only completed job
    # executions are included.
    # @param skip [Integer] The number of elements in the collection to skip.
    # @param top [Integer] The number of elements to return from the collection.
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def list_by_step_async(resource_group_name, server_name, job_agent_name, job_name, job_execution_id, step_name, create_time_min:nil, create_time_max:nil, end_time_min:nil, end_time_max:nil, is_active:nil, skip:nil, top:nil, custom_headers:nil)
      fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
      fail ArgumentError, 'server_name is nil' if server_name.nil?
      fail ArgumentError, 'job_agent_name is nil' if job_agent_name.nil?
      fail ArgumentError, 'job_name is nil' if job_name.nil?
      fail ArgumentError, 'job_execution_id is nil' if job_execution_id.nil?
      fail ArgumentError, 'step_name is nil' if step_name.nil?
      fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
      fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?

      request_headers = {}
      request_headers['Content-Type'] = 'application/json; charset=utf-8'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
      path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/jobs/{jobName}/executions/{jobExecutionId}/steps/{stepName}/targets'

      request_url = @base_url || @client.base_url

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          path_params: {'resourceGroupName' => resource_group_name,'serverName' => server_name,'jobAgentName' => job_agent_name,'jobName' => job_name,'jobExecutionId' => job_execution_id,'stepName' => step_name,'subscriptionId' => @client.subscription_id},
          query_params: {'createTimeMin' => create_time_min,'createTimeMax' => create_time_max,'endTimeMin' => end_time_min,'endTimeMax' => end_time_max,'isActive' => is_active,'$skip' => skip,'$top' => top,'api-version' => @client.api_version},
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = @client.make_request_async(:get, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 200
          error_model = JSON.load(response_content)
          fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
        result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
        # Deserialize Response
        if status_code == 200
          begin
            parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
            result_mapper = Azure::SQL::Mgmt::V2017_03_01_preview::Models::JobExecutionListResult.mapper()
            result.body = @client.deserialize(result_mapper, parsed_response)
          rescue Exception => e
            fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
          end
        end

        result
      end

      promise.execute
    end

    #
    # Gets a target execution.
    #
    # @param resource_group_name [String] The name of the resource group that
    # contains the resource. You can obtain this value from the Azure Resource
    # Manager API or the portal.
    # @param server_name [String] The name of the server.
    # @param job_agent_name [String] The name of the job agent.
    # @param job_name [String] The name of the job to get.
    # @param job_execution_id The unique id of the job execution
    # @param step_name [String] The name of the step.
    # @param target_id The target id.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [JobExecution] operation results.
    #
    def get(resource_group_name, server_name, job_agent_name, job_name, job_execution_id, step_name, target_id, custom_headers:nil)
      response = get_async(resource_group_name, server_name, job_agent_name, job_name, job_execution_id, step_name, target_id, custom_headers:custom_headers).value!
      response.body unless response.nil?
    end

    #
    # Gets a target execution.
    #
    # @param resource_group_name [String] The name of the resource group that
    # contains the resource. You can obtain this value from the Azure Resource
    # Manager API or the portal.
    # @param server_name [String] The name of the server.
    # @param job_agent_name [String] The name of the job agent.
    # @param job_name [String] The name of the job to get.
    # @param job_execution_id The unique id of the job execution
    # @param step_name [String] The name of the step.
    # @param target_id The target id.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def get_with_http_info(resource_group_name, server_name, job_agent_name, job_name, job_execution_id, step_name, target_id, custom_headers:nil)
      get_async(resource_group_name, server_name, job_agent_name, job_name, job_execution_id, step_name, target_id, custom_headers:custom_headers).value!
    end

    #
    # Gets a target execution.
    #
    # @param resource_group_name [String] The name of the resource group that
    # contains the resource. You can obtain this value from the Azure Resource
    # Manager API or the portal.
    # @param server_name [String] The name of the server.
    # @param job_agent_name [String] The name of the job agent.
    # @param job_name [String] The name of the job to get.
    # @param job_execution_id The unique id of the job execution
    # @param step_name [String] The name of the step.
    # @param target_id The target id.
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def get_async(resource_group_name, server_name, job_agent_name, job_name, job_execution_id, step_name, target_id, custom_headers:nil)
      fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
      fail ArgumentError, 'server_name is nil' if server_name.nil?
      fail ArgumentError, 'job_agent_name is nil' if job_agent_name.nil?
      fail ArgumentError, 'job_name is nil' if job_name.nil?
      fail ArgumentError, 'job_execution_id is nil' if job_execution_id.nil?
      fail ArgumentError, 'step_name is nil' if step_name.nil?
      fail ArgumentError, 'target_id is nil' if target_id.nil?
      fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
      fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?

      request_headers = {}
      request_headers['Content-Type'] = 'application/json; charset=utf-8'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
      path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/jobs/{jobName}/executions/{jobExecutionId}/steps/{stepName}/targets/{targetId}'

      request_url = @base_url || @client.base_url

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          path_params: {'resourceGroupName' => resource_group_name,'serverName' => server_name,'jobAgentName' => job_agent_name,'jobName' => job_name,'jobExecutionId' => job_execution_id,'stepName' => step_name,'targetId' => target_id,'subscriptionId' => @client.subscription_id},
          query_params: {'api-version' => @client.api_version},
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = @client.make_request_async(:get, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 200
          error_model = JSON.load(response_content)
          fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
        result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
        # Deserialize Response
        if status_code == 200
          begin
            parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
            result_mapper = Azure::SQL::Mgmt::V2017_03_01_preview::Models::JobExecution.mapper()
            result.body = @client.deserialize(result_mapper, parsed_response)
          rescue Exception => e
            fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
          end
        end

        result
      end

      promise.execute
    end

    #
    # Lists target executions for all steps of a job execution.
    #
    # @param next_page_link [String] The NextLink from the previous successful call
    # to List operation.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [JobExecutionListResult] operation results.
    #
    def list_by_job_execution_next(next_page_link, custom_headers:nil)
      response = list_by_job_execution_next_async(next_page_link, custom_headers:custom_headers).value!
      response.body unless response.nil?
    end

    #
    # Lists target executions for all steps of a job execution.
    #
    # @param next_page_link [String] The NextLink from the previous successful call
    # to List operation.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def list_by_job_execution_next_with_http_info(next_page_link, custom_headers:nil)
      list_by_job_execution_next_async(next_page_link, custom_headers:custom_headers).value!
    end

    #
    # Lists target executions for all steps of a job execution.
    #
    # @param next_page_link [String] The NextLink from the previous successful call
    # to List operation.
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def list_by_job_execution_next_async(next_page_link, custom_headers:nil)
      fail ArgumentError, 'next_page_link is nil' if next_page_link.nil?

      request_headers = {}
      request_headers['Content-Type'] = 'application/json; charset=utf-8'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
      path_template = '{nextLink}'

      request_url = @base_url || @client.base_url

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          skip_encoding_path_params: {'nextLink' => next_page_link},
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = @client.make_request_async(:get, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 200
          error_model = JSON.load(response_content)
          fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
        result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
        # Deserialize Response
        if status_code == 200
          begin
            parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
            result_mapper = Azure::SQL::Mgmt::V2017_03_01_preview::Models::JobExecutionListResult.mapper()
            result.body = @client.deserialize(result_mapper, parsed_response)
          rescue Exception => e
            fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
          end
        end

        result
      end

      promise.execute
    end

    #
    # Lists the target executions of a job step execution.
    #
    # @param next_page_link [String] The NextLink from the previous successful call
    # to List operation.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [JobExecutionListResult] operation results.
    #
    def list_by_step_next(next_page_link, custom_headers:nil)
      response = list_by_step_next_async(next_page_link, custom_headers:custom_headers).value!
      response.body unless response.nil?
    end

    #
    # Lists the target executions of a job step execution.
    #
    # @param next_page_link [String] The NextLink from the previous successful call
    # to List operation.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def list_by_step_next_with_http_info(next_page_link, custom_headers:nil)
      list_by_step_next_async(next_page_link, custom_headers:custom_headers).value!
    end

    #
    # Lists the target executions of a job step execution.
    #
    # @param next_page_link [String] The NextLink from the previous successful call
    # to List operation.
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def list_by_step_next_async(next_page_link, custom_headers:nil)
      fail ArgumentError, 'next_page_link is nil' if next_page_link.nil?

      request_headers = {}
      request_headers['Content-Type'] = 'application/json; charset=utf-8'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
      path_template = '{nextLink}'

      request_url = @base_url || @client.base_url

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          skip_encoding_path_params: {'nextLink' => next_page_link},
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = @client.make_request_async(:get, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 200
          error_model = JSON.load(response_content)
          fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
        result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
        # Deserialize Response
        if status_code == 200
          begin
            parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
            result_mapper = Azure::SQL::Mgmt::V2017_03_01_preview::Models::JobExecutionListResult.mapper()
            result.body = @client.deserialize(result_mapper, parsed_response)
          rescue Exception => e
            fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
          end
        end

        result
      end

      promise.execute
    end

    #
    # Lists target executions for all steps of a job execution.
    #
    # @param resource_group_name [String] The name of the resource group that
    # contains the resource. You can obtain this value from the Azure Resource
    # Manager API or the portal.
    # @param server_name [String] The name of the server.
    # @param job_agent_name [String] The name of the job agent.
    # @param job_name [String] The name of the job to get.
    # @param job_execution_id The id of the job execution
    # @param create_time_min [DateTime] If specified, only job executions created
    # at or after the specified time are included.
    # @param create_time_max [DateTime] If specified, only job executions created
    # before the specified time are included.
    # @param end_time_min [DateTime] If specified, only job executions completed at
    # or after the specified time are included.
    # @param end_time_max [DateTime] If specified, only job executions completed
    # before the specified time are included.
    # @param is_active [Boolean] If specified, only active or only completed job
    # executions are included.
    # @param skip [Integer] The number of elements in the collection to skip.
    # @param top [Integer] The number of elements to return from the collection.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [JobExecutionListResult] which provide lazy access to pages of the
    # response.
    #
    def list_by_job_execution_as_lazy(resource_group_name, server_name, job_agent_name, job_name, job_execution_id, create_time_min:nil, create_time_max:nil, end_time_min:nil, end_time_max:nil, is_active:nil, skip:nil, top:nil, custom_headers:nil)
      response = list_by_job_execution_async(resource_group_name, server_name, job_agent_name, job_name, job_execution_id, create_time_min:create_time_min, create_time_max:create_time_max, end_time_min:end_time_min, end_time_max:end_time_max, is_active:is_active, skip:skip, top:top, custom_headers:custom_headers).value!
      unless response.nil?
        page = response.body
        page.next_method = Proc.new do |next_page_link|
          list_by_job_execution_next_async(next_page_link, custom_headers:custom_headers)
        end
        page
      end
    end

    #
    # Lists the target executions of a job step execution.
    #
    # @param resource_group_name [String] The name of the resource group that
    # contains the resource. You can obtain this value from the Azure Resource
    # Manager API or the portal.
    # @param server_name [String] The name of the server.
    # @param job_agent_name [String] The name of the job agent.
    # @param job_name [String] The name of the job to get.
    # @param job_execution_id The id of the job execution
    # @param step_name [String] The name of the step.
    # @param create_time_min [DateTime] If specified, only job executions created
    # at or after the specified time are included.
    # @param create_time_max [DateTime] If specified, only job executions created
    # before the specified time are included.
    # @param end_time_min [DateTime] If specified, only job executions completed at
    # or after the specified time are included.
    # @param end_time_max [DateTime] If specified, only job executions completed
    # before the specified time are included.
    # @param is_active [Boolean] If specified, only active or only completed job
    # executions are included.
    # @param skip [Integer] The number of elements in the collection to skip.
    # @param top [Integer] The number of elements to return from the collection.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [JobExecutionListResult] which provide lazy access to pages of the
    # response.
    #
    def list_by_step_as_lazy(resource_group_name, server_name, job_agent_name, job_name, job_execution_id, step_name, create_time_min:nil, create_time_max:nil, end_time_min:nil, end_time_max:nil, is_active:nil, skip:nil, top:nil, custom_headers:nil)
      response = list_by_step_async(resource_group_name, server_name, job_agent_name, job_name, job_execution_id, step_name, create_time_min:create_time_min, create_time_max:create_time_max, end_time_min:end_time_min, end_time_max:end_time_max, is_active:is_active, skip:skip, top:top, custom_headers:custom_headers).value!
      unless response.nil?
        page = response.body
        page.next_method = Proc.new do |next_page_link|
          list_by_step_next_async(next_page_link, custom_headers:custom_headers)
        end
        page
      end
    end

  end
end


text:
**_A faster way to open a ssh connection to an OpsWorks instance_**

[![Build Status](https://travis-ci.org/w4andy/node-yaowst.svg)](https://travis-ci.org/w4andy/node-yaowst)

## Table of Contents

  - [Usage](#usage)
  - [Examples](#examples)
  - [Config](#config)
  - [API](#api)
  - [Tests](#tests)
  - [ChangeLog](./CHANGELOG.markdown)
  - [License](./LICENSE)
  - [Uninstall](#uninstall)

## Installation

```
$ npm install yaowst -g
$ yaowst
YaOWsT run the first time
Creating the config file and backup the existing OpenSSH config file
YaOWsT init complete, now you can edit the config file "~/.yaowst"
```

## Usage

```
$ yaowst --help

Yet another OpsWorks ssh Tool

Usage: yaowst [options]

  options
   -c, --config-file      The location of the YaOWsT config file
   -o, --ssh-config-file  The location of the OpenSSH config file
   -s, --save-mode        24/7 or all, 24/7 store no instances that started by auto scaling

```

## Examples

### Shell Commands

```
$ yaowst
Get running OpsWorks instances and store the hosts to the OpenSSH config file
The OpenSSH config file successful updated
4 Entries updated (instances and base config)

$ ssh opsworks_one_1
$ scp example.txt opsworks_one_1:/tmp/
```

### Config

```json
{
  "sshOptions": {
    "StrictHostKeyChecking": "no",
    "UserKnownHostsFile": "~/.ssh/opsworks_known_hosts",
    "IdentitiesOnly": "yes",
    "User": "yaowst"
  },
  "opsWorks": {
    "accessKeyId": "MAIN_KEY",
    "secretAccessKey": "MAIN_SECRET",
    "region": "OPSWORKS_REGION"
  },
  "stacks": [
    {
      "id": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
      "sshOptions": {
        "IdentityFile": "~/.ssh/opsworks_yaowst.pem"
      }
    },
    {
      "sshOptions": {
        "IdentityFile": "~/.ssh/opsworks_yaowst_1.pem"
      },
      "layers": [
        {
          "id": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
          "alias": "opsworks_one-"
        },
        {
          "id": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
          "alias": "opsworks_two-"
        }
      ]
    },
    {
      "accessKeyId": "ANOTHER_KEY",
      "secretAccessKey": "ANOTHER_SECRET",
      "sshOptions": {
        "IdentityFile": "~/.ssh/opsworks_yaowst_2.pem"
      },
      "layers": [
        {
          "id": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
          "alias": "opsworks_three-"
        }
      ]
    }
  ]
}
```

## Config

After the first run, YaOWsT create a config file with basic settings.

The location is `~/.yaowst` and has the permission `0600`.

### Base Config

```json
{
  "opsWorks": {
    "region": "us-east-1"
  },
  "sshOptions": {
    "StrictHostKeyChecking": "no",
    "UserKnownHostsFile": "/dev/null",
    "IdentitiesOnly": "yes"
  },
  "stacks": []
}
```

### Config with all possible settings

```json
{
  "opsWorks": {
    "accessKeyId": "<Access Key ID>",
    "secretAccessKey": "<Secret Access Key>",
    "region": "<OpsWorks Region>"
  },
  "sshConfigFile": {
    "file": null,
    "saveMode": "24/7"
  },
  "sshOptions": {
    "StrictHostKeyChecking": "no",
    "UserKnownHostsFile": "/dev/null",
    "IdentitiesOnly": "yes"
  },
  "stacks": [
    {
      "id": "<OpsWorks Stack ID>",
      "accessKeyId": "<Access Key ID>",
      "secretAccessKey": "<Secret Access Key>",
      "region": "<OpsWorks Region>",
      "prefix": "aws-",
      "sshOptions": {},
      "layers": [
        {
          "id": "<OpsWorks Layer ID>",
          "alias": "layer-1-",
          "prefix": "aws-layer-1-",
          "sshOptions": {}
        }
      ]
    }
  ]
}
```

### Config description
  - `{object} opsWorks` the default IAM credentials for all stacks
    - `{string} accessKeyId` the access key id
    - `{string} secretAccessKey` the secret access key
    - `{string} region` the default OpsWork region
  - `{object} sshConfigFile` OpenSSH config file settings
    - `{string|null} file` if `null` then YaOWsT use `~/.ssh/config` as OpenSSH config file else YaOWsT use this path
    - `{string} saveMode` `24/7` or `all`, `24/7` store only instances that run 24/7 (no time- or load-based instances)
  - `{object} sshOptions` see the [OpenSSH client config manual](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man5/ssh_config.5?query=ssh_config&sec=5)
  - `{object[]} stacks` this array has all stacks
    - `{string} id` the OpsWorks Stack ID, if you use the **layers** option then you can skip this option
    - `{string} [accessKeyId]` overwrite the default access key id
    - `{string} [secretAccessKey]` overwrite the default secret access key
    - `{string} [region]` overwrite the default OpsWorks region
    - `{string} [prefix]` add this prefix to all instances in this stack, only if the layer as no alias
    - `{object} [sshOptions]` overwrite existing options and merge the another options
    - `{object} [layers]` if this option not exists then YaOWsT check all instances in this stack
      - `{string} id` the OpsWorks layer ID
      - `{string} [alias]` if the instance name has numbers then YaOWsT replace eventing before the number, if the instance name has no number then the alias value will added as prefix to the instance name
      - `{string} [prefix]` add this prefix to all instances in this stack, only if the layer as no alias
      - `{object} [sshOptions]` overwrite existing options and merge the another options

## API

### Class: Yaowst

#### new Yaowst(options, callback)

**options**

  - `{string} configFile` The location of the YaOWsT config file
  - `{object} sshConfigFile`
    - `{string} file` The location of the OpenSSH config file
    - `{string} saveMode` `24/7` or `all`, `24/7` store only instances that run 24/7

#### yaowst.firstInit(option, callback)

Create the YaOWsT config file and backup the existing OpenSSH config file

**option**

  - `{boolean} force` overwrite the YaOWsT config file

#### yaowst.save(option, callback)

Store the instances in the OpenSSH config file

**option**

  - `{string} saveMode` `24/7` or `all`, `24/7` store no instances that started by auto scaling

## Tests

The tests are with and without AWS API request, per default the tests are without API requests.

### Test with API Requests

For the Tests with API Requests you must create as new OpsWorks Stack and copy some files.

#### The OpsWorks Stack

The Stack structure

  - The Stack need 2 Layers
  - in the first Layer one instance is online
  - in the second Layer two instances are online

#### The Files

Copy Files and add your IAM credentials and Ids, the files are in `resources/test/`

  - `configOpsWorksLayer.json.default` -> `configOpsWorksLayer.json`
  - `configOpsWorksStack.json.default` -> `configOpsWorksStack.json`
  - `configYaowst.json.default` -> `configYaowst.json`

### Single test

```
npm test
```

### Cross node version testing

Run tests for all relevant versions of io.js/node.js

#### Install nvm and all relevant versions

```
$ git clone https://github.com/creationix/nvm.git ~/.nvm && cd ~/.nvm && git checkout `git describe --abbrev=0 --tags`
$ echo "source ~/.nvm/nvm.sh" >> ~/.bashrc
$ nvm install 0.10
$ nvm install 0.12
$ nvm install 4
$ nvm install 6
```

#### Run the test

```
./resources/tools/cross-test.sh
```

### Cross OS and cross node version testing

For the cross os tests you can use [vagrant-yaowst](https://github.com/w4andy/vagrant-yaowst)

# Uninstall
If you uninstall yaowst then you must also delete the **yaowst** section form the ssh config file, everything between `## yaowst begin ##` and `## yaowst end ##`


text:
using System;
using Microsoft.Azure.Mobile;
using Microsoft.Azure.Mobile.Analytics;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Popups;
using Windows.Storage;
using Windows.ApplicationModel.ExtendedExecution;
using System.Threading.Tasks;
using System.Threading;

namespace Fcus_Restart
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    sealed partial class App : Application
    {
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;
        }

        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs e)
        {
            MobileCenter.Start("3ceb4858-3b7c-45f4-8883-0d99578c9ad8", typeof(Analytics));
            OnActivated(e);
        }

        /// <summary>
        /// Invoked when Navigation to a certain page fails
        /// </summary>
        /// <param name="sender">The Frame which failed navigation</param>
        /// <param name="e">Details about the navigation failure</param>
        void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
        }

        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private void OnSuspending(object sender, SuspendingEventArgs e)
        {

            var deferral = e.SuspendingOperation.GetDeferral();
            //TODO: Save application state and stop any background activit

            deferral.Complete();
        }

        protected async override void OnActivated(IActivatedEventArgs args)
        {
#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = true;
            }
#endif

            var prelaunchActivated = false;

            var launcharg = args as LaunchActivatedEventArgs;
            if (launcharg != null)
            {
                prelaunchActivated = launcharg.PrelaunchActivated;
            }

            var vspro = args as IViewSwitcherProvider;
            if (vspro.ViewSwitcher == null)
            {
                Windows.UI.ViewManagement.ApplicationViewSwitcher.DisableSystemViewActivationPolicy();

                // Initialize rootFrame normally.
                CreateRootFrame(args, prelaunchActivated);

            }
            else
            {
                // Create new view, use launcharg.ViewSwitcher.ShowAsStandaloneAsync(int) to display.
                var view = Windows.ApplicationModel.Core.CoreApplication.CreateNewView();
                await view.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
                {
                    CreateRootFrame(args, prelaunchActivated);
                    var id = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().Id;
                    await vspro.ViewSwitcher.ShowAsStandaloneAsync(id);
                });

                return;
            }

        }
        private void CreateRootFrame(IActivatedEventArgs args, bool prelaunchActivated)
        {
            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            var currentView = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView();
            currentView.Consolidated += CurrentView_Consolidated;
            if (!prelaunchActivated)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                var filearg = args as FileActivatedEventArgs;

                if (filearg == null && rootFrame.Content == null)
                    rootFrame.Navigate(typeof(MainPage));
                else
                    rootFrame.Navigate(typeof(MainPage), filearg.Files[0] as Windows.Storage.IStorageFile);
                // Ensure the current window is active
                Window.Current.Activate();
            }
        }

        private void CurrentView_Consolidated(Windows.UI.ViewManagement.ApplicationView sender, Windows.UI.ViewManagement.ApplicationViewConsolidatedEventArgs args)
        {

            Window.Current.Content = null;
        }

        protected override void OnFileActivated(FileActivatedEventArgs args)
        {
            OnActivated(args);
        }
    }
}


text:
DELETE FROM meta WHERE meta_key='schema_version';
INSERT INTO meta (species_id, meta_key, meta_value) VALUES (NULL, 'schema_version', '71');

# Patch identifier
INSERT INTO meta (species_id, meta_key, meta_value)
  VALUES (NULL, 'patch', 'patch_70_71_c.sql|schema_version');


text:
本文将对Mybatis中sql映射Mapper文件的读取解析进行详细分析。此文将先从一个mybatis的编程示例入手,逐步分析。

### 一、Mybatis编程示例

下面是使用Mybatis操作数据库的一个编程示例,演示了数据库中一个最基本的查询操作流程。

``````java
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
try {
  Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
} finally {
  session.close();
}
``````

mybatis-config.xml配置文件的内容如下:

``````xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>
``````

BlogMapper.xml映射文件内容如下:

``````xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.mybatis.example.BlogMapper">
  <select id="selectBlog" resultType="Blog">
    select * from Blog where id = #{id}
  </select>
</mapper>
``````

### 二、过程分析

从第一部分的代码我们可以知道,Mybatis的编程流程大致如下:

1. 创建Mybatis配置文件的输入流对象inputstream;
2. 通过工厂构建类SqlSessionFactoryBuilder,利用inputstream来构建一个SqlSessionFactory实例sqlSessionFactory;
3. 利用工厂实例sqlSessionFactory生产SqlSession实例sqlSession;
4. 通过sqlSession执行具体的数据库操作,至于具体的数据库操作是什么,则是通过Mapper映射文件中的设定来操作的。

那么在这个过程中,是在什么时候读取的Mapper映射文件的呢?跟踪源码发现在SqlSessionFactoryBuilder.build方法执行时,会解析mybatis-config.xml这个mybatis的配置文件,在解析此配置文件过程中,根据其mappers元素的配置,进一步会逐一解析Mapper映射文件,SqlSessionFactoryBuilder.build方法的源码如下(SqlSessionFactoryBuilder提供了多个重载的build方法,针对任何build方法的条用,最终都是调用的下面这个方法):

``````java
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
    try {
        XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
        return build(parser.parse());
    } catch (Exception e) {
        throw ExceptionFactory.wrapException("Error building SqlSession.", e);
    } finally {
        ErrorContext.instance().reset();
        try {
            inputStream.close();
        } catch (IOException e) {
            // Intentionally ignore. Prefer previous error.
        }
    }
}
``````

从代码中,可以看到build方法里面调用了XmlConfigBuilder这个类(这个类的职责就是解析mybatis-config.xml这个配置文件),并调用了XmlConfigBuilder.parse()这个方法,下面我们看看这个方法里面做了什么:

``````java
public Configuration parse() {
    if (parsed) {
        throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    }
    parsed = true;
    parseConfiguration(parser.evalNode("/configuration"));
    return configuration;
}
``````

从代码中我们知道,parse()方法又调用了parseConfiguration()这个方法(parser变量是一个XPathParser的实例,负责读取解析xml文件的内容,parser.evalNode("/configuration")这句代码的意思就是找到mybatis-config.xml配置文件中的configuration这个外部顶级元素):

``````java
private void parseConfiguration(XNode root) {
    try {
        //issue #117 read properties first
        propertiesElement(root.evalNode("properties"));
        Properties settings = settingsAsProperties(root.evalNode("settings"));
        loadCustomVfs(settings);
        typeAliasesElement(root.evalNode("typeAliases"));
        pluginElement(root.evalNode("plugins"));
        objectFactoryElement(root.evalNode("objectFactory"));
        objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
        reflectorFactoryElement(root.evalNode("reflectorFactory"));
        settingsElement(settings);
        // read it after objectFactory and objectWrapperFactory issue #631
        environmentsElement(root.evalNode("environments"));
        databaseIdProviderElement(root.evalNode("databaseIdProvider"));
        typeHandlerElement(root.evalNode("typeHandlers"));
        mapperElement(root.evalNode("mappers"));
    } catch (Exception e) {
        throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
    }
}
``````

从上述代码可以知道parseConfiguration这个方法的职责就是一步步解析处理配置文件中配置的properties、settings、typeAliases、plugins、...、以及mappers这些xml文件元素;因为我们的Mapper映射文件就是配置在mappers这个元素里面的,要知道mybatis是怎么处理映射文件,继续查看mapperElement()这个方法的实现即可:

``````java
private void mapperElement(XNode parent) throws Exception {
    if (parent != null) {
        for (XNode child : parent.getChildren()) {
            if ("package".equals(child.getName())) {
                String mapperPackage = child.getStringAttribute("name");
                configuration.addMappers(mapperPackage);
            } else {
                String resource = child.getStringAttribute("resource");
                String url = child.getStringAttribute("url");
                String mapperClass = child.getStringAttribute("class");
                if (resource != null && url == null && mapperClass == null) {
                    ErrorContext.instance().resource(resource);
                    InputStream inputStream = Resources.getResourceAsStream(resource);
                    XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
                    mapperParser.parse();
                } else if (resource == null && url != null && mapperClass == null) {
                    ErrorContext.instance().resource(url);
                    InputStream inputStream = Resources.getUrlAsStream(url);
                    XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
                    mapperParser.parse();
                } else if (resource == null && url == null && mapperClass != null) {
                    Class<?> mapperInterface = Resources.classForName(mapperClass);
                    configuration.addMapper(mapperInterface);
                } else {
                    throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
                }
            }
        }
    }
}
``````

从方法代码可以知道,首先,mapperElement方法会对mappers这个元素节点的所有子节点进行循环,也就是循环处理mappers元素节点里面的每个mapper元素节点,mapperElement针对Mapper映射配置的四种方式都有对应的处理方式,此文以比较常用的那种方法(也就是\<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>这种指定resource值的方法)进行分析;查看XMLMapperBuilder类中parse()方法的实现如下:

``````java
public void parse() {
    if (!configuration.isResourceLoaded(resource)) {
        configurationElement(parser.evalNode("/mapper"));
        configuration.addLoadedResource(resource);
        bindMapperForNamespace();
    }

    parsePendingResultMaps();
    parsePendingCacheRefs();
    parsePendingStatements();
}

private void configurationElement(XNode context) {
    try {
        String namespace = context.getStringAttribute("namespace");
        if (namespace == null || namespace.equals("")) {
            throw new BuilderException("Mapper's namespace cannot be empty");
        }
        builderAssistant.setCurrentNamespace(namespace);
        cacheRefElement(context.evalNode("cache-ref"));
        cacheElement(context.evalNode("cache"));
        parameterMapElement(context.evalNodes("/mapper/parameterMap"));
        resultMapElements(context.evalNodes("/mapper/resultMap"));
        sqlElement(context.evalNodes("/mapper/sql"));
        buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
    } catch (Exception e) {
        throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e);
    }
}
``````

从代码实现我们可以看出,解析Mapper文件主要是通过configurationElement(XNode context)这个方法来实现,从实现我们就可以知道针对Mapper文件中的不同元素节点分步对应处理即可,我们着重理解针对select、insert、update和delete语句的处理:

``````java
private void buildStatementFromContext(List<XNode> list) {
    if (configuration.getDatabaseId() != null) {
        buildStatementFromContext(list, configuration.getDatabaseId());
    }
    buildStatementFromContext(list, null);
}

private void buildStatementFromContext(List<XNode> list, String requiredDatabaseId) {
    for (XNode context : list) {
        final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId);
        try {
            statementParser.parseStatementNode();
        } catch (IncompleteElementException e) {
            configuration.addIncompleteStatement(statementParser);
        }
    }
}
``````

XMLStatementBuilder中parseStatementNode()方法的作用就是解析配置的语句:

``````java
public void parseStatementNode() {
    String id = context.getStringAttribute("id");
    String databaseId = context.getStringAttribute("databaseId");

    if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) {
        return;
    }

    Integer fetchSize = context.getIntAttribute("fetchSize");
    Integer timeout = context.getIntAttribute("timeout");
    String parameterMap = context.getStringAttribute("parameterMap");
    String parameterType = context.getStringAttribute("parameterType");
    Class<?> parameterTypeClass = resolveClass(parameterType);
    String resultMap = context.getStringAttribute("resultMap");
    String resultType = context.getStringAttribute("resultType");
    String lang = context.getStringAttribute("lang");
    LanguageDriver langDriver = getLanguageDriver(lang);

    Class<?> resultTypeClass = resolveClass(resultType);
    String resultSetType = context.getStringAttribute("resultSetType");
    StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString()));
    ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType);

    String nodeName = context.getNode().getNodeName();
    SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));
    boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
    boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect);
    boolean useCache = context.getBooleanAttribute("useCache", isSelect);
    boolean resultOrdered = context.getBooleanAttribute("resultOrdered", false);

    // Include Fragments before parsing
    XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant);
    includeParser.applyIncludes(context.getNode());

    // Parse selectKey after includes and remove them.
    processSelectKeyNodes(id, parameterTypeClass, langDriver);

    // Parse the SQL (pre: <selectKey> and <include> were parsed and removed)
    SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
    String resultSets = context.getStringAttribute("resultSets");
    String keyProperty = context.getStringAttribute("keyProperty");
    String keyColumn = context.getStringAttribute("keyColumn");
    KeyGenerator keyGenerator;
    String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX;
    keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true);
    if (configuration.hasKeyGenerator(keyStatementId)) {
        keyGenerator = configuration.getKeyGenerator(keyStatementId);
    } else {
        keyGenerator = context.getBooleanAttribute("useGeneratedKeys",
                                                   configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType))
            ? Jdbc3KeyGenerator.INSTANCE : NoKeyGenerator.INSTANCE;
    }

    builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
                                        fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
                                        resultSetTypeEnum, flushCache, useCache, resultOrdered,
                                        keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
}
``````

其中这个方法langDriver.createSqlSource(configuration, context, parameterTypeClass);非常重要,此语句的作用就是将具体的sql配置语句解析成不同的java实例,我们可以查看到XMLLanguageDriver对这个方法的实现为:

``````java
@Override
public SqlSource createSqlSource(Configuration configuration, XNode script, Class<?> parameterType) {
    XMLScriptBuilder builder = new XMLScriptBuilder(configuration, script, parameterType);
    return builder.parseScriptNode();
}
``````

而XmlScriptBuilder中parseScriptNode()方法实现如下:

``````java
public SqlSource parseScriptNode() {
    MixedSqlNode rootSqlNode = parseDynamicTags(context);
    SqlSource sqlSource = null;
    if (isDynamic) {
      sqlSource = new DynamicSqlSource(configuration, rootSqlNode);
    } else {
      sqlSource = new RawSqlSource(configuration, rootSqlNode, parameterType);
    }
    return sqlSource;
  }
``````

从实现我们可以看出,针对动态sql语句生成的是DynamicSqlSource实例,而其他sql语句则是RawSqlSource实例。其中动态sql语句为:在select、insert、update和delete元素中包含有\<if>,\<where>,\<set>等动态标签以及包含有${}参数的配置语句。


text:
package vagrant

import (
	"io/ioutil"
	"path/filepath"
)

// GlobalStatus returns strings like `vagrant global-status` command output.
func GlobalStatus() ([]string, error) {
	index, err := readMachineIndex()
	if err != nil {
		return []string{}, err
	}
	machineIndex := NewMachineIndex(index)
	return machineIndex.GlobalStatuses(), nil
}

func readMachineIndex() ([]byte, error) {
	index := filepath.Join(
		homeDir(),
		".vagrant.d",
		"data",
		"machine-index",
		"index",
	)
	return ioutil.ReadFile(index)
}


text:
'use strict';

module.exports = function ($scope, application) {
    $scope.application = application;
    application.getActiviti()
        .then(function (activiti){
            $scope.summary = [];
            $scope.summary.push({
                key: 'Completed Task Count Today',
                value: activiti.completedTaskCountToday
            });
            $scope.summary.push({
                key: 'Process Definition Count',
                value: activiti.processDefinitionCount
            });
            $scope.summary.push({
                key: 'Cached Process Definition Count',
                value: activiti.cachedProcessDefinitionCount
            });
            $scope.summary.push({
                key: 'Completed Task Count',
                value: activiti.completedTaskCount
            });
            $scope.summary.push({
                key: 'Completed Activities',
                value: activiti.completedActivities
            });
            $scope.summary.push({
                key: 'Open Task Count',
                value: activiti.openTaskCount
            });
            $scope.processes = [];
            for (var i = 0; i < activiti.deployedProcessDefinitions.length; i++) {
                var process = activiti.deployedProcessDefinitions[i];
                var runningProcessInstanceCount = activiti.runningProcessInstanceCount[process];
                var completedProcessInstanceCount = activiti.completedProcessInstanceCount[process];
                $scope.processes.push({
                    name: process,
                    running: runningProcessInstanceCount,
                    completed: completedProcessInstanceCount
                });
            }
        })
        .catch(function (error) {
            $scope.error = error;
        });
};


text:
<?php

namespace PEIP\Handler;

/**
 * CallableHandler
 * Class to wrap a PHP callable in a handler.
 *
 * @author Timo Michna <timomichna/yahoo.de>
 * @implements \PEIP\INF\Handler\Handler
 */
class CallableHandler implements \PEIP\INF\Handler\Handler
{
    protected $callable;

    /**
     * constructor.
     *
     * @param callable $callable the callable to wrap with the handler
     *
     * @return
     */
    public function __construct($callable)
    {
        $this->callable = $callable;
    }

    /**
     * Handles a subject by calling the wrapped callable with the subject as argument.
     *
     * @implements \PEIP\INF\Handler\Handler
     *
     * @param mixed $subject the subject to handle
     *
     * @return mixed result of calling the registered callable with given subject
     */
    public function handle($subject)
    {
        return call_user_func($this->callable, $subject);
    }

    /**
     * Allows the handler instance to act as a lambda function.
     * Delegates to own 'handle' method.
     *
     * @param mixed $subject the subject to handle
     *
     * @return mixed result of calling the registered callable with given subject
     *
     * @see CallableHandler::handle
     */
    public function __invoke($subject)
    {
        return $this->handle($subject);
    }

    /**
     * Returns the callable wrapped by the handler instance.
     *
     * @return callable callable wrapped by the handler
     */
    public function getCallable()
    {
        return $this->callable;
    }
}