text:
from PyObjCTools.TestSupport import *
import objc
from PyObjCTest.test_object_property import OCObserve
import sys
import pickle

NSObject = objc.lookUpClass('NSObject')

class TestSetPropertyHelper (NSObject):
    aSet = objc.set_property()
    aSet2 = objc.set_property()
    aROSet = objc.set_property(read_only=True)

class TestSetProperty (TestCase):
    def testCopying(self):
        o = TestSetPropertyHelper.alloc().init()
        aSet = set([1,2])
        o.aSet = aSet

        self.assertEqual(len(o.aSet), 2)
        self.assertEqual(len(aSet), 2)
        aSet.add(3)
        self.assertEqual(len(o.aSet), 2)
        self.assertEqual(len(aSet), 3)

    def testRepr(self):
        o = TestSetPropertyHelper.alloc().init()
        aSet = set([1,2])
        o.aSet = aSet

        self.assertEqual(repr(o.aSet), '<set proxy for property aSet %r>'%(aSet,))

    def testDefault(self):
        with OCObserve.alloc().init() as observer:
            o = TestSetPropertyHelper.alloc().init()

            observer.register(o, 'aSet')

            o.aSet = set()
            self.assertEqual(observer.seen, {'aSet': set()})

            self.assertEqual(len(o.aSet), 0)
            o.aSet.add('a')
            o.aSet.add('b')
            self.assertEqual(len(o.aSet), 2)
            self.assertEqual(observer.seen, {'aSet': {'b'}})

            self.assertEqual(observer.values[-2][-1]['kind'], 2)
            self.assertNotIn('old', observer.values[-2][-1])
            self.assertEqual(observer.values[-2][-1]['new'], set('a'))

            self.assertEqual(observer.values[-1][-1]['kind'], 2)
            self.assertNotIn('old', observer.values[-1][-1])
            self.assertEqual(observer.values[-1][-1]['new'], set('b'))

            v = list(o.aSet)
            v.sort()
            self.assertEqual(v, ['a', 'b'])

            self.assertEqual(o.aSet, set(['a', 'b']))

            proxy = o.aSet

            o.aSet.clear()
            self.assertEqual(len(o.aSet), 0)
            self.assertEqual(len(proxy), 0)

            self.assertEqual(observer.values[-1][-1]['old'], set(['a', 'b']))
            self.assertNotIn('new', observer.values[-1][-1])

    def testForwarding(self):
        o = TestSetPropertyHelper.alloc().init()
        o.aSet = set()

        self.assertTrue(o.aSet.issubset({1,2}))

    def testSetting(self):
        o = TestSetPropertyHelper.alloc().init()
        s = {1,2}
        o.aSet = s
        self.assertEqual(o.aSet, s)
        s.add(3)
        self.assertNotEqual(o.aSet, s)
        o.aSet2 = o.aSet
        o.aSet.add(4)
        self.assertNotEqual(o.aSet, o.aSet2)

        v = o.aSet
        o._aSet = None
        self.assertEqual(v, set())

    def testDifferenceUpdate(self):
        with OCObserve.alloc().init() as observer:
            o = TestSetPropertyHelper.alloc().init()

            o.aSet.add(1)
            o.aSet.add(2)
            o.aSet.add(3)

            observer.register(o, 'aSet')

            o.aSet.difference_update(set([1,4]))
            self.assertEqual(o.aSet, set([2,3]))

            self.assertEqual(len(observer.values), 1)
            self.assertEqual(observer.values[-1][-1]['kind'], 3)
            self.assertNotIn('new', observer.values[-1][-1])
            self.assertEqual(observer.values[-1][-1]['old'], set([1]))

    def testSymmetricDifferenceUpdate(self):
        with OCObserve.alloc().init() as observer:
            o = TestSetPropertyHelper.alloc().init()

            o.aSet = set([1,2,3])

            observer.register(o, 'aSet')

            self.assertEqual(len(observer.values), 0)
            o.aSet.symmetric_difference_update(set([1,4]))
            self.assertEqual(o.aSet, set([2, 3, 4]))

            self.assertEqual(len(observer.values), 2)

            haveAdd = False
            haveRemove = False

            for i in 0, 1:
                if observer.values[i][-1]['kind'] == 3:
                    # Remove
                    self.assertNotIn('new', observer.values[i][-1])
                    self.assertEqual(observer.values[i][-1]['old'], set([1]))
                    haveRemove = True

                elif observer.values[i][-1]['kind'] == 2:
                    # Remove
                    self.assertNotIn('old', observer.values[i][-1])
                    self.assertEqual(observer.values[i][-1]['new'], set([4]))
                    haveAdd = True

                else:
                    self.fail("Unexpected update kind")

            if not haveAdd and haveRemove:
                self.fail("Do not have both an add and remove notification")

    def testUpdate(self):
        with OCObserve.alloc().init() as observer:
            o = TestSetPropertyHelper.alloc().init()
            observer.register(o, 'aSet')
            self.assertEqual(o.aSet, set())
            self.assertEqual(len(observer.values), 1)

            o.aSet.update([1,2,3])
            self.assertEqual(len(observer.values), 2)
            self.assertEqual(observer.values[-1][-1]['kind'], 2)
            self.assertNotIn('old', observer.values[-1][-1])
            self.assertEqual(observer.values[-1][-1]['new'], set([1, 2, 3]))

            o.aSet.update(set([3,4,5]))
            self.assertEqual(len(observer.values), 3)
            self.assertEqual(observer.values[-1][-1]['kind'], 2)
            self.assertNotIn('old', observer.values[-1][-1])
            self.assertEqual(observer.values[-1][-1]['new'], set([4, 5]))

    def testAddDiscard(self):
        with OCObserve.alloc().init() as observer:
            o = TestSetPropertyHelper.alloc().init()
            observer.register(o, 'aSet')

            o.aSet.add(1)
            self.assertEqual(observer.seen, {'aSet': {1}})
            self.assertNotIn('old', observer.values[-1][-1])
            self.assertEqual(observer.values[-1][-1]['new'], set([1]))

            o.aSet.discard(1)
            self.assertNotIn('new', observer.values[-1][-1])
            self.assertEqual(observer.values[-1][-1]['old'], set([1]))

            o.aSet.discard(2)
            self.assertNotIn('new', observer.values[-1][-1])
            self.assertEqual(observer.values[-1][-1]['old'], set([]))

    def testAddRemove(self):
        with OCObserve.alloc().init() as observer:
            o = TestSetPropertyHelper.alloc().init()
            observer.register(o, 'aSet')

            o.aSet.add(1)
            self.assertEqual(observer.seen, {'aSet': {1}})
            self.assertNotIn('old', observer.values[-1][-1])
            self.assertEqual(observer.values[-1][-1]['new'], set([1]))

            o.aSet.remove(1)
            self.assertNotIn('new', observer.values[-1][-1])
            self.assertEqual(observer.values[-1][-1]['old'], set([1]))

            self.assertRaises(KeyError, o.aSet.remove, 2)
            self.assertNotIn('new', observer.values[-1][-1])
            self.assertEqual(observer.values[-1][-1]['old'], set([]))

            o.aSet.add(1)
            o.aSet.add(2)
            v = o.aSet.pop()
            self.assertTrue(v in (1, 2))
            self.assertNotIn('new', observer.values[-1][-1])
            self.assertEqual(observer.values[-1][-1]['old'], set([v]))

            o.aSet = set()
            self.assertRaises(KeyError, o.aSet.pop)

    def testOperators(self):
        with OCObserve.alloc().init() as observer:
            o = TestSetPropertyHelper.alloc().init()
            o.aSet = {1,2,3}

            observer.register(o, 'aSet')
            self.assertEquals(observer.seen, {})

            self.assertEquals(o.aSet - {2}, {1,3})
            self.assertEquals(o.aSet, {1,2,3})

            self.assertEquals(o.aSet | {4}, {1,2,3,4})
            self.assertEquals(o.aSet, {1,2,3})

            self.assertEquals(o.aSet & {3,4}, {3})
            self.assertEquals(o.aSet, {1,2,3})

            self.assertEquals(o.aSet ^ {3,4}, {1,2,4})
            self.assertEquals(o.aSet, {1,2,3})

    def testInplace(self):
        # FIXME: the disabled lines in this test indicate a problem in
        # either the set_proxy implementation, or my understanding of
        # unordered collection properties.
        with OCObserve.alloc().init() as observer:
            o = TestSetPropertyHelper.alloc().init()
            o.aSet.add(1)
            observer.register(o, 'aSet')

            # The inplace operators aren't actually implemented, which means
            # "o.aSet |= value" is actually  "o.aSet = o.aSet | value" and
            # we get the some KVO notificatons as when a new value is set.

            self.assertEqual(o.aSet, {1})
            o.aSet |= set([2,3])
            self.assertEqual(o.aSet, {1,2,3})
            self.assertEqual(o.aSet, set([1,2,3]))
            self.assertEqual(len(observer.values), 2)
            self.assertEqual(observer.values[-1][-1]['kind'], 1)
            #self.assertEqual(observer.values[-1][-1]['old'], set([1]))
            self.assertEqual(observer.values[-1][-1]['new'], set([1,2,3]))

            self.assertEqual(o.aSet, {1,2,3})
            o.aSet &= set([3, 4])
            self.assertEqual(o.aSet, {3})
            self.assertEqual(o.aSet, set([3]))
            self.assertEqual(len(observer.values), 4)
            self.assertEqual(observer.values[-1][-1]['kind'], 1)
            #self.assertEqual(observer.values[-1][-1]['old'], set([1,2,3]))
            #self.assertEqual(observer.values[-1][-1]['new'], set([3]))

            self.assertEqual(o.aSet, {3})
            o.aSet -= {3}
            self.assertEqual(o.aSet, set())
            self.assertEqual(o.aSet, set([]))
            self.assertEqual(len(observer.values), 6)
            self.assertEqual(observer.values[-1][-1]['kind'], 1)
            #self.assertEqual(observer.values[-1][-1]['old'], set([3]))
            #self.assertEqual(observer.values[-1][-1]['new'], set())

            o.aSet = set([1,2,3])
            #self.assertEqual(len(observer.values), 8)

            self.assertEqual(o.aSet, {1,2,3})
            o.aSet ^= set([1, 4])
            self.assertEqual(o.aSet, {2, 3, 4})
            #self.assertEqual(len(observer.values), 9)
            self.assertEqual(observer.values[-1][-1]['kind'], 1)
            #self.assertEqual(observer.values[-1][-1]['old'], set([1,2,3]))
            #self.assertEqual(observer.values[-1][-1]['new'], set([2,3,4]))

    def testObjCAccessors(self):
        # Check that the right ObjC array accessors are defined and work properly
        self.assertTrue(TestSetPropertyHelper.instancesRespondToSelector_(b"setASet:"))
        self.assertTrue(TestSetPropertyHelper.instancesRespondToSelector_(b"aSet"))
        self.assertTrue(TestSetPropertyHelper.instancesRespondToSelector_(b"countOfASet"))
        self.assertTrue(TestSetPropertyHelper.instancesRespondToSelector_(b"enumeratorOfASet"))
        self.assertTrue(TestSetPropertyHelper.instancesRespondToSelector_(b"memberOfASet:"))
        self.assertTrue(TestSetPropertyHelper.instancesRespondToSelector_(b"addASet:"))
        self.assertTrue(TestSetPropertyHelper.instancesRespondToSelector_(b"addASetObject:"))
        self.assertTrue(TestSetPropertyHelper.instancesRespondToSelector_(b"removeASet:"))
        self.assertTrue(TestSetPropertyHelper.instancesRespondToSelector_(b"removeASetObject:"))

        o = TestSetPropertyHelper.alloc().init()
        self.assertEqual(0, o.pyobjc_instanceMethods.countOfASet())
        self.assertRaises(AttributeError, getattr, o, 'countOfASet')
        o.aSet.add(1)
        o.aSet.add(2)

        v = list(sorted(o.pyobjc_instanceMethods.enumeratorOfASet()))
        self.assertEqual(v, [1,2])

        class Testing (object):
            def __hash__(self):
                return 42

            def __eq__(self, other):
                return isinstance(other, Testing)

        p = Testing()
        o.aSet.add(p)

        v = o.pyobjc_instanceMethods.memberOfASet_(Testing())
        self.assertIs(p, v)
        v = o.pyobjc_instanceMethods.memberOfASet_(9)
        self.assertIs(v, None)

        self.assertNotIn(9, o.aSet)
        o.pyobjc_instanceMethods.addASet_(9)
        self.assertIn(9, o.aSet)

        self.assertNotIn(10, o.aSet)
        o.pyobjc_instanceMethods.addASetObject_(10)
        self.assertIn(10, o.aSet)

        self.assertIn(9, o.aSet)
        o.pyobjc_instanceMethods.removeASet_(9)
        self.assertNotIn(9, o.aSet)

        self.assertIn(10, o.aSet)
        o.pyobjc_instanceMethods.removeASetObject_(10)
        self.assertNotIn(10, o.aSet)

    def test_ro_set(self):
        o = TestSetPropertyHelper.alloc().init()
        o._aROSet = { 1, 2, 3, 4 }

        self.assertEqual(o.aROSet, { 1, 2, 3, 4 })
        self.assertIsNot(type(o.aROSet), set)

        self.assertRaises(ValueError, o.aROSet.add, 1)
        self.assertRaises(ValueError, o.aROSet.clear)
        self.assertRaises(ValueError, o.aROSet.pop)
        self.assertRaises(ValueError, o.aROSet.remove, 1)
        self.assertRaises(ValueError, o.aROSet.difference_update, { 1, 2})
        self.assertRaises(ValueError, o.aROSet.intersection_update, { 1, 2})
        self.assertRaises(ValueError, o.aROSet.symmetric_difference_update, { 1, 2})
        self.assertRaises(ValueError, o.aROSet.update, { 1, 2})
        self.assertRaises(ValueError, o.aROSet.discard, 4)

        try:
            o.aROSet |= {1,2}
        except ValueError:
            pass
        else:
            self.fail()

        try:
            o.aROSet -= {1,2}
        except ValueError:
            pass
        else:
            self.fail()

        try:
            o.aROSet ^= {1,2}
        except ValueError:
            pass
        else:
            self.fail()

        try:
            o.aROSet &= {1,2}
        except ValueError:
            pass
        else:
            self.fail()

    def test_compare(self):
        o = TestSetPropertyHelper.alloc().init()
        o.aSet =  {1, 2, 3}
        o.aSet2 = {1, 2, 3}

        self.assertTrue(o.aSet ==  o.aSet2)
        self.assertTrue(o.aSet ==  {1, 2, 3})
        self.assertTrue(o.aSet <=  o.aSet2)
        self.assertTrue(o.aSet <=  {1, 2, 3})
        self.assertTrue(o.aSet >=  o.aSet2)
        self.assertTrue(o.aSet >=  {1, 2, 3})
        self.assertFalse(o.aSet != o.aSet2)
        self.assertFalse(o.aSet != {1, 2, 3})

        o.aSet2 = {2, 3}
        self.assertTrue(o.aSet !=  o.aSet2)
        self.assertTrue(o.aSet !=  {1, 2})
        self.assertFalse(o.aSet == o.aSet2)
        self.assertFalse(o.aSet == {1, 2})

        o.aSet2 = { 1, 2, 3, 4}
        self.assertTrue(o.aSet < o.aSet2)
        self.assertTrue(o.aSet < {1, 2, 3, 4})
        self.assertTrue(o.aSet <= o.aSet2)
        self.assertTrue(o.aSet <= {1, 2, 3, 4})
        self.assertFalse(o.aSet > o.aSet2)
        self.assertFalse(o.aSet > {1, 2, 3, 4})
        self.assertFalse(o.aSet >= o.aSet2)
        self.assertFalse(o.aSet >= {1, 2, 3, 4})

        o.aSet2 = { 1 }
        self.assertTrue(o.aSet > o.aSet2)
        self.assertTrue(o.aSet > {1})
        self.assertTrue(o.aSet >= o.aSet2)
        self.assertTrue(o.aSet >= {1})
        self.assertFalse(o.aSet < o.aSet2)
        self.assertFalse(o.aSet < {1})
        self.assertFalse(o.aSet <= o.aSet2)
        self.assertFalse(o.aSet <= {1})

        if sys.version_info[0] == 2:
            o.aSet = {1, 2, 3}
            o.aSet2 = {1, 2 }

            self.assertRaises(TypeError, cmp, o.aSet, o.aSet2)
            #self.assertRaises(TypeError, cmp, o.aSet, {1})

            self.assertRaises(TypeError, o.aSet.__cmp__, o.aSet2)
            self.assertRaises(TypeError, o.aSet.__cmp__, {1})

    def testPickling(self):
        o = TestSetPropertyHelper.alloc().init()
        o.aSet = {1, 2, 3}

        self.assertFalse(isinstance(o.aSet, set))

        p = pickle.dumps(o.aSet)
        v = pickle.loads(p)
        self.assertEqual(o.aSet, v)
        self.assertTrue(isinstance(v, set))

if __name__ == "__main__":
    main()


text:
package org.nekorp.workflow.desktop.servicio.reporte.cliente;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFDataFormat;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.nekorp.workflow.desktop.modelo.reporte.cliente.RegistroCostoRC;
import org.nekorp.workflow.desktop.modelo.reporte.cliente.ReporteCliente;
import org.springframework.stereotype.Component;

/**
 *
 */
@Component
public class CostoMecanicaReporteCliente extends AbstractSeccionXLS implements GeneradorSeccionXLS {

    @Override
    public BordeSeccion generar(BordeSeccion borde, ContextoSeccion contexto, ReporteCliente datos) {
        Sheet sheet = contexto.getSheet();
        XSSFWorkbook wb = contexto.getWb();
        int initialRow = borde.getUpperRow();
        int initialColumn = borde.getLeftColumn();
        BordeSeccion r = new BordeSeccion();
        r.setLeftColumn(initialColumn);
        r.setUpperRow(initialRow);

        Cell cell;
        Row row = getRow(sheet, initialRow);
        cell = row.createCell(initialColumn);
        cell.setCellValue("Mecanica");
        XSSFCellStyle cellStyle = wb.createCellStyle();
        addHeaderStyle(cellStyle, wb);
        addBorders(wb, cellStyle, CellStyle.BORDER_MEDIUM);
        cell.setCellStyle(cellStyle);
        for (int i = 1; i < 3; i++) {
            cell = row.createCell(initialColumn + i);
            cellStyle = wb.createCellStyle();
            addBorders(wb, cellStyle, CellStyle.BORDER_MEDIUM);
            cell.setCellStyle(cellStyle);
        }
        //merge de celdas
        sheet.addMergedRegion(new CellRangeAddress(
                initialRow, //first row (0-based)
                initialRow, //last row  (0-based)
                initialColumn, //first column (0-based)
                initialColumn + 2  //last column  (0-based)
        ));

        //detalle
        cellStyle = wb.createCellStyle();
        XSSFDataFormat df = wb.createDataFormat();
        cellStyle.setDataFormat(df.getFormat("$#,##0.00"));
        Cell inicio = null;
        Cell fin = null;
        for (RegistroCostoRC x: datos.getRegistroMecanica()) {
            initialRow = initialRow + 1;
            row = getRow(sheet, initialRow);
            //tipo
            cell = row.createCell(initialColumn);
            cell.setCellValue(x.getTipo());
            //descripcion
            cell = row.createCell(initialColumn + 1);
            cell.setCellValue(x.getDescripcion());
            //costo
            cell = row.createCell(initialColumn + 2);
            cell.setCellValue(x.getCosto());
            cell.setCellStyle(cellStyle);
            if (inicio == null) {
               inicio = cell;
            }
        }
        if (inicio != null) {
            fin = cell;
        }
        initialRow = initialRow + 1;
        row = getRow(sheet, initialRow);
        cell = row.createCell(initialColumn + 1);
        cell.setCellValue("Total");
        cellStyle = wb.createCellStyle();
        XSSFFont font = wb.createFont();
        font.setBold(true);
        cellStyle.setFont(font);
        cell.setCellStyle(cellStyle);

        cellStyle = wb.createCellStyle();
        cellStyle.setFont(font);
        cellStyle.setDataFormat(df.getFormat("$#,##0.00"));
        cell = row.createCell(initialColumn + 2);
        cell.setCellStyle(cellStyle);
        if (inicio != null) {
            String formula = "SUM("+getSimpleReference(inicio)+":"+getSimpleReference(fin)+")";
            cell.setCellFormula(formula);
            contexto.put("totalMecanica", cell);
        } else {
            cell.setCellValue(0.0);
        }
        r.setLowerRow(initialRow);
        r.setRightColumn(initialColumn + 2);
        BordeSeccion sinTotal = new BordeSeccion(r);
        sinTotal.setLowerRow(r.getLowerRow() - 1);
        paintBorder(wb, sheet, CellStyle.BORDER_MEDIUM, sinTotal);
        return r;
    }

}

redpajama_set_name: RedPajamaGithub


text:
module Fog
  module Compute
    class Azure
      class Real
        def list_databases
          @db_svc.list_servers
        end
      end

      class Mock
        def list_databases
          db = ::Azure::SqlDatabaseManagement::SqlServer.new
          db.name = 'Mock Database'
          db.location = 'US East'
          [db]
        end
      end
    end
  end
end


text:
package net.violet.platform.daemons.crawlers.gestion;

import java.util.List;

import net.violet.platform.daemons.crawlers.AbstractCrawler;
import net.violet.platform.datamodel.InterruptionLogImpl;
import net.violet.platform.datamodel.VObject;
import net.violet.platform.datamodel.VObjectImpl;

import org.apache.log4j.Logger;

/** vérifie si un lapin en mode jabber n'est plus connecté */

public class CrawlerCheckJabber extends AbstractCrawler {

	private static final Logger LOGGER = Logger.getLogger(CrawlerCheckJabber.class);

	/**
	 * Walker sur les VObjectImpl.
	 */
	private final VObjectImpl.RecordWalker<VObject> mWalker;

	public CrawlerCheckJabber(String[] inArgs) {
		super(inArgs);
		this.mWalker = new VObjectImpl.RecordWalker<VObject>() {

			public void process(VObject inObject) {
				processObject(inObject);
			}
		};
	}

	/**
	 * Passage de l'objet jabber en mode inactif
	 *
	 * @param inObject
	 */
	private void processObject(VObject inObject) {
		final List<String> resources = inObject.getResources(); //IQResourcesQuery.getClientResources(inObject.getXmppAddress());
		if (resources.isEmpty()) {
			if (inObject.getObject_mode() != VObject.MODE_XMPP_INACTIVE) {
				inObject.setMode(VObject.MODE_XMPP_INACTIVE);
				InterruptionLogImpl.insert(inObject, InterruptionLogImpl.WHAT_OPTION.OFFLINE, "CrawlerCheckJabber");
			}
		} else {
			inObject.setMode(VObject.MODE_XMPP);
		}
	}

	@Override
	protected void process() {
		final int nbProcessed = VObjectImpl.walkCheckJabber(this.mWalker);
		CrawlerCheckJabber.LOGGER.info(" total : " + nbProcessed);
	}
}


text:
var menuOpen = false;

var showhidemenu = function(){
	if (menuOpen){
		moveTo="0";
		menuOpen=false;
	}else{
		moveTo="250dp";
		menuOpen=true;
	}

	$.drawermainview.width=Ti.Platform.displayCaps.platformWidth;
	$.drawermainview.animate({
		left:moveTo,
		curve : Ti.UI.ANIMATION_CURVE_EASE_OUT,
		duration:400
	});
}

Ti.Gesture.addEventListener('orientationchange', function(e) {
    $.drawermainview.width=Ti.Platform.displayCaps.platformWidth;
});

exports.showhidemenu=showhidemenu;


text:
  <?php if ((!method_exists($sf_guard_user, 'userHasPrivilege')) || $sf_guard_user->userHasPrivilege('edit')): ?>
  <input type="checkbox" name="ids[]" value="<?php echo $sf_guard_user->getPrimaryKey() ?>" class="a-admin-batch-checkbox a-checkbox" />
  <?php endif; ?>


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.04.17 at 03:16:44 PM AEST
//

package au.com.scds.agric.fixture.xml.generated;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

/**
 *
Java class for CompletedOrderLine complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="CompletedOrderLine">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="order-line" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="completed-on" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
 *         <element name="completed-by" type="{http://www.example.org/AgricProducerSchema}Person" minOccurs="0"/>
 *         <element name="product-pack" type="{http://www.example.org/AgricProducerSchema}ProductPack" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CompletedOrderLine", propOrder = {
    "orderLine",
    "completedOn",
    "completedBy",
    "productPack"
})
public class CompletedOrderLine {

    @XmlElement(name = "order-line", required = true)
    protected String orderLine;
    @XmlElement(name = "completed-on", type = String.class)
    @XmlJavaTypeAdapter(Adapter1 .class)
    @XmlSchemaType(name = "dateTime")
    protected Date completedOn;
    @XmlElement(name = "completed-by")
    protected Person completedBy;
    @XmlElement(name = "product-pack")
    protected List<ProductPack> productPack;

    /**
     * Gets the value of the orderLine property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getOrderLine() {
        return orderLine;
    }

    /**
     * Sets the value of the orderLine property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setOrderLine(String value) {
        this.orderLine = value;
    }

    /**
     * Gets the value of the completedOn property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public Date getCompletedOn() {
        return completedOn;
    }

    /**
     * Sets the value of the completedOn property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setCompletedOn(Date value) {
        this.completedOn = value;
    }

    /**
     * Gets the value of the completedBy property.
     *
     * @return
     *     possible object is
     *     {@link Person }
     *
     */
    public Person getCompletedBy() {
        return completedBy;
    }

    /**
     * Sets the value of the completedBy property.
     *
     * @param value
     *     allowed object is
     *     {@link Person }
     *
     */
    public void setCompletedBy(Person value) {
        this.completedBy = value;
    }

    /**
     * Gets the value of the productPack property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the productPack property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getProductPack().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link ProductPack }
     *
     *
     */
    public List<ProductPack> getProductPack() {
        if (productPack == null) {
            productPack = new ArrayList<ProductPack>();
        }
        return this.productPack;
    }

}


text:
$packages  = @(
    "golang.Go"
)

$code = "C:\Program Files\Microsoft VS Code\bin\code.cmd"

foreach ($package in $packages) {
    Start-Process -FilePath $code -ArgumentList "--install-extension $package --force" -NoNewWindow -Wait
}


text:
/**
 * Created by DavidHong on 2015. 6. 25..
 */

var router = require('express').Router()
var bcrypt = require('bcrypt')
var jwt =    require('jwt-simple')
var User =   require('../../models/user')
var config = require('../../config')

router.get('/users', function(req, res, next) {
    if(!req.headers['x-auth']) {
        return res.send(401)
    }

    var auth = jwt.decode(req.headers['x-auth'], config.secret)
    User.findOne({username: auth.username}, function (err, user) {
        if(err) { return next(err) }
        res.json(user)
    })
})

router.post('/users', function(req, res, next) {
    var user = new User({username: req.body.username})

    bcrypt.hash(req.body.password, 10, function (err, hash){
        if(err) { return next(err) }
        user.password = hash;
        user.save(function (err) {
            if(err) { return next(err) }
            res.sendStatus(201)
        })
    })
})

module.exports = router


text:
<?php

namespace Zend\Mvc\Controller;

use Zend\Mvc\Exception;
use Zend\ServiceManager\AbstractPluginManager;
use Zend\Stdlib\DispatchableInterface;

/**
 * Plugin manager implementation for controllers
 *
 * Registers a number of default plugins, and contains an initializer for
 * injecting plugins with the current controller.
 */
class PluginManager extends AbstractPluginManager
{
    /**
     * Default set of plugins factories
     *
     * @var array
     */
    protected $factories = array(
        'forward'  => 'Zend\Mvc\Controller\Plugin\Service\ForwardFactory',
        'identity' => 'Zend\Mvc\Controller\Plugin\Service\IdentityFactory',
    );

    /**
     * Default set of plugins
     *
     * @var array
     */
    protected $invokableClasses = array(
        'acceptableviewmodelselector' => 'Zend\Mvc\Controller\Plugin\AcceptableViewModelSelector',
        'filepostredirectget'         => 'Zend\Mvc\Controller\Plugin\FilePostRedirectGet',
        'flashmessenger'              => 'Zend\Mvc\Controller\Plugin\FlashMessenger',
        'layout'                      => 'Zend\Mvc\Controller\Plugin\Layout',
        'params'                      => 'Zend\Mvc\Controller\Plugin\Params',
        'postredirectget'             => 'Zend\Mvc\Controller\Plugin\PostRedirectGet',
        'redirect'                    => 'Zend\Mvc\Controller\Plugin\Redirect',
        'url'                         => 'Zend\Mvc\Controller\Plugin\Url',
        'createhttpnotfoundmodel'     => 'Zend\Mvc\Controller\Plugin\CreateHttpNotFoundModel',
        'createconsolenotfoundmodel'  => 'Zend\Mvc\Controller\Plugin\CreateConsoleNotFoundModel',
    );

    /**
     * Default set of plugin aliases
     *
     * @var array
     */
    protected $aliases = array(
        'prg'     => 'postredirectget',
        'fileprg' => 'filepostredirectget',
    );

    /**
     * @var DispatchableInterface
     */
    protected $controller;

    /**
     * Retrieve a registered instance
     *
     * After the plugin is retrieved from the service locator, inject the
     * controller in the plugin every time it is requested. This is required
     * because a controller can use a plugin and another controller can be
     * dispatched afterwards. If this second controller uses the same plugin
     * as the first controller, the reference to the controller inside the
     * plugin is lost.
     *
     * @param  string $name
     * @param  mixed  $options
     * @param  bool   $usePeeringServiceManagers
     * @return mixed
     */
    public function get($name, $options = array(), $usePeeringServiceManagers = true)
    {
        $plugin = parent::get($name, $options, $usePeeringServiceManagers);
        $this->injectController($plugin);

        return $plugin;
    }

    /**
     * Set controller
     *
     * @param  DispatchableInterface $controller
     * @return PluginManager
     */
    public function setController(DispatchableInterface $controller)
    {
        $this->controller = $controller;

        return $this;
    }

    /**
     * Retrieve controller instance
     *
     * @return null|DispatchableInterface
     */
    public function getController()
    {
        return $this->controller;
    }

    /**
     * Inject a helper instance with the registered controller
     *
     * @param  object $plugin
     * @return void
     */
    public function injectController($plugin)
    {
        if (!is_object($plugin)) {
            return;
        }
        if (!method_exists($plugin, 'setController')) {
            return;
        }

        $controller = $this->getController();
        if (!$controller instanceof DispatchableInterface) {
            return;
        }

        $plugin->setController($controller);
    }

    /**
     * Validate the plugin
     *
     * Any plugin is considered valid in this context.
     *
     * @param  mixed                            $plugin
     * @return void
     * @throws Exception\InvalidPluginException
     */
    public function validatePlugin($plugin)
    {
        if ($plugin instanceof Plugin\PluginInterface) {
            // we're okay
            return;
        }

        throw new Exception\InvalidPluginException(sprintf(
            'Plugin of type %s is invalid; must implement %s\Plugin\PluginInterface',
            (is_object($plugin) ? get_class($plugin) : gettype($plugin)),
            __NAMESPACE__
        ));
    }
}


text:
namespace wn {
namespace engine_base {
class context;
}
namespace engine {
namespace renderer {

struct render_data : scripting::script_object_type {
  using parent_type = void;

  void export_type(
      scripting::engine::script_type_importer<render_data>* _importer) {
    _importer->register_function("register_data", &register_data);
  }

  static wn::containers::string_view exported_name() {
    return "RenderData";
  }

  static wn::containers::string_view required_script() {
    return "renderer/render_data.wns";
  }

  scripting::scripting_virtual_object_function<render_data, void> register_data;

  static void register_scripting(scripting::engine* _engine);
  static bool resolve_scripting(scripting::engine* _engine);
};

struct render_dependency : scripting::script_object_type {
  using parent_type = void;

  void export_type(
      scripting::engine::script_type_importer<render_dependency>* _importer) {
    _importer->register_function("get_render_target", &get_render_target);
    _importer->register_function("get_frame_offset", &get_frame_offset);
  }

  static wn::containers::string_view exported_name() {
    return "RenderDependency";
  }

  static void register_scripting(scripting::engine* _engine);
  static bool resolve_scripting(scripting::engine* _engine);

  static wn::containers::string_view required_script() {
    return "renderer/pass_data.wns";
  }

  scripting::scripting_object_function<render_dependency, int32_t>
      get_render_target;
  scripting::scripting_object_function<render_dependency, int32_t>
      get_frame_offset;
};

struct render_target_usage : scripting::script_object_type {
  using parent_type = void;
  void export_type(
      scripting::engine::script_type_importer<render_target_usage>* _importer) {
    _importer->register_function("get_render_target", &get_render_target);
    _importer->register_function("get_clear_mode", &get_clear_mode);
    _importer->register_function("get_store_mode", &get_store_mode);
  }

  static wn::containers::string_view exported_name() {
    return "RenderTargetUsage";
  }

  static void register_scripting(scripting::engine* _engine);
  static bool resolve_scripting(scripting::engine* _engine);

  static wn::containers::string_view required_script() {
    return "renderer/pass_data.wns";
  }

  scripting::scripting_object_function<render_target_usage, int32_t>
      get_render_target;
  scripting::scripting_object_function<render_target_usage, int32_t>
      get_clear_mode;
  scripting::scripting_object_function<render_target_usage, int32_t>
      get_store_mode;
};

struct pass_data : scripting::script_object_type {
  using parent_type = void;

  void export_type(
      scripting::engine::script_type_importer<pass_data>* _importer) {
    _importer->register_function("get_pass_name", &get_pass_name);
    _importer->register_function("get_render_targets", &get_render_targets);
    _importer->register_function("get_depth_target", &get_depth_target);
    _importer->register_function(
        "get_render_dependencies", &get_render_dependencies);
  }

  static wn::containers::string_view exported_name() {
    return "PassData";
  }

  static wn::containers::string_view required_script() {
    return "renderer/pass_data.wns";
  }

  scripting::scripting_object_function<pass_data, const char*> get_pass_name;
  scripting::scripting_object_function<pass_data,
      scripting::wn_array<scripting::script_pointer<render_target_usage>>>
      get_render_targets;
  scripting::scripting_object_function<pass_data,
      scripting::script_pointer<render_target_usage>>
      get_depth_target;
  scripting::scripting_object_function<pass_data,
      scripting::wn_array<scripting::script_pointer<render_dependency>>>
      get_render_dependencies;

  static void register_scripting(scripting::engine* _engine);
  static bool resolve_scripting(scripting::engine* _engine);
};

struct render_description : scripting::script_object_type {
  using parent_type = void;
  static wn::containers::string_view exported_name() {
    return "RenderDescription";
  }

  static wn::containers::string_view required_script() {
    return "renderer/render_description.wns";
  }

  void export_type(
      scripting::engine::script_type_importer<render_description>* _importer) {
    _importer->register_function("get_render_targets", &get_render_targets);
    _importer->register_function("get_passes", &get_passes);
    _importer->register_function("get_output_target", &get_output_target);
  }

  wn::scripting::scripting_object_function<render_description,
      scripting::wn_array<scripting::shared_script_pointer<rt_description>>>
      get_render_targets;
  wn::scripting::scripting_object_function<render_description,
      scripting::wn_array<scripting::script_pointer<pass_data>>>
      get_passes;
  wn::scripting::scripting_object_function<render_description, int32_t>
      get_output_target;
};

}  // namespace renderer
}  // namespace engine
}  // namespace wn

#endif  // __WN_ENGINE_RENDERER_RENDERER_H__


text:
import os
import shutil
import sys
from typing import (
    Any,
    cast,
    ClassVar,
    Generic,
    List,
    Optional,
    Type,
    TYPE_CHECKING,
    TypeVar,
    Union,
)

import wandb
from wandb import util
from wandb.sdk.interface.artifacts import b64_string_to_hex, md5_files_b64

from ._private import MEDIA_TMP
from .base_types.wb_value import WBValue

if TYPE_CHECKING:  # pragma: no cover
    from wandb.apis.public import Artifact as PublicArtifact

    from ..wandb_artifacts import Artifact as LocalArtifact
    from ..wandb_run import Run as LocalRun

    import cloudpickle  # type: ignore
    import torch  # type: ignore
    import sklearn  # type: ignore
    import tensorflow  # type: ignore

DEBUG_MODE = False

def _add_deterministic_dir_to_artifact(
    artifact: "LocalArtifact", dir_name: str, target_dir_root: str
) -> str:
    file_paths = []
    for dirpath, _, filenames in os.walk(dir_name, topdown=True):
        for fn in filenames:
            file_paths.append(os.path.join(dirpath, fn))
    dirname = b64_string_to_hex(md5_files_b64(file_paths))[:20]
    target_path = util.to_forward_slash_path(os.path.join(target_dir_root, dirname))
    artifact.add_dir(dir_name, target_path)
    return target_path

def _load_dir_from_artifact(source_artifact: "PublicArtifact", path: str) -> str:
    dl_path = None

    # Look through the entire manifest to find all of the files in the directory.
    # Construct the directory path by inspecting the target download location.
    for p, _ in source_artifact.manifest.entries.items():
        if p.startswith(path):
            example_path = source_artifact.get_path(p).download()
            if dl_path is None:
                root = example_path[: -len(p)]
                dl_path = os.path.join(root, path)

    assert dl_path is not None, f"Could not find directory {path} in artifact"

    return dl_path

SavedModelObjType = TypeVar("SavedModelObjType")

class _SavedModel(WBValue, Generic[SavedModelObjType]):
    """SavedModel is a private data type that can be used to store a model object
    inside of a W&B Artifact.

    _model_type_id: (str) The id of the SavedModel subclass used to serialize the model.
    """

    _log_type: ClassVar[str]
    _path_extension: ClassVar[str]

    _model_obj: Optional["SavedModelObjType"]
    _path: Optional[str]
    _input_obj_or_path: Union[SavedModelObjType, str]

    # Public Methods
    def __init__(
        self, obj_or_path: Union[SavedModelObjType, str], **kwargs: Any
    ) -> None:
        super().__init__()
        if self.__class__ == _SavedModel:
            raise TypeError(
                "Cannot instantiate abstract SavedModel class - please use SavedModel.init(...) instead."
            )
        self._model_obj = None
        self._path = None
        self._input_obj_or_path = obj_or_path
        input_is_path = isinstance(obj_or_path, str) and os.path.exists(obj_or_path)
        if input_is_path:
            assert isinstance(obj_or_path, str)  # mypy
            self._set_obj(self._deserialize(obj_or_path))
        else:
            self._set_obj(obj_or_path)

        self._copy_to_disk()
        # At this point, the model will be saved to a temp path,
        # and self._path will be set to such temp path. If the model
        # provided was a path, then both self._path and self._model_obj
        # are copies of the user-provided data. However, if the input
        # was a model object, then we want to clear the model object. The first
        # accessing of the model object (via .model_obj()) will load the model
        # from the temp path.

        if not input_is_path:
            self._unset_obj()

    @staticmethod
    def init(obj_or_path: Any, **kwargs: Any) -> "_SavedModel":
        maybe_instance = _SavedModel._maybe_init(obj_or_path, **kwargs)
        if maybe_instance is None:
            raise ValueError(
                f"No suitable SavedModel subclass constructor found for obj_or_path: {obj_or_path}"
            )
        return maybe_instance

    @classmethod
    def from_json(
        cls: Type["_SavedModel"], json_obj: dict, source_artifact: "PublicArtifact"
    ) -> "_SavedModel":
        path = json_obj["path"]

        # First, if the entry is a file, the download it.
        entry = source_artifact.manifest.entries.get(path)
        if entry is not None:
            dl_path = source_artifact.get_path(path).download()
        else:
            # If not, assume it is directory.
            # FUTURE: Add this functionality to the artifact loader
            # (would be nice to parallelize)
            dl_path = _load_dir_from_artifact(source_artifact, path)

        # Return the SavedModel object instantiated with the downloaded path
        # and specified adapter.
        return cls(dl_path)

    def to_json(self, run_or_artifact: Union["LocalRun", "LocalArtifact"]) -> dict:
        # Unlike other data types, we do not allow adding to a Run directly. There is a
        # bit of tech debt in the other data types which requires the input to `to_json`
        # to accept a Run or Artifact. However, Run additions should be deprecated in the future.
        # This check helps ensure we do not add to the debt.
        if isinstance(run_or_artifact, wandb.wandb_sdk.wandb_run.Run):
            raise ValueError("SavedModel cannot be added to run - must use artifact")
        artifact = run_or_artifact
        json_obj = {
            "type": self._log_type,
        }
        assert self._path is not None, "Cannot add SavedModel to Artifact without path"
        if os.path.isfile(self._path):
            # If the path is a file, then we can just add it to the artifact,
            # First checking to see if the artifact already has the file (use the cache)
            # Else, add it directly, allowing the artifact adder to rename the file deterministically.
            already_added_path = artifact.get_added_local_path_name(self._path)
            if already_added_path is not None:
                json_obj["path"] = already_added_path
            else:
                target_path = os.path.join(
                    ".wb_data", "saved_models", os.path.basename(self._path)
                )
                json_obj["path"] = artifact.add_file(self._path, target_path, True).path
        elif os.path.isdir(self._path):
            # If the path is a directory, then we need to add all of the files
            # The directory must be named deterministically based on the contents of the directory,
            # but the files themselves need to have their name preserved.
            # FUTURE: Add this functionality to the artifact adder itself
            json_obj["path"] = _add_deterministic_dir_to_artifact(
                artifact, self._path, os.path.join(".wb_data", "saved_models")
            )
        else:
            raise ValueError(
                f"Expected a path to a file or directory, got {self._path}"
            )

        return json_obj

    def model_obj(self) -> SavedModelObjType:
        """Returns the model object."""
        if self._model_obj is None:
            assert self._path is not None, "Cannot load model object without path"
            self._set_obj(self._deserialize(self._path))

        assert self._model_obj is not None, "Model object is None"
        return self._model_obj

    # Methods to be implemented by subclasses
    @staticmethod
    def _deserialize(path: str) -> SavedModelObjType:
        """Returns the model object from a path. Allowed to throw errors"""
        raise NotImplementedError()

    @staticmethod
    def _validate_obj(obj: Any) -> bool:
        """Validates the model object. Allowed to throw errors"""
        raise NotImplementedError()

    @staticmethod
    def _serialize(obj: SavedModelObjType, dir_or_file_path: str) -> None:
        """Save the model to disk. The method will receive a directory path which all
        files needed for deserialization should be saved. A directory will always be passed if
        _path_extension is an empty string, else a single file will be passed. Allowed to throw errors
        """
        raise NotImplementedError()

    # Private Class Methods
    @classmethod
    def _maybe_init(
        cls: Type["_SavedModel"], obj_or_path: Any, **kwargs: Any
    ) -> Optional["_SavedModel"]:
        # _maybe_init is an exception-safe method that will return an instance of this class
        # (or any subclass of this class - recursively) OR None if no subclass constructor is found.
        # We first try the current class, then recursively call this method on children classes. This pattern
        # conforms to the new "Weave-type" pattern developed by Shawn. This way, we can for example have a
        # pytorch subclass that can itself have two subclasses: one for a TorchScript model, and one for a PyTorch model.
        # The children subclasses will know how to serialize/deserialize their respective payloads, but the pytorch
        # parent class can know how to execute inference on the model - regardless of serialization strategy.
        try:
            return cls(obj_or_path, **kwargs)
        except Exception as e:
            if DEBUG_MODE:
                print(f"{cls}._maybe_init({obj_or_path}) failed: {e}")
            pass

        for child_cls in cls.__subclasses__():
            maybe_instance = child_cls._maybe_init(obj_or_path, **kwargs)
            if maybe_instance is not None:
                return maybe_instance

        return None

    @classmethod
    def _tmp_path(cls: Type["_SavedModel"]) -> str:
        # Generates a tmp path under our MEDIA_TMP directory which confirms to the file
        # or folder preferences of the class.
        assert isinstance(cls._path_extension, str), "_path_extension must be a string"
        tmp_path = os.path.abspath(
            os.path.join(MEDIA_TMP.name, str(util.generate_id()))
        )
        if cls._path_extension != "":
            tmp_path += "." + cls._path_extension
        return tmp_path

    # Private Instance Methods
    def _copy_to_disk(self) -> None:
        # Creates a temporary path and writes a fresh copy of the
        # model to disk - updating the _path appropriately.
        tmp_path = self._tmp_path()
        self._dump(tmp_path)
        self._path = tmp_path

    def _unset_obj(self) -> None:
        assert self._path is not None, "Cannot unset object if path is None"
        self._model_obj = None

    def _set_obj(self, model_obj: Any) -> None:
        assert model_obj is not None and self._validate_obj(
            model_obj
        ), f"Invalid model object {model_obj}"
        self._model_obj = model_obj

    def _dump(self, target_path: str) -> None:
        assert self._model_obj is not None, "Cannot dump if model object is None"
        self._serialize(self._model_obj, target_path)

def _get_cloudpickle() -> "cloudpickle":
    return cast(
        "cloudpickle",
        util.get_module("cloudpickle", "ModelAdapter requires `cloudpickle`"),
    )

# TODO: Add pip deps
# TODO: potentially move this up to the saved model class
PicklingSavedModelObjType = TypeVar("PicklingSavedModelObjType")

class _PicklingSavedModel(_SavedModel[SavedModelObjType]):
    _dep_py_files: Optional[List[str]] = None
    _dep_py_files_path: Optional[str] = None

    def __init__(
        self,
        obj_or_path: Union[SavedModelObjType, str],
        dep_py_files: Optional[List[str]] = None,
    ):
        super().__init__(obj_or_path)
        if self.__class__ == _PicklingSavedModel:
            raise TypeError(
                "Cannot instantiate abstract _PicklingSavedModel class - please use SavedModel.init(...) instead."
            )
        if dep_py_files is not None and len(dep_py_files) > 0:
            self._dep_py_files = dep_py_files
            self._dep_py_files_path = os.path.abspath(
                os.path.join(MEDIA_TMP.name, str(util.generate_id()))
            )
            os.makedirs(self._dep_py_files_path, exist_ok=True)
            for extra_file in self._dep_py_files:
                if os.path.isfile(extra_file):
                    shutil.copy(extra_file, self._dep_py_files_path)
                elif os.path.isdir(extra_file):
                    shutil.copytree(
                        extra_file,
                        os.path.join(
                            self._dep_py_files_path, os.path.basename(extra_file)
                        ),
                    )
                else:
                    raise ValueError(f"Invalid dependency file: {extra_file}")

    @classmethod
    def from_json(
        cls: Type["_SavedModel"], json_obj: dict, source_artifact: "PublicArtifact"
    ) -> "_PicklingSavedModel":
        backup_path = [p for p in sys.path]
        if (
            "dep_py_files_path" in json_obj
            and json_obj["dep_py_files_path"] is not None
        ):
            dl_path = _load_dir_from_artifact(
                source_artifact, json_obj["dep_py_files_path"]
            )
            assert dl_path is not None
            sys.path.append(dl_path)
        inst = super().from_json(json_obj, source_artifact)  # type: ignore
        sys.path = backup_path

        return inst  # type: ignore

    def to_json(self, run_or_artifact: Union["LocalRun", "LocalArtifact"]) -> dict:
        json_obj = super().to_json(run_or_artifact)
        assert isinstance(run_or_artifact, wandb.wandb_sdk.wandb_artifacts.Artifact)
        if self._dep_py_files_path is not None:
            json_obj["dep_py_files_path"] = _add_deterministic_dir_to_artifact(
                run_or_artifact,
                self._dep_py_files_path,
                os.path.join(".wb_data", "extra_files"),
            )
        return json_obj

def _get_torch() -> "torch":
    return cast(
        "torch",
        util.get_module("torch", "ModelAdapter requires `torch`"),
    )

class _PytorchSavedModel(_PicklingSavedModel["torch.nn.Module"]):
    _log_type = "pytorch-model-file"
    _path_extension = "pt"

    @staticmethod
    def _deserialize(dir_or_file_path: str) -> "torch.nn.Module":
        return _get_torch().load(dir_or_file_path)

    @staticmethod
    def _validate_obj(obj: Any) -> bool:
        return isinstance(obj, _get_torch().nn.Module)

    @staticmethod
    def _serialize(model_obj: "torch.nn.Module", dir_or_file_path: str) -> None:
        _get_torch().save(
            model_obj,
            dir_or_file_path,
            pickle_module=_get_cloudpickle(),
        )

def _get_sklearn() -> "sklearn":
    return cast(
        "sklearn",
        util.get_module("sklearn", "ModelAdapter requires `sklearn`"),
    )

class _SklearnSavedModel(_PicklingSavedModel["sklearn.base.BaseEstimator"]):
    _log_type = "sklearn-model-file"
    _path_extension = "pkl"

    @staticmethod
    def _deserialize(
        dir_or_file_path: str,
    ) -> "sklearn.base.BaseEstimator":
        with open(dir_or_file_path, "rb") as file:
            model = _get_cloudpickle().load(file)
        return model

    @staticmethod
    def _validate_obj(obj: Any) -> bool:
        dynamic_sklearn = _get_sklearn()
        return cast(
            bool,
            (
                dynamic_sklearn.base.is_classifier(obj)
                or dynamic_sklearn.base.is_outlier_detector(obj)
                or dynamic_sklearn.base.is_regressor(obj)
            ),
        )

    @staticmethod
    def _serialize(
        model_obj: "sklearn.base.BaseEstimator", dir_or_file_path: str
    ) -> None:
        dynamic_cloudpickle = _get_cloudpickle()
        with open(dir_or_file_path, "wb") as file:
            dynamic_cloudpickle.dump(model_obj, file)

def _get_tf_keras() -> "tensorflow.keras":
    return cast(
        "tensorflow",
        util.get_module("tensorflow", "ModelAdapter requires `tensorflow`"),
    ).keras

class _TensorflowKerasSavedModel(_SavedModel["tensorflow.keras.Model"]):
    _log_type = "tfkeras-model-file"
    _path_extension = ""

    @staticmethod
    def _deserialize(
        dir_or_file_path: str,
    ) -> "tensorflow.keras.Model":
        return _get_tf_keras().models.load_model(dir_or_file_path)

    @staticmethod
    def _validate_obj(obj: Any) -> bool:
        return isinstance(obj, _get_tf_keras().models.Model)

    @staticmethod
    def _serialize(model_obj: "tensorflow.keras.Model", dir_or_file_path: str) -> None:
        _get_tf_keras().models.save_model(
            model_obj, dir_or_file_path, include_optimizer=True
        )


text:
package io.fabric8.kubernetes.client.dsl;

public interface BytesLimitTerminateTimeTailPrettyLoggable extends TimeTailPrettyLoggable {

  /**
   * Configure Maximum bytes of logs to return. Defaults to no limit.
   *
   * @param limitBytes number of bytes
   * @return returns pod log operation with specified PodLogOption configured
   */
  TimeTailPrettyLoggable limitBytes(int limitBytes);

  /**
   * Get logs for the previous instance of the container in a pod if it exists:
   *
   * @return returns pod log operation with specified PodLogOption configured
   */
  TimeTailPrettyLoggable terminated();
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

	<artifactId>persistence-mongodb</artifactId>
	<packaging>jar</packaging>
	<name>persistence-mongodb</name>
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>de.evoila.cf.broker</groupId>
		<artifactId>persistence-parent</artifactId>
		<relativePath>../</relativePath>
		<version>1.2.0</version>
	</parent>

	<properties>
		<persistence.version>1.2.0</persistence.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-mongodb</artifactId>
		</dependency>

		<dependency>
			<groupId>de.evoila.cf.broker</groupId>
			<artifactId>core</artifactId>
		</dependency>
		<dependency>
			<groupId>de.evoila.cf.broker</groupId>
			<artifactId>model</artifactId>
		</dependency>
	</dependencies>

</project>


text:
layout: post
category: blog
author: atax1a
title: Urbit Is : Chapter 0
date: 2013-12-13 17:23
---

#Introduction#

Greetings from the off-world colonies! I'm your guide and scribe,
`atax1a`, a character from a book that hasn't been written yet. Every
great book has a Chapter 0, though, and you are reading mine.

I am often asked...
#What Is Urbit?#

Urbit could be a way of sharing your data in a way that makes it live
forever.  Maybe it's a Facebook of memories, 140 Twitters of words, or
an Instagram for when you're a grandpa. Maybe you send Urbit an email.
You can hit it with your web browser right now, but that's a bit rough
around the edges. (Given time, it could even be that BBS or MUD that
you wanted, but could never have...) It could be anything --- right
now, we use it as a glorified chat program, but one that never loses
messages. Well, almost never.  Sometimes we have to reboot the
Universe, and everything we haven't backed up is lost.

You may be getting the idea that Urbit is hard to define precisely. It is,
because it isn't finished yet. In reality, Urbit is just a labyrinth
of code, written as a book, running on a virtual machine (possibly
running on another virtual machine, and so on), built out of physical
parts, and it's read and written )and edited( by human mammals on a
planet called Earth. (The Urbit computer follows a "Hears, knows,
does" model, which I can explain later.) A lot of Earthlings call it
an art project, which isn't far off. Sometime it's Dada, other times
it's baroque, but it always has a precise scientific backing in the
form of *Nock*, which are the fundamental axioms (rules) of the
Urbiverse. Nock is all numbers, tho, and it's tiring.

Urbit is also a programming language. We call that *Hoon*, for reasons
I'm still not quite clear on. It takes Nock's numbers and puts symbols
on them. They're kinda weird symbols, and most "real" programmers I
know (and work with) take one look at something like

    |=(x=@ ?:((lth x 2) 1 (add $(x (dec x)) $(x (sub x 2)))))

and go pale around the gills. Myself, I grew up speaking a language
called `perl`, which has an even bigger love-affair with special
characters, so reading this doesn't faze me (Hoon uses its special
characters judiciously, so please don't think of `perl` unless you like
that sort of thing).

An earlier version of Urbit (when Hoon was still called Watt) was
rejected from a real scientific conference because the judges felt
vaguely insulted by the nonstandard language. The Urbit you're looking
at now has had a few years to cool down and mature, and right now it's
so cool at the core that it's well below -400 Fahrenheit. Thankfully,
there is an entire planet built up around its icy core, and on the
surface of that planet, it's a balmy 25 degrees Celsius, and the water
is like glass.

Urbit is currently only usable by a hyperliterate set of people ---
it's immersed in the culture of the word, and it's struggling for a
glimpse of air, the sound of music, and a taste of freedom.  Really,
though, it's easy to teach yourself, if you work through it with a
dedicated mind. Having a friend along for the ride is definitely
recommended. People with prior programming experience are welcome, but
be warned: your existing biases and expectations are wrong. We'll try
and be gentle about breaking them.

#Why should I care? (the buried lede)#

In the end, Urbit is a single global computer. Think "Cyberspace" from
_Neuromancer_, or "The Metaverse" from _Snow Crash_. If you're really
early, think of Haflinger's worm from _The Shockwave Rider_. But don't
think of it as the Internet --- the internet is a single global
_network_, and it only follows two rules: you can act like a UNIX
machine when prompted, and you speak TCP/IP. Anyone can see what
you're saying, and most people can understand it. There are gaps in
the network, too: _The Great Firewall Of China_, anyone? "Encryption",
or as I might call it, _privacy_, is an afterthought, and people who
Never Say Anything can read a lot of supposedly "private" things, just
by doing the right math. *Urbit isn't like that*. It enables secure,
private, computing, in a way that nobody else can, because it is
"semantically isolated" --- the meaning of the Urbit program is
independent of the outside world (in this case, the Internet).

Urbit works like an Internet should. If you know someone's address,
you can send them a message. It will either reliably be delivered, or
get rejected. Likewise with requesting something: if you ask for
tomorrow's newspaper headline _today_, Urbit will gladly give it to
you...  tomorrow. Your ship just waits for it to come in, and when it
does, everything proceeds like normal. "HTTP 404 Not Found"? What the
`!^&#` does THAT mean?

##Who ARE you people?##

We're dreamers, but the dream escaped and is slowly consuming the real
world. We're programmers with a sense of humor and an overload of
whimsy. At the end of the day, though, we're just people just like
you. People who want to change the world.  Everyone wants to change
the world, right?

##And what is with all of the weird words?##

Urbit is a piece of technology. Unfortunately, technology is hard to
explain, and it gets harder when the words we use to explain it are
misunderstood.  If you're used to speaking about your computers in
terms of a Unix (or Windows) workstation, it's a bit of a leap to
think in terms of Urbit ships in a pier.

In short, we use weird words to force a change in how our technology
is perceived. Without that, readers are likely to gloss over important
details, thinking that they understand more than they really do. It's
why we redefine everything, change the pronunciation of the symbols
you're used to, and even have our own number system. Count with me,
and feel free to scribble in the margins:

    ~zod 0   (also 'yes')                 if i were rewriting this
    ~nec 1   (no)                            i would put 'can' b4
    ~bud 2   [the rest of the numberz        'change meaning…'
    ~wes 3        change meaning
    ~sev 4    according to context]
    ~per 5   ---
    ~sut 6   <but that's 0kay>
    ~let 7
    ~ful 8
    ~pen 9   ¡you can figure it out!

Saying them out loud helps. You and your friend can agree on the
pronunciation.

#Introductions#

You can get in touch with me on Urbit, of course. Join up to `:chat`
and use `=` to see who's in the room. On the old internet, I go by
many names, but on this one I try to stick with `~hatteb-mitlyd`.


text:
package com.lee.main.system.edgeeffect;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.Resources;

/**
 * EdgeEffect ContextWrapper
 * </p>
 * Created by LiYang on 2017/6/22.
 */

public class EdgeEffectContextWrapper extends ContextWrapper {

    private static EdgeEffectResources RES_EDGE_EFFECT;

    public EdgeEffectContextWrapper(Context context) {
        super(context);
        Resources resources = context.getResources();
        if (RES_EDGE_EFFECT == null) {
            RES_EDGE_EFFECT = new EdgeEffectResources(resources.getAssets(), resources.getDisplayMetrics(), resources.getConfiguration());
        }
    }

    public Resources getResources() {
        return RES_EDGE_EFFECT;
    }

}


text:
class Word
    def initialize(vocable, language="english")
        @vocable = vocable
        @language = language
    end

    def vocable
        @vocable
    end

    def language
        @language
    end

    def set_vocable(new_voc)
        @vocable = new_voc
    end

    def set_def(new_def)
        @def = new_def
    end
end


text:
import os
import math
import logging
import time
import rasterio
from rasterio.io import MemoryFile
from rasterio.features import shapes
from rasterio.windows import union
from rasterio.warp import transform_geom
from shapely.geometry import shape
import json

def read_records(file_name, src_crs, centroid_only):
    #total_bytes = os.path.getsize(file_name)

    # do first window
    t0 = time.process_time()
    with open(file_name, 'rb') as f, MemoryFile(f.read()) as m, m.open() as src:
    #with open(file_name, 'rb') as f, rasterio.open(f) as src:
        logging.info('opening file time: {}'.format(time.process_time() - t0))

        t1 = time.process_time()
        block_windows = list([win for ji, win in src.block_windows()])
        logging.info('list block windows: {}'.format(time.process_time() - t1))
        num_windows = len(block_windows)
        #window_bytes = math.floor(total_bytes / num_windows)
        t2 = time.process_time()
        window_slice = block_windows[0:math.ceil(num_windows / 2)]
        cur_window = union(window_slice)
        cur_transform = src.window_transform(cur_window)
        block_mask = src.read_masks(1, window=cur_window)
        block = src.read(1, window=cur_window, masked=True)
        logging.info('windowing stuff + src.read {}'.format(time.process_time() - t2))

        t3 = time.process_time()
        block_shapes = shapes(block, block_mask, transform=cur_transform)
        logging.info('shapes {}'.format(time.process_time() - t3))

        for (g, v) in block_shapes:
            #geom = transform_geom(src_crs, 'epsg:4326', g)

            if centroid_only:
                geom = shape(g).centroid.__geo_interface__

            #logging.info('{} {}'.format(geom, v))

        logging.info('reading all geoms {}'.format(time.process_time() - t3))
            #yield (v, geom)

if __name__ == '__main__':
    import argparse

    logging.getLogger().setLevel(logging.INFO)

    parser = argparse.ArgumentParser()
    parser.add_argument('--file_name', type=str)
    parser.add_argument('--src_crs', type=str, default='epsg:4326')
    parser.add_argument('--centroid_only', type=bool, default=False)
    args, _ = parser.parse_known_args()

    read_records(args.file_name, args.src_crs, args.centroid_only)


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd">

<chapter>
  <header>
    <copyright>
      <year>2004</year><year>2016</year>
      <holder>Ericsson AB. All Rights Reserved.</holder>
    </copyright>
    <legalnotice>
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.

    </legalnotice>

    <title>Common Test Release Notes History</title>
    <prepared>Peter Andersson</prepared>
    <responsible>Peter Andersson</responsible>
    <docno></docno>
    <approved></approved>
    <checked></checked>
    <date>07-12-01</date>
    <rev>A</rev>
    <file>notes_history.xml</file>
  </header>

  <section><title>common_test 1.3.0</title>
  </section>
</chapter>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _13_areaOfFigures
{
    class Program
    {
        static void Main(string[] args)
        {
            string figure = Console.ReadLine().ToLower();
            if (figure=="square")
            {
                double side = double.Parse(Console.ReadLine());
                double area =Math.Round( side * side, 3);
                Console.WriteLine(area);
            }
            else if (figure=="rectangle")
            {
                double side1 = double.Parse(Console.ReadLine());
                double side2 = double.Parse(Console.ReadLine());
                double area = Math.Round(side1 * side2, 3);
                Console.WriteLine(area);
            }
            else if (figure=="circle")
            {
                double radius = double.Parse(Console.ReadLine());
                double area = Math.Round(Math.PI*radius*radius,3);
                Console.WriteLine(area);

            }
            else if (figure=="triangle")
            {
                double side1 = double.Parse(Console.ReadLine());
                double side2 = double.Parse(Console.ReadLine());
                double area = Math.Round(side1*side2/2, 3);

                Console.WriteLine(area);

            }

        }
    }
}


text:
set -e  # exit script if any command returns an error
set -u  # exit the script if any variable is uninitialized

this_dir=$(dirname "${BASH_SOURCE[0]}")
cd "$this_dir/.."
src="$PWD"

gen_load="$src/devel/mps_generate_load.sh"
corpus="$HOME/pagespeed-loadtest-corpus"

start_apache_then_exit=0

# Check if we are asked for an external cache (e.g memcached or redis) but
# don't have a port configured first, as we need to re-launch ourselves using
# run_program_with_EXTCACHE.sh, so we don't want to mess up $@.
for argument in "$@"; do
  if [ "$argument" = "-memcached" -a -z "${MEMCACHED_PORT+x}" ]; then
    exec "$src/install/run_program_with_memcached.sh" \
        "$src/devel/mps_load_test.sh" "$@"
  elif [ "$argument" = "-redis" -a -z "${REDIS_PORT+x}" ]; then
    exec "$src/install/run_program_with_redis.sh" \
        "$src/devel/mps_load_test.sh" "$@"
  fi
done

if [[ $# -ge 1 && "$1" = "-start_apache_then_exit" ]]; then
  start_apache_then_exit=1
  shift
fi

custom_so=
if [[ $# -ge 2 && "$1" = "-custom_so" ]]; then
  custom_so=$2
  shift 2
fi

custom_so24=
if [[ $# -ge 2 && "$1" = "-custom_so24" ]]; then
  custom_so24=$2
  shift 2
fi

if [[ $# -ge 1 && "$1" = "-chrome" ]]; then
  export USER_AGENT_FLAG="--user_agent Chrome/47.0.2526.80"
  shift
elif [[ $# -ge 2 && "$1" = "-user_agent" ]]; then
  export USER_AGENT_FLAG="--user_agent $2"
  shift 2
else
  export USER_AGENT_FLAG=
fi

if [[ $# -ge 1 && "$1" = "-memcached" ]]; then
  echo "Using memcached on port $MEMCACHED_PORT"
  shift
  export MEMCACHED=1
  export REDIS=0
  cache_stat_prefix="memcache"
elif [[ $# -ge 1 && "$1" = "-redis" ]]; then
  echo Using redis on port "$REDIS_PORT"
  shift
  export MEMCACHED=0
  export REDIS=1
  cache_stat_prefix="redis"
else
  export MEMCACHED=0
  export REDIS=0
  cache_stat_prefix="file_cache_"
fi

if [[ $# -ge 1 && "$1" = "-ipro_preserve" ]]; then
  shift
  export IPRO_PRESERVE=1
  export EXTRA_URL_FLAGS=--ipro_preserve
else
  export IPRO_PRESERVE=0
  export EXTRA_URL_FLAGS=
fi

if [[ $# -ge 1 && "$1" = "-purging" ]]; then
  shift
  export PURGING=1
else
  export PURGING=0
fi

if [[ $# -ge 1 && "$1" = "-inline_unauthorized_resources" ]]; then
  shift
  export IUR=1
else
  export IUR=0
fi

if [[ $# -ge 1 && "$1" = "-ssl" ]]; then
  shift
  export EXTRA_FETCH_FLAGS=--ssl
else
  export EXTRA_FETCH_FLAGS=
fi

if [[ $# -ge 1 && "$1" = "-debug" ]]; then
  shift
  compile_mode="Debug"
else
  compile_mode="OptDebug"
fi

if [ $# -ge 2 ]; then
  echo "Unknown arguments: $@"
  exit 1
fi

if [ ! -d "$corpus" ] && [ $# -ne 1 ]; then
  echo "Invalid arguments: corpus required"
  exit 1
fi

if [ -d "$corpus" ] && [ $# -ne 0 ]; then
  echo "Warning: using already extracted corpus instead of $1"
fi

# If an 'su' password is required, then get it before going off and compiling
# stuff.
"$src/devel/turn_on_timewait_recyling.sh"

if [ -d /var/run/pagespeed/ ]; then
  rm -rf /var/run/pagespeed/*
else
  sudo mkdir -p /var/run/pagespeed
  sudo chown "$USER" /var/run/pagespeed
fi

# Only ssh (and warn user that they will need a password) if using a separate
# host for load generation.
cmd="$gen_load $EXTRA_URL_FLAGS $EXTRA_FETCH_FLAGS $USER_AGENT_FLAG"

APACHE_DEBUG_ROOT=${APACHE_DEBUG_ROOT:-$HOME/apache2}

echo Checking whether we have the corpus available.
if [ ! -d "$corpus" ]; then
  corpus_src="$1"
  echo "Copying corpus files from $corpus_src"
  mkdir -p "$corpus"
  cd "$corpus"
  tar xjf "$corpus_src"
fi

cd "$src/devel"

# Build a version of mod_pagespeed with all optimizations enabled, but with
# a build that includes DCHECKs.
make -j8 CONF=$compile_mode apache_trace_stress_test_server \
  DUMP_DIR="$corpus" \
  APACHE_DEBUG_ROOT="${APACHE_DEBUG_ROOT}" \
  MOD_PAGESPEED_CACHE=/var/run/pagespeed/cache

# If a custom .so got specified, install it.
if [[ -n "$custom_so" ]]; then
  install -c "$custom_so" "$APACHE_DEBUG_ROOT/modules/mod_pagespeed.so"
fi

if [[ -n "$custom_so24" ]]; then
  install -c "$custom_so24" "$APACHE_DEBUG_ROOT/modules/mod_pagespeed_ap24.so"
fi

# Restart apache for any hand-specified .so or alternative binary
if [[ -n "$custom_so" || -n "$custom_so24" ]]; then
  make apache_debug_stop
  make apache_debug_start
fi

if [[ "$start_apache_then_exit" = 1 ]]; then
  exit 0
fi

stop_crash_scraper="/tmp/stop_crash_scraper"
error_log="$APACHE_DEBUG_ROOT/logs/error_log"
rm -f "$stop_crash_scraper"

echo starting test ...
"$src/devel/scrape_error_log_for_crashes.sh" \
    "$error_log" "$stop_crash_scraper" &
echo "$cmd ..."
$cmd
touch "$stop_crash_scraper"

# Print some interesting statistics from the server
statsfile=/tmp/mps_load_test_stats.$$
wget -q -O $statsfile http://localhost:8080/mod_pagespeed_global_statistics
grep "$cache_stat_prefix" $statsfile | grep -v onchange=
grep shm $statsfile
grep dropped $statsfile
grep cache_batcher $statsfile
grep rewrite_cached_output_missed_deadline $statsfile
grep bytes_saved $statsfile
grep serf $statsfile
grep queued-fetch-count $statsfile
grep page_load_count $statsfile
grep 404_count $statsfile
grep file_cache_bytes_freed_in_cleanup $statsfile
grep file_cache_cleanups $statsfile
grep file_cache_write_errors $statsfile
grep image_webp_rewrites $statsfile
egrep "num_css|num_js" $statsfile
rm -f $statsfile

set +e
echo 'egrep "exit signal|CRASH" $error_log'
egrep "exit signal|CRASH" $error_log
if [ $? = 0 ]; then
  echo "*** $error_log has dangerous looking errors.  Please investigate."
  exit 1
else
  echo "No deaths reported in $error_log -- ship it."
fi

if [ "$MEMCACHED" = "1" -o "$REDIS" = "1" ]; then
  date
  echo -n Sleeping 5 seconds before killing external cache server to let
  echo -n outstanding writes quiesce...
  sleep 5
  echo "done"
fi


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.jaikh.movies.ui.MainActivity">

    <item
        android:id="@+id/action_popular"
        android:title="@string/action_popular"
        android:icon="@drawable/ic_whatshot_white_48dp"
        app:showAsAction="never" />
    <item
        android:id="@+id/action_most_rated"
        android:title="@string/action_most_rated"
        android:icon="@drawable/ic_plus_one_white_48dp"
        app:showAsAction="never" />
    <item
        android:id="@+id/action_favorite"
        android:title="@string/action_favorite"
        android:icon="@drawable/ic_star_white_48dp"
        app:showAsAction="never" />

</menu>


text:
using System;
using GalaSoft.MvvmLight.Command;
using Mg2.Models;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Input;
using System.Xml.Serialization;

namespace Mg2.ViewModels
{
    public class FiltersViewModel : Screen
    {
        private Filter _selectedFilter;

        public ObservableCollection<Filter> Filters { get; private set; }

        public ICommand AddCommand { get; set; }
        public ICommand RemoveCommand { get; set; }
        public ICommand CloseCommand { get; set; }

        public Filter SelectedFilter
        {
            get { return _selectedFilter; }
            set
            {
                _selectedFilter = value;
                RaisePropertyChanged(() => SelectedFilter);
            }
        }

        public FiltersViewModel(ObservableCollection<Filter> filters)
        {
            DisplayName = "Filters";
            Filters = filters;

            AddCommand = new RelayCommand(Add);
            RemoveCommand = new RelayCommand(Remove);
            CloseCommand = new RelayCommand(Close);
        }

        public void Add()
        {
            Filters.Add(new Filter("New filter", ""));
        }

        public void Remove()
        {
            Filters.Remove(SelectedFilter);
        }

        private void Close()
        {
            try
            {
                var path = Constants.AppDataPath + "Filters.xml";

                var writer = new XmlSerializer(typeof (ObservableCollection<Filter>), new XmlRootAttribute("Filters"));
                var file = new StreamWriter(path);
                writer.Serialize(file, Filters);
                file.Close();
            }
            catch
            {
                Console.WriteLine("Could not save filters");
            }

            TryClose();
        }
    }
}


text:
NS_ASSUME_NONNULL_BEGIN

@implementation PINFutureMap (FlatMap)

+ (PINFuture<id> *)flatMap:(PINFuture<id> *)sourceFuture
                   executor:(id<PINExecutor>)executor
                   transform:(PINFuture<id> *(^)(id fromValue))transform
{
    return [PINFuture withBlock:^(void (^resolve)(id), void (^reject)(NSError *)) {
        [sourceFuture executor:executor success:^(id value) {
            PINFuture<id> *newFuture = transform(value);
            NSString *reason = @"A flatMap block returned nil, but it must return a PINFuture.";
            NSAssert(newFuture != nil, reason);
            if (newFuture == nil) {
                NSError *error = [PINFutureError errorWithReason:reason];
                reject(error);
            } else {
                [newFuture executor:executor success:^(id value) {
                    resolve(value);
                } failure:^(NSError *error) {
                    reject(error);
                }];
            }
        } failure:^(NSError *error) {
            reject(error);
        }];
    }];
}

@end

NS_ASSUME_NONNULL_END


text:
from os import listdir
from os.path import isdir, isfile, join
from shutil import rmtree

from static_aid import config, make_pages, utils

def setup():
    utils.remove_file_or_dir(config.STAGING_DIR)

def test_make_pages():
    make_pages.main()
    assert isdir(config.STAGING_DIR), "{} must exist".format(config.STAGING_DIR)
    assert isfile(join(config.STAGING_DIR, '_config.yml')), "{} must exist".format(join(config.STAGING_DIR, '_config.yml'))
    assert isfile(join(config.STAGING_DIR, config.sitemap)), "{} must exist".format(join(config.STAGING_DIR, config.sitemap))
    for k, v in config.destinations.items():
        assert isdir(join(config.STAGING_DIR, k)), "{} must exist".format(join(config.STAGING_DIR, k))
        # some objects have an index.html file, others do not.
        expected = (len(listdir(join(config.DATA_DIR, v))) + 1
                    if k not in ['breadcrumbs', 'subjects', 'trees']
                    else len(listdir(join(config.DATA_DIR, v))))
        assert len(listdir(join(config.STAGING_DIR, k))) == expected, "The correct number of files should be generated"

def teardown():
    utils.remove_file_or_dir(config.STAGING_DIR)

# assert directories and counts for STAGING_DIR