text:
layout: post
title: "DNE 151 - Entrevista Thiago Avelino"
home-title: "Thiago Avelino"
type: "Entrevista"
cast: "dne151-prod.mp3"
cast-length: "49638911"
cast-time: "00:51:39"
description: "Thiago Avelino é CTO da empresa [Nuveo](https://nuveo.ai/en/), já trabalhou em diversos projetos, inclusive um projeto próprio de conteúdo adulto. Golang e Python são seus principais envolvimentos na comunidade. Avelino bateu um papo conosco sobre sua história e todas as empresas pelo que passou. Bora escutar?"
libsyn-image: "dne-151-capa.jpg"
lybsyn-id: "6451362"
sponsors: ["revelo", "alura", "crowd"]
participants:
  -
    name: Thiago Avelino
    twitter: avelino0
links:
  -
    name: "Thiago Avelino Github"
    url: "https://github.com/avelino"
  -
    name: "Thiago Avelino Medium"
    url: "https://medium.com/@avelino0"
  -
    name: "Nuveo"
    url: "https://nuveo.ai/en/"
scraps:
  -
    name: "Segunda, qual a primeira coisa que fazem?"
    url: "https://www.youtube.com/watch?v=5LJk8-myJ9o"
  -
    name: "Frontinsampa"
    url: "http://www.frontinsampa.com.br/"
  -
    name: "Frontincampinas (cupom DevNaEstrada)"
    url: "https://www.sympla.com.br/front-in-campinas__248102?d=DevNaEstrada"
  -
    name: "CapiConf Cupom com 20%"
    url: "https://www.sympla.com.br/capiconf-18-by-contabilizei__233871?d=DEVNAESTRADA"
  -
    name: "Brasilia Dev Festival"
    url: "https://www.brasiliadevfestival.com.br"
  -
    name: "BraziLJS OnTheRoad"
    url: "https://braziljs.org/eventos/on-the-road-sorocaba"

---

Thiago Avelino é CTO da empresa [Nuveo](https://nuveo.ai/en/), já trabalhou em diversos projetos, inclusive um projeto próprio de conteúdo adulto. Golang e Python são seus principais envolvimentos na comunidade. Avelino bateu um papo conosco sobre sua história e todas as empresas pelo que passou. Bora escutar?

---

{% include modules/post-extras.html data=page %}

    Segunda, qual a primeira coisa que fazem?


text:
<?php
/**
 * @author Jordi Llonch <llonch.jordi@gmail.com>
 * @date 17/08/12 23:34
 */

namespace JordiLlonch\Bundle\WebScrapperBundle\Extractor\Spiders;

use JordiLlonch\Bundle\WebScrapperBundle\Extractor\Parsers\Base as BaseParser;

abstract class Rss extends Base
{
    protected $feed;

    public function __construct()
    {
        parent::__construct();

        $this->feed = new \SimplePie();
        $this->feed->enable_cache(false);
    }
}

redpajama_set_name: RedPajamaGithub


text:
Everyone participating in the Datapolitan community—including, but not limited to the Datapolitan classes, Datapolitan seminars, and Datapolitan Slack channel—is required to agree to the following code of conduct. This includes all class attendees, speakers, meeting members, and observers.

Datapolitan will enforce this code during its classes and meetings, as well as any other engagements at which Datapolitan team members are present. We expect cooperation from everyone to ensure a safe, diverse, and welcoming environment.

## The Condensed Version
Datapolitan is dedicated to providing a harassment-free experience for everyone, regardless of gender, age, sexual orientation, disability, physical appearance, body size, race, religion (or lack thereof), or veteran status. We do not tolerate harassment of participants in any form.

Sexist, racist, discriminatory, or harassing language and imagery is not appropriate in the Datapolitan community, in person or online. Participants violating these rules may be sanctioned or expelled from Datapolitan classes, meetings, or other events, the Slack channel, and all future events without a refund or other compensation at the discretion of Datapolitan.

## The Less Condensed Version
Harassment includes offensive verbal comments related to gender, age, sexual orientation, disability, physical appearance, body size, race, religion, or veteran status; sexual images in public spaces; deliberate intimidation, stalking, following, harassing photography or recording; sustained disruption of talks or other events; inappropriate physical contact; and unwelcome sexual attention.

Exception: Discussion or images related to sex, pornography, discriminatory language, or similar is welcome if it meets all of the following criteria:

+ It is necessary to the topic of discussion and no alternative exists
+ It is presented in a respectful manner
+ Participants are respectfully given ample warning and opportunity to leave beforehand.

This exception specifically does not allow use of gratuitous sexual images as attention-getting devices or unnecessary examples.

Participants asked to stop any harassing behavior are required to comply immediately.

If a participant engages in any of the aforementioned behavior, Datapolitan may take any action they deem appropriate, from warning the offender to immediately expelling the offender with no refund.

## Reporting and Enforcement
If you are being harassed, notice that someone else is being harassed, or have any other concerns, please contact Richard Dunks immediately. If you can't or don't wish to speak in person, or prefer to talk privately or electronically, contact us at conduct@datapolitan.com or by direct message in Slack.

All reports will be handled in the strictest confidence.

Datapolitan leadership will be happy to help participants contact local law enforcement, provide escorts, or otherwise assist those experiencing harassment to feel safe for the duration of the class, meeting, or other Datapolitan-sponsored event.

This Code of Conduct is based on [the XOXO Festival Code of Conduct](http://blog.xoxofest.com/conduct)

Licensed under a [Creative Commons Attribution 3.0 Unported License.](https://creativecommons.org/licenses/by/3.0/us/)


text:
/* tslint:disable */
/* eslint-disable */

import { ReaderFragment } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type SeoProductsForCollections_descending_artworks = {
    readonly edges: ReadonlyArray<{
        readonly node: {
            readonly id: string;
            readonly availability: string | null;
            readonly listPrice: ({
                readonly __typename: "PriceRange";
                readonly minPrice: {
                    readonly major: number;
                    readonly currencyCode: string;
                } | null;
                readonly maxPrice: {
                    readonly major: number;
                    readonly currencyCode: string;
                } | null;
            } | {
                readonly __typename: "Money";
                readonly major: number;
                readonly currencyCode: string;
            } | {
                /*This will never be '%other', but we need some
                value in case none of the concrete values match.*/
                readonly __typename: "%other";
            }) | null;
        } | null;
    } | null> | null;
    readonly " $refType": "SeoProductsForCollections_descending_artworks";
};
export type SeoProductsForCollections_descending_artworks$data = SeoProductsForCollections_descending_artworks;
export type SeoProductsForCollections_descending_artworks$key = {
    readonly " $data"?: SeoProductsForCollections_descending_artworks$data;
    readonly " $fragmentRefs": FragmentRefs<"SeoProductsForCollections_descending_artworks">;
};

const node: ReaderFragment = (function(){
var v0 = [
  {
    "alias": null,
    "args": [
      {
        "kind": "Literal",
        "name": "convertTo",
        "value": "USD"
      }
    ],
    "kind": "ScalarField",
    "name": "major",
    "storageKey": "major(convertTo:\"USD\")"
  },
  {
    "alias": null,
    "args": null,
    "kind": "ScalarField",
    "name": "currencyCode",
    "storageKey": null
  }
];
return {
  "argumentDefinitions": [],
  "kind": "Fragment",
  "metadata": null,
  "name": "SeoProductsForCollections_descending_artworks",
  "selections": [
    {
      "alias": null,
      "args": null,
      "concreteType": "FilterArtworksEdge",
      "kind": "LinkedField",
      "name": "edges",
      "plural": true,
      "selections": [
        {
          "alias": null,
          "args": null,
          "concreteType": "Artwork",
          "kind": "LinkedField",
          "name": "node",
          "plural": false,
          "selections": [
            {
              "alias": null,
              "args": null,
              "kind": "ScalarField",
              "name": "id",
              "storageKey": null
            },
            {
              "alias": null,
              "args": null,
              "kind": "ScalarField",
              "name": "availability",
              "storageKey": null
            },
            {
              "alias": null,
              "args": null,
              "concreteType": null,
              "kind": "LinkedField",
              "name": "listPrice",
              "plural": false,
              "selections": [
                {
                  "alias": null,
                  "args": null,
                  "kind": "ScalarField",
                  "name": "__typename",
                  "storageKey": null
                },
                {
                  "kind": "InlineFragment",
                  "selections": [
                    {
                      "alias": null,
                      "args": null,
                      "concreteType": "Money",
                      "kind": "LinkedField",
                      "name": "minPrice",
                      "plural": false,
                      "selections": (v0/*: any*/),
                      "storageKey": null
                    },
                    {
                      "alias": null,
                      "args": null,
                      "concreteType": "Money",
                      "kind": "LinkedField",
                      "name": "maxPrice",
                      "plural": false,
                      "selections": (v0/*: any*/),
                      "storageKey": null
                    }
                  ],
                  "type": "PriceRange"
                },
                {
                  "kind": "InlineFragment",
                  "selections": (v0/*: any*/),
                  "type": "Money"
                }
              ],
              "storageKey": null
            }
          ],
          "storageKey": null
        }
      ],
      "storageKey": null
    }
  ],
  "type": "FilterArtworksConnection"
};
})();
(node as any).hash = '3ed2186b3a7931bc9115d9f936826ac2';
export default node;


text:
'use strict';

describe('handsontable-chart.arrayUtils', function() {

	var arrayUtils;

	beforeEach(function() {
		angular.module('ngHandsontable', []);
		angular.module('chart.js', []);
		module('handsontable-chart');

		inject(function(_arrayUtils_) {
			arrayUtils = _arrayUtils_;
		});
	});

	describe('Array utility methods', function() {
		it('should transpose array', function () {
			var array = [[1,2,5], [5,4,1], [7,9,2]];
			var expected = [[1,5,7], [2,4,9], [5,1,2]];
			expect(arrayUtils.transposeMatrix(array)).toEqual(expected);
		});
	});

});


text:
//snippet-sourcedescription:[UploadUserDocs.java demonstrates how to upload a document to Amazon Workdocs.]
//snippet-keyword:[AWS SDK for Java v2]
//snippet-service:[Amazon WorkDocs]

// snippet-start:[workdocs.java2.upload_user_doc.complete]

package com.example.workdocs;

// snippet-start:[workdocs.java2.upload_user_doc.import]
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.workdocs.WorkDocsClient;
import software.amazon.awssdk.services.workdocs.model.InitiateDocumentVersionUploadRequest;
import software.amazon.awssdk.services.workdocs.model.InitiateDocumentVersionUploadResponse;
import software.amazon.awssdk.services.workdocs.model.UploadMetadata;
import software.amazon.awssdk.services.workdocs.model.DescribeUsersResponse;
import software.amazon.awssdk.services.workdocs.model.User;
import software.amazon.awssdk.services.workdocs.model.DescribeUsersRequest;
import software.amazon.awssdk.services.workdocs.model.WorkDocsException;
import software.amazon.awssdk.services.workdocs.model.UpdateDocumentVersionRequest;
import software.amazon.awssdk.services.workdocs.model.DocumentVersionStatus;
// snippet-end:[workdocs.java2.upload_user_doc.import]

/**
 * Before running this Java V2 code example, set up your development environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class UploadUserDocs {

    public static void main(String[] args) {
    // Based on WorkDocs dev guide code at http://docs.aws.amazon.com/workdocs/latest/developerguide/upload-documents.html

        final String usage = "\n" +
            "Usage:\n" +
            "    <organizationId> <userEmail> <docName> <docPath> \n\n" +
            "Where:\n" +
            "    organizationId - Your organization Id value. You can obtain this value from the AWS Management Console. \n"+
            "    userEmail - A user email. \n"+
            "    docName - The name of the document (for example, book.pdf). \n"+
            "    docPath - The path where the document is located (for example, C:/AWS/book.pdf). \n";

        if (args.length != 4) {
            System.out.println(usage);
            System.exit(1);
        }

        String organizationId = args[0];
        String userEmail = args[1];
        String docName = args[2];
        String docPath = args[3];
        Region region = Region.US_WEST_2;
        WorkDocsClient workDocs = WorkDocsClient.builder()
            .region(region)
            .credentialsProvider(ProfileCredentialsProvider.create())
            .build();

        uploadDoc(workDocs, organizationId, userEmail, docName, docPath) ;
        workDocs.close();
    }

    // snippet-start:[workdocs.java2.upload_user_doc.main]
    public static void uploadDoc(WorkDocsClient workDocs, String orgId, String userEmail, String docName, String docPath) {

        String docId ;
        String versionId ;
        String uploadUrl ;
        int statusValue;
        Map<String, String> map = getDocInfo(workDocs, orgId, userEmail, docName);
        docId = map.get("doc_id");
        versionId = map.get("version_id");
        uploadUrl = map.get("upload_url");

        statusValue = startDocUpload(uploadUrl, docPath);
        if (statusValue != 200) {
            System.out.println("Error code uploading: " + statusValue);
        } else {
            System.out.println("Success uploading doc " + docName);
        }

        completeUpload(workDocs, docId, versionId);
    }

    private static Map<String, String> getDocInfo(WorkDocsClient workDocs, String orgId, String user, String doc) {

        String folderId = getUserFolder(workDocs, orgId, user);
        InitiateDocumentVersionUploadRequest request = InitiateDocumentVersionUploadRequest.builder()
            .parentFolderId(folderId)
            .name(doc)
            .contentType("application/octet-stream")
            .build();

        InitiateDocumentVersionUploadResponse result = workDocs.initiateDocumentVersionUpload(request);
        UploadMetadata uploadMetadata = result.uploadMetadata();
        Map<String, String> map = new HashMap<>();
        map.put("doc_id", result.metadata().id());
        map.put("version_id", result.metadata().latestVersionMetadata().id());
        map.put("upload_url", uploadMetadata.uploadUrl());

        return map;
    }

    private static String getUserFolder(WorkDocsClient workDocs, String orgId, String user) {
        List<User> wdUsers = new ArrayList<>();
        String marker = null;

        do {
            DescribeUsersResponse result;

            if(marker == null) {
                DescribeUsersRequest request = DescribeUsersRequest.builder()
                    .organizationId(orgId)
                    .query(user)
                    .build();
                result = workDocs.describeUsers(request);
            } else {
                DescribeUsersRequest request = DescribeUsersRequest.builder()
                    .organizationId(orgId)
                    .query(user)
                    .marker(marker)
                    .build();
                result = workDocs.describeUsers(request);
            }

            wdUsers.addAll(result.users());
            marker = result.marker();
        } while (marker != null);

        for (User wdUser : wdUsers) {
            return wdUser.rootFolderId();
        }

        return "";
    }

    private static int startDocUpload(String uploadUrl, String doc) {

        try {
            URL url = new URL(uploadUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("PUT");

            // Content-Type supplied here should match with the Content-Type set
            // in the InitiateDocumentVersionUpload request.
            connection.setRequestProperty("Content-Type","application/octet-stream");
            connection.setRequestProperty("x-amz-server-side-encryption", "AES256");
            File file = new File(doc);
            FileInputStream fileInputStream = new FileInputStream(file);
            OutputStream outputStream = connection.getOutputStream();
            IOUtils.copy(fileInputStream, outputStream);

            // Very misleading. Getting a 200 only means the call succeeded, not that the copy worked.
            return connection.getResponseCode();  // int where 200 == success

        } catch(WorkDocsException | ProtocolException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return -1;
    }

    private static void completeUpload(WorkDocsClient workDocs, String docId, String versionId) {
        UpdateDocumentVersionRequest request = UpdateDocumentVersionRequest.builder()
            .documentId(docId)
            .versionId(versionId)
            .versionStatus(DocumentVersionStatus.ACTIVE)
            .build();

        workDocs.updateDocumentVersion(request);
    }
    // snippet-end:[workdocs.java2.upload_user_doc.main]
}

// snippet-end:[workdocs.java2.upload_user_doc.complete]


text:
@class NSString, WCImageFullScreenWindow;

@interface WCImageFullScreanViewMgr : MMService <MMService, WCImageFullScreenWindowDelegate>
{
    WCImageFullScreenWindow *m_view;
    NSString *_nsFromVCName;
}

- (void).cxx_destruct;
- (void)onWindowAnimationHide;
- (void)onWindowAnimationWillHide;
- (_Bool)isWindowShown;
- (void)animationHideToLeft;
- (void)animationShowWithMediaDataArray:(id)arg1 originView:(id)arg2 index:(unsigned int)arg3;
- (void)animationShowWithHint:(id)arg1;
- (id)getWCImageFullScreenView;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SimpleDB.core.TableManagement;
using System.Xml.Linq;

namespace SimpleDB.core
{
    public class Column
    {
        public string columnName { get; private set; }
        public DataType dataType { get; private set; }
        public DataOptions[] dataOptions { get; private set; }
        public string Optional;
        public Table parentTable;
        public ColumnLine columnLine { get; private set; }

        private XElement xElement;
        //private List<Reference> References = new List<Reference>();
        private Reference reference;

        public Column(string columnName, DataType dataType, DataOptions[] dataOptions, XElement element, Table parent)
        {
            this.columnName = columnName;
            this.dataType = dataType;
            this.dataOptions = dataOptions;
            this.xElement = element;
            this.parentTable = parent;

            columnLine = new ColumnLine();
        }

        public bool setOptional(string param)
        {
            if (xElement.Parent == null) return false;
            XElement EntityElement = xElement.Parent;

            try
            {
                EntityElement.Elements().Where(el => el.Attribute("Name").Value == columnName).First().Attribute("Optional").Value = param;
            }
            catch {
                EntityElement.Elements().Where(el => el.Attribute("Name").Value == columnName).First().Add(new XAttribute("Optional", param));
            }

            Optional = param;
            return true;
        }

        public string getOptional()
        {
            return Optional;
        }

        public bool EditName(string newName)
        {
            if (xElement.Parent == null) return false;
            string oldName = columnName;
            XElement EntityElement = xElement.Parent;
            if (EntityElement.Elements().Where(el => el.Attribute("Name").Value == newName).Count() >= 1) return false;

            xElement.Attribute("Name").Value = newName;
            columnName = newName;

            if (reference != null) ReferenceHelper.editName(reference, oldName, newName);

            return true;
        }

        public void EditDataType(DataType newDataType)
        {
            xElement.Attribute("DataType").Value = newDataType.ToString();
            dataType = newDataType;
        }

        //Sprawdzic popawnosc dzialania
        public bool RemoveDataOption(DataOptions dataOption)
        {
            var xAttribute = xElement.Attributes().First(attribute => attribute.Name == dataOption.ToString());
            if (xAttribute == null) return false;

            dataOptions.ToList().Remove(dataOption);
            xAttribute.Remove();
            return true;
        }

        public void Remove()
        {
            xElement.Remove();
        }

        public void RemoveReference()
        {
            foreach(DataOptions option in dataOptions)
            {
                if(option == DataOptions.FOREIGN_KEY)
                {
                    reference.Remove();
                    RemoveDataOption(DataOptions.FOREIGN_KEY);
                    TableList.getTableList().getTable(reference.getTableName()).getColumn(reference.getColumnName()).reference.Remove();
                    TableList.getTableList().getTable(reference.getTableName()).getColumn(reference.getColumnName()).RemoveDataOption(DataOptions.FOREIGN_KEY);
                }
            }
        }

        public bool MoveUp()
        {
            if (xElement.Parent == null) return false;
            XElement EntityElement = xElement.Parent;

            if (EntityElement.Elements().ToList<XElement>()[0].Attribute("Name").Value == columnName) return false;
            XElement elementToMove;

            try
            {
                elementToMove = EntityElement.Elements().First(el => el.Attribute("Name").Value == columnName);
            }
            catch
            {
                return false;
            }

            int count = elementToMove.ElementsBeforeSelf().Count();
            elementToMove.Remove();

            EntityElement.Elements().ToList<XElement>()[count - 1].AddBeforeSelf(elementToMove);

            var index = parentTable.getColumns().ToList<Column>().IndexOf(this);

            columnLine.SwapLine(parentTable.getColumns().ToList<Column>()[index - 1].columnLine);
            //columnLine.MoveUp();

            return true;

        }

        public bool addRelationship(Table targetTable, string columnName)
        {
            try
            {
                Column referenceColumn = targetTable.getColumn(columnName);
                addReferenceElement(targetTable.tableName, columnName);

                targetTable.getColumn(columnName).addReferenceElement(parentTable.tableName, this.columnName);
                //referenceColumn.reference.ForeigenReference = this.reference;
               // this.reference = referenceColumn.reference;

                return true;
            }
            catch
            {
                return false;
            }
        }

        private void addReferenceElement(string tableName, string columnName)
        {
            if (xElement.Element("Reference") == null)
                xElement.Add(new XElement("Reference"));

            xElement.Element("Reference").Add(new XAttribute("Table",tableName), new XAttribute("Column",columnName));

            reference = new Reference(xElement.Element("Reference"), this);
            TableList.getTableList().addReferencePrefix(tableName);
            parentTable.ReferenceColumn.Add(columnName);
        }

        internal void InitializeReference()
        {
            try
            {
                reference = new Reference(xElement.Element("Reference"), this);
                parentTable.ReferenceColumn.Add(columnName);
            }
            catch
            {
                return;
            }

        }

        public bool MoveDown()
        {
            if (xElement.Parent == null) return false;
            XElement EntityElement = xElement.Parent;

            XElement elementToMove;
            try
            {
                elementToMove = EntityElement.Elements().First(el => el.Attribute("Name").Value == columnName);

                var index = parentTable.getColumns().ToList<Column>().IndexOf(this);
                columnLine.SwapLine(parentTable.getColumns().ToList<Column>()[index + 1].columnLine);
            }
            catch
            {
                return false;
            }

            if (elementToMove.ElementsAfterSelf().Count() == 0) return false;

            int count = elementToMove.ElementsBeforeSelf().Count();

            elementToMove.Remove();

            EntityElement.Elements().ToList<XElement>()[count].AddAfterSelf(elementToMove);

            return true;
        }

        public void addData(object data)
        {
            if (!checkDataType(data)) return;

           // if(dataType == DataType.NUMBER)

        }

        private bool checkDataType(object data)
        {
            if(dataType == DataType.NUMBER)
            {
                if (dataType.GetType() == typeof(Int32)) return true;
                return false;
            }

            if (dataType.GetType() == typeof(string)) return true;

            return false;
        }

        internal Reference getReference()
        {
            return reference;
        }

        public bool hasReference()
        {
            if (reference != null) return true;
            return false;
        }

    }
}


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

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.flowable.cmmn.editor.constants.CmmnStencilConstants;
import org.flowable.cmmn.editor.json.converter.CmmnJsonConverter.CmmnModelIdHelper;
import org.flowable.cmmn.editor.json.converter.util.ListenerConverterUtil;
import org.flowable.cmmn.editor.json.model.CmmnModelInfo;
import org.flowable.cmmn.model.BaseElement;
import org.flowable.cmmn.model.CaseElement;
import org.flowable.cmmn.model.CmmnModel;
import org.flowable.cmmn.model.GraphicInfo;
import org.flowable.cmmn.model.PlanItem;
import org.flowable.cmmn.model.Stage;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * @author Tijs Rademakers
 * @author Joram Barrez
 */
public class StageJsonConverter extends BaseCmmnJsonConverter implements FormAwareConverter, FormKeyAwareConverter,
        DecisionTableAwareConverter, DecisionTableKeyAwareConverter, CaseModelAwareConverter, ProcessModelAwareConverter {

    protected Map<String, String> formMap;
    protected Map<String, CmmnModelInfo> formKeyMap;
    protected Map<String, String> decisionTableMap;
    protected Map<String, CmmnModelInfo> decisionTableKeyMap;
    protected Map<String, String> caseModelMap;
    protected Map<String, String> processModelMap;

    public static void fillTypes(Map<String, Class<? extends BaseCmmnJsonConverter>> convertersToCmmnMap,
            Map<Class<? extends BaseElement>, Class<? extends BaseCmmnJsonConverter>> convertersToJsonMap) {

        fillJsonTypes(convertersToCmmnMap);
        fillCmmnTypes(convertersToJsonMap);
    }

    public static void fillJsonTypes(Map<String, Class<? extends BaseCmmnJsonConverter>> convertersToCmmnMap) {
        convertersToCmmnMap.put(STENCIL_STAGE, StageJsonConverter.class);
    }

    public static void fillCmmnTypes(Map<Class<? extends BaseElement>, Class<? extends BaseCmmnJsonConverter>> convertersToJsonMap) {
        convertersToJsonMap.put(Stage.class, StageJsonConverter.class);
    }

    @Override
    protected String getStencilId(BaseElement baseElement) {
        return STENCIL_STAGE;
    }

    @Override
    protected void convertElementToJson(ObjectNode elementNode, ObjectNode propertiesNode, ActivityProcessor processor, BaseElement baseElement, CmmnModel cmmnModel) {
        PlanItem planItem = (PlanItem) baseElement;
        Stage stage = (Stage) planItem.getPlanItemDefinition();

        if (stage.getDisplayOrder() != null) {
            propertiesNode.put(PROPERTY_DISPLAY_ORDER, stage.getDisplayOrder());
        }
        if (stage.isIncludeInStageOverview())  {
            propertiesNode.put(PROPERTY_INCLUDE_IN_STAGE_OVERVIEW, true);
        }

        GraphicInfo graphicInfo = cmmnModel.getGraphicInfo(planItem.getId());
        ArrayNode subProcessShapesArrayNode = objectMapper.createArrayNode();

        processor.processPlanItems(stage, cmmnModel, subProcessShapesArrayNode, formKeyMap, decisionTableKeyMap, graphicInfo.getX(), graphicInfo.getY());

        elementNode.set("childShapes", subProcessShapesArrayNode);

        ListenerConverterUtil.convertLifecycleListenersToJson(objectMapper, propertiesNode, stage);
    }

    @Override
    protected CaseElement convertJsonToElement(JsonNode elementNode, JsonNode modelNode, ActivityProcessor processor,
                    BaseElement parentElement, Map<String, JsonNode> shapeMap, CmmnModel cmmnModel, CmmnModelIdHelper cmmnModelIdHelper) {

        Stage stage = new Stage();
        stage.setId(CmmnJsonConverterUtil.getElementId(elementNode));

        stage.setAutoComplete(CmmnJsonConverterUtil.getPropertyValueAsBoolean(PROPERTY_IS_AUTOCOMPLETE, elementNode));
        String autoCompleteCondition = CmmnJsonConverterUtil.getPropertyValueAsString(PROPERTY_AUTOCOMPLETE_CONDITION, elementNode);
        if (StringUtils.isNotEmpty(autoCompleteCondition)) {
            stage.setAutoCompleteCondition(autoCompleteCondition);
        }

        stage.setDisplayOrder(CmmnJsonConverterUtil
            .getPropertyValueAsInteger(CmmnStencilConstants.PROPERTY_DISPLAY_ORDER, elementNode));
        stage.setIncludeInStageOverview(CmmnJsonConverterUtil
            .getPropertyValueAsBoolean(CmmnStencilConstants.PROPERTY_INCLUDE_IN_STAGE_OVERVIEW, elementNode, true));

        JsonNode childShapesArray = elementNode.get(EDITOR_CHILD_SHAPES);
        processor.processJsonElements(childShapesArray, modelNode, stage, shapeMap, formMap, decisionTableMap,
                        caseModelMap, processModelMap, cmmnModel, cmmnModelIdHelper);

        Stage parentStage = (Stage) parentElement;
        stage.setParent(parentStage);

        ListenerConverterUtil.convertJsonToLifeCycleListeners(elementNode, stage);

        return stage;
    }

    @Override
    public void setFormMap(Map<String, String> formMap) {
        this.formMap = formMap;
    }

    @Override
    public void setFormKeyMap(Map<String, CmmnModelInfo> formKeyMap) {
        this.formKeyMap = formKeyMap;
    }

    @Override
    public void setDecisionTableMap(Map<String, String> decisionTableMap) {
        this.decisionTableMap = decisionTableMap;
    }

    @Override
    public void setDecisionTableKeyMap(Map<String, CmmnModelInfo> decisionTableKeyMap) {
        this.decisionTableKeyMap = decisionTableKeyMap;
    }

    @Override
    public void setCaseModelMap(Map<String, String> caseModelMap) {
        this.caseModelMap = caseModelMap;
    }

    @Override
    public void setProcessModelMap(Map<String, String> processModelMap) {
        this.processModelMap = processModelMap;
    }
}


text:
package com.jamal.springdemo.validation.test;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Documented
@Retention(RUNTIME)
@Target(ElementType.TYPE)
@Constraint(validatedBy = FieldsVerificationValidator.class)
public @interface FieldsVerification {

	String message() default "* Fields values do not match";
	String field();
    String fieldMatch();

	Class<?>[] groups() default { };

	Class<? extends Payload>[] payload() default { };

	@Retention(RUNTIME)
	@Target(ElementType.TYPE)
    @interface List {
		FieldsVerification[] value();
    }
}


text:
<?php

namespace Yeah\Fw\Logger;

/**
 * Describes a logger-aware instance per PSR-3 standard recommendation
 * @link https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md
 */
interface LoggerAwareInterface
{
    /**
     * Sets a logger instance on the object
     *
     * @param LoggerInterface $logger
     * @return null
     */
    public function setLogger(LoggerInterface $logger);
}


text:
.class public abstract Lorg/apache/harmony/xml/dom/CharacterDataImpl;
.super Lorg/apache/harmony/xml/dom/LeafNodeImpl;
.source "CharacterDataImpl.java"

# interfaces
.implements Lorg/w3c/dom/CharacterData;

# instance fields
.field protected buffer:Ljava/lang/StringBuffer;

# direct methods
.method constructor <init>(Lorg/apache/harmony/xml/dom/DocumentImpl;Ljava/lang/String;)V
    .locals 0
    .param p1, "document"    # Lorg/apache/harmony/xml/dom/DocumentImpl;
    .param p2, "data"    # Ljava/lang/String;

    .prologue
    .line 38
    invoke-direct {p0, p1}, Lorg/apache/harmony/xml/dom/LeafNodeImpl;-><init>(Lorg/apache/harmony/xml/dom/DocumentImpl;)V

    .line 39
    invoke-virtual {p0, p2}, Lorg/apache/harmony/xml/dom/CharacterDataImpl;->setData(Ljava/lang/String;)V

    .line 40
    return-void
.end method

# virtual methods
.method public appendData(Ljava/lang/String;)V
    .locals 1
    .param p1, "arg"    # Ljava/lang/String;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Lorg/w3c/dom/DOMException;
        }
    .end annotation

    .prologue
    .line 43
    iget-object v0, p0, Lorg/apache/harmony/xml/dom/CharacterDataImpl;->buffer:Ljava/lang/StringBuffer;

    invoke-virtual {v0, p1}, Ljava/lang/StringBuffer;->append(Ljava/lang/String;)Ljava/lang/StringBuffer;

    .line 44
    return-void
.end method

.method public appendDataTo(Ljava/lang/StringBuilder;)V
    .locals 1
    .param p1, "stringBuilder"    # Ljava/lang/StringBuilder;

    .prologue
    .line 58
    iget-object v0, p0, Lorg/apache/harmony/xml/dom/CharacterDataImpl;->buffer:Ljava/lang/StringBuffer;

    invoke-virtual {p1, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/StringBuffer;)Ljava/lang/StringBuilder;

    .line 59
    return-void
.end method

.method public deleteData(II)V
    .locals 2
    .param p1, "offset"    # I
    .param p2, "count"    # I
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Lorg/w3c/dom/DOMException;
        }
    .end annotation

    .prologue
    .line 47
    iget-object v0, p0, Lorg/apache/harmony/xml/dom/CharacterDataImpl;->buffer:Ljava/lang/StringBuffer;

    add-int v1, p1, p2

    invoke-virtual {v0, p1, v1}, Ljava/lang/StringBuffer;->delete(II)Ljava/lang/StringBuffer;

    .line 48
    return-void
.end method

.method public getData()Ljava/lang/String;
    .locals 1
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Lorg/w3c/dom/DOMException;
        }
    .end annotation

    .prologue
    .line 51
    iget-object v0, p0, Lorg/apache/harmony/xml/dom/CharacterDataImpl;->buffer:Ljava/lang/StringBuffer;

    invoke-virtual {v0}, Ljava/lang/StringBuffer;->toString()Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method

.method public getLength()I
    .locals 1

    .prologue
    .line 62
    iget-object v0, p0, Lorg/apache/harmony/xml/dom/CharacterDataImpl;->buffer:Ljava/lang/StringBuffer;

    invoke-virtual {v0}, Ljava/lang/StringBuffer;->length()I

    move-result v0

    return v0
.end method

.method public getNodeValue()Ljava/lang/String;
    .locals 1

    .prologue
    .line 67
    invoke-virtual {p0}, Lorg/apache/harmony/xml/dom/CharacterDataImpl;->getData()Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method

.method public insertData(ILjava/lang/String;)V
    .locals 4
    .param p1, "offset"    # I
    .param p2, "arg"    # Ljava/lang/String;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Lorg/w3c/dom/DOMException;
        }
    .end annotation

    .prologue
    .line 72
    :try_start_0
    iget-object v1, p0, Lorg/apache/harmony/xml/dom/CharacterDataImpl;->buffer:Ljava/lang/StringBuffer;

    invoke-virtual {v1, p1, p2}, Ljava/lang/StringBuffer;->insert(ILjava/lang/String;)Ljava/lang/StringBuffer;
    :try_end_0
    .catch Ljava/lang/ArrayIndexOutOfBoundsException; {:try_start_0 .. :try_end_0} :catch_0

    .line 76
    return-void

    .line 73
    :catch_0
    move-exception v0

    .line 74
    .local v0, "ex":Ljava/lang/ArrayIndexOutOfBoundsException;
    new-instance v1, Lorg/w3c/dom/DOMException;

    const/4 v2, 0x1

    const/4 v3, 0x0

    invoke-direct {v1, v2, v3}, Lorg/w3c/dom/DOMException;-><init>(SLjava/lang/String;)V

    throw v1
.end method

.method public replaceData(IILjava/lang/String;)V
    .locals 4
    .param p1, "offset"    # I
    .param p2, "count"    # I
    .param p3, "arg"    # Ljava/lang/String;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Lorg/w3c/dom/DOMException;
        }
    .end annotation

    .prologue
    .line 81
    :try_start_0
    iget-object v1, p0, Lorg/apache/harmony/xml/dom/CharacterDataImpl;->buffer:Ljava/lang/StringBuffer;

    add-int v2, p1, p2

    invoke-virtual {v1, p1, v2, p3}, Ljava/lang/StringBuffer;->replace(IILjava/lang/String;)Ljava/lang/StringBuffer;
    :try_end_0
    .catch Ljava/lang/ArrayIndexOutOfBoundsException; {:try_start_0 .. :try_end_0} :catch_0

    .line 85
    return-void

    .line 82
    :catch_0
    move-exception v0

    .line 83
    .local v0, "ex":Ljava/lang/ArrayIndexOutOfBoundsException;
    new-instance v1, Lorg/w3c/dom/DOMException;

    const/4 v2, 0x1

    const/4 v3, 0x0

    invoke-direct {v1, v2, v3}, Lorg/w3c/dom/DOMException;-><init>(SLjava/lang/String;)V

    throw v1
.end method

.method public setData(Ljava/lang/String;)V
    .locals 1
    .param p1, "data"    # Ljava/lang/String;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Lorg/w3c/dom/DOMException;
        }
    .end annotation

    .prologue
    .line 88
    new-instance v0, Ljava/lang/StringBuffer;

    invoke-direct {v0, p1}, Ljava/lang/StringBuffer;-><init>(Ljava/lang/String;)V

    iput-object v0, p0, Lorg/apache/harmony/xml/dom/CharacterDataImpl;->buffer:Ljava/lang/StringBuffer;

    .line 89
    return-void
.end method

.method public substringData(II)Ljava/lang/String;
    .locals 4
    .param p1, "offset"    # I
    .param p2, "count"    # I
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Lorg/w3c/dom/DOMException;
        }
    .end annotation

    .prologue
    .line 93
    :try_start_0
    iget-object v1, p0, Lorg/apache/harmony/xml/dom/CharacterDataImpl;->buffer:Ljava/lang/StringBuffer;

    add-int v2, p1, p2

    invoke-virtual {v1, p1, v2}, Ljava/lang/StringBuffer;->substring(II)Ljava/lang/String;
    :try_end_0
    .catch Ljava/lang/ArrayIndexOutOfBoundsException; {:try_start_0 .. :try_end_0} :catch_0

    move-result-object v1

    return-object v1

    .line 94
    :catch_0
    move-exception v0

    .line 95
    .local v0, "ex":Ljava/lang/ArrayIndexOutOfBoundsException;
    new-instance v1, Lorg/w3c/dom/DOMException;

    const/4 v2, 0x1

    const/4 v3, 0x0

    invoke-direct {v1, v2, v3}, Lorg/w3c/dom/DOMException;-><init>(SLjava/lang/String;)V

    throw v1
.end method


text:
package org.qsardb.editor.importer;

import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import org.qsardb.conversion.table.Mapping;
import org.qsardb.conversion.table.Table;
import org.qsardb.conversion.table.Table2Qdb;
import org.qsardb.conversion.table.TableSetup;
import org.qsardb.editor.common.QdbContext;
import org.qsardb.editor.common.Utils;
import org.qsardb.editor.events.ImportEvent;
import org.qsardb.model.Qdb;

public class PerformImportAction extends AbstractAction {

	private final QdbContext qdbContext;
	private final MappingRulesModel rulesModel;
	private final Table dataTable;

	public PerformImportAction(QdbContext context, Table table, MappingRulesModel model) {
		super("Import");
		qdbContext = context;
		dataTable = table;
		rulesModel = model;
		setEnabled(rulesModel.getIdMappingRule() != null);

		rulesModel.addTableModelListener(new TableModelListener() {
			@Override
			public void tableChanged(TableModelEvent e) {
				setEnabled(rulesModel.getIdMappingRule() != null);
			}
		});
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		try {
			importTable();
		} catch (IllegalArgumentException ex) {
			Utils.showExceptionPanel(ex.getMessage(), ex);
		}
	}

	public void importTable() {
		MappingRule idRule = rulesModel.getIdMappingRule();
		try {
			for (int i=0; i<rulesModel.getRowCount(); i++) {
				MappingRule rule = rulesModel.getMappingRule(i);
				if (rule.getMapTo() == MapTo.IGNORE || idRule.equals(rule)) {
					continue;
				}

				importColumn(idRule, rule);
			}
		} finally {
			qdbContext.fire(new ImportEvent(this));
		}
	}

	private void importColumn(MappingRule idRule, MappingRule rule) {
		TableSetup setup = new TableSetup();
		if (rulesModel.hasHeader()) {
			setup.setIgnored("1");
		}

		Mapping idMapping = idRule.getMapTo().createMapping(null);
		setup.addMapping(idRule.getSourceColumnId(), idMapping);

		Mapping mapping = rule.getMapTo().createMapping(rule.getArgument());
		setup.addMapping(rule.getSourceColumnId(), mapping);

		try {
			Qdb qdb = qdbContext.getQdb();
			Table2Qdb.convert(qdb, dataTable, setup);
		} catch (Exception ex) {
			String msg = "Error mapping column "+rule.getSourceColumnHeading()+ " to " + rule.getMapTo() + ": " + ex.getMessage();
			throw new IllegalArgumentException(msg, ex);
		}
	}
}


text:
<?php

namespace luya\cms\frontend\blocks;

use luya\cms\frontend\Module;
use luya\cms\frontend\blockgroups\TextGroup;
use luya\cms\base\PhpBlock;

/**
 * WYSIWYG Block with ng-wig.
 *
 * @author Basil Suter <basil@nadar.io>
 */
final class WysiwygBlock extends PhpBlock
{
    /**
     * @inheritdoc
     */
    public $module = 'cms';

    /**
     * @inheritDoc
     */
    public $cacheEnabled = true;

    /**
     * @inheritDoc
     */
    public function name()
    {
        return Module::t('block_wysiwyg_name');
    }

    /**
     * @inheritDoc
     */
    public function blockGroup()
    {
        return TextGroup::className();
    }

    /**
     * @inheritDoc
     */
    public function icon()
    {
        return 'format_color_text';
    }

    /**
     * @inheritDoc
     */
    public function config()
    {
        return [
            'vars' => [
                ['var' => 'content', 'label' => Module::t('block_wysiwyg_content_label'), 'type' => self::TYPE_WYSIWYG],
            ],
        ];
    }

    /**
     * @inheritDoc
     */
    public function admin()
    {
        return '{% if vars.content is empty %}' . Module::t('block_wysiwyg_no_content') . '{% else %}{{ vars.content }}{% endif %}';
    }
}


text:
package org.theospi.portfolio.admin.service;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.theospi.portfolio.admin.intf.SakaiIntegrationPlugin;

import java.util.List;

abstract public class IntegrationPluginBase implements SakaiIntegrationPlugin {
   protected final transient Log logger = LogFactory.getLog(getClass());

   private String title;
   private String description;
   private List potentialIntegrations;

   public String getDescription() {
      return description;
   }

   public void setDescription(String description) {
      this.description = description;
   }

   public List getPotentialIntegrations() {
      return potentialIntegrations;
   }

   public void setPotentialIntegrations(List potentialIntegrations) {
      this.potentialIntegrations = potentialIntegrations;
   }

   public String getTitle() {
      return title;
   }

   public void setTitle(String title) {
      this.title = title;
   }

}


text:
function setTimeout(callback, ms) {

    return NodeKitTimer.setTimeoutSync(callback, ms)
}

function setInterval(callback, ms) {

    return NodeKitTimer.setIntervalSync(callback, ms)
}

function clearTimeout(indentifier) {

    NodeKitTimer.clearTimeoutSync(indentifier)
}


text:
using System;
using System.Globalization;
using System.Runtime.Serialization;
using Bio.Properties;

namespace Bio.IO.AppliedBiosystems.Exceptions
{
    /// <summary>
    /// File version is invalid.
    /// </summary>
    public class InvalidFileVersionException : Exception
    {
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="expected"></param>
        /// <param name="actual"></param>
        public InvalidFileVersionException(int expected, int actual) :
            base(string.Format(CultureInfo.InvariantCulture, Resource.Ab1InvalidFileVersionExceptionFormat, expected, actual))
        {
        }

        /// <summary>
        /// Empty constructor
        /// </summary>
        public InvalidFileVersionException()
        {
        }

        /// <summary>
        /// Constructor with message.
        /// </summary>
        /// <param name="message"></param>
        public InvalidFileVersionException(string message)
            : base(message)
        {
        }

        /// <summary>
        /// Constructor with message and inner exception.
        /// </summary>
        /// <param name="message"></param>
        /// <param name="innerException"></param>
        public InvalidFileVersionException(string message, Exception innerException)
            : base(message, innerException)
        {
        }
    }
}


text:
require 'test/unit'

require 'targeting/add_campaign_targeting_criteria'
require 'targeting/add_demographic_targeting_criteria'
require 'targeting/get_campaign_targeting_criteria'
require 'targeting/get_targetable_languages_and_carriers'
require 'targeting/lookup_location'

class TestTargetingV201302 < Test::Unit::TestCase
  def setup
    @logger = Logger.new(STDOUT)
    @logger.level = Logger::ERROR
    @adwords = AdwordsApi::Api.new
    @adwords.logger = @logger
    @utils = UtilsV201302.new(@adwords)
  end

  def test_add_campaign_targeting_criteria
    campaign = @utils.get_campaign()
    assert_not_nil(campaign)
    assert_not_nil(campaign[:id])
    add_campaign_targeting_criteria(campaign[:id])
  end

  def test_add_demographic_targeting_criteria
    ad_group = @utils.get_ad_group()
    assert_not_nil(ad_group)
    assert_not_nil(ad_group[:id])
    add_demographic_targeting_criteria(ad_group[:id])
  end

  def test_get_campaign_targeting_criteria
    campaign = @utils.get_campaign()
    assert_not_nil(campaign)
    assert_not_nil(campaign[:id])
    get_campaign_targeting_criteria(campaign[:id])
  end

  def test_get_targetable_languages_and_carriers
    get_targetable_languages_and_carriers()
  end

  def test_lookup_location
    lookup_location()
  end
end


text:
namespace ProductShop.Data.Migrations
{
    using Microsoft.EntityFrameworkCore.Metadata;
    using Microsoft.EntityFrameworkCore.Migrations;

    public partial class InitialDb : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "Categories",
                columns: table => new
                {
                    CategoryId = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    Name = table.Column<string>(maxLength: 15, nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Categories", x => x.CategoryId);
                });

            migrationBuilder.CreateTable(
                name: "Users",
                columns: table => new
                {
                    UserId = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    Age = table.Column<int>(nullable: true),
                    FirstName = table.Column<string>(nullable: true),
                    LastName = table.Column<string>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Users", x => x.UserId);
                });

            migrationBuilder.CreateTable(
                name: "Products",
                columns: table => new
                {
                    ProductId = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    BuyerId = table.Column<int>(nullable: true),
                    Name = table.Column<string>(nullable: false),
                    Price = table.Column<decimal>(nullable: false),
                    SellerId = table.Column<int>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Products", x => x.ProductId);
                    table.ForeignKey(
                        name: "FK_Products_Users_BuyerId",
                        column: x => x.BuyerId,
                        principalTable: "Users",
                        principalColumn: "UserId",
                        onDelete: ReferentialAction.SetNull);
                    table.ForeignKey(
                        name: "FK_Products_Users_SellerId",
                        column: x => x.SellerId,
                        principalTable: "Users",
                        principalColumn: "UserId",
                        onDelete: ReferentialAction.Restrict);
                });

            migrationBuilder.CreateTable(
                name: "CategoryProduct",
                columns: table => new
                {
                    CategoryId = table.Column<int>(nullable: false),
                    ProductId = table.Column<int>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_CategoryProduct", x => new { x.CategoryId, x.ProductId });
                    table.ForeignKey(
                        name: "FK_CategoryProduct_Categories_CategoryId",
                        column: x => x.CategoryId,
                        principalTable: "Categories",
                        principalColumn: "CategoryId",
                        onDelete: ReferentialAction.Cascade);
                    table.ForeignKey(
                        name: "FK_CategoryProduct_Products_ProductId",
                        column: x => x.ProductId,
                        principalTable: "Products",
                        principalColumn: "ProductId",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateIndex(
                name: "IX_CategoryProduct_ProductId",
                table: "CategoryProduct",
                column: "ProductId");

            migrationBuilder.CreateIndex(
                name: "IX_Products_BuyerId",
                table: "Products",
                column: "BuyerId");

            migrationBuilder.CreateIndex(
                name: "IX_Products_SellerId",
                table: "Products",
                column: "SellerId");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "CategoryProduct");

            migrationBuilder.DropTable(
                name: "Categories");

            migrationBuilder.DropTable(
                name: "Products");

            migrationBuilder.DropTable(
                name: "Users");
        }
    }
}


text:
package com.dranawhite.spring.event;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author liangyq 2018/3/19
 */
public class EventPro {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MyEventConfig.class);
		ctx.publishEvent(new MyEvent("EventPro", "HelloWorld"));
		ctx.close();
	}

}


text:
using System;

namespace Yalf
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)]
	public class NoLogAttribute : Attribute
	{
        public NoLogAttribute() { }
	}
}


text:
cask 'daisydisk' do
  if MacOS.version <= :snow_leopard
    version '2.1.2'
    sha256 'd0a606dee19e524d6fa7b79fd48b3b9865123ca4126fb8805f8e96c317b57b31'
    url "https://www.daisydiskapp.com/downloads/DaisyDisk_#{version.dots_to_underscores}.dmg"
  elsif MacOS.version <= :mavericks
    version '3.0.3.1'
    sha256 'fe2aa86f2ea8a1f0c4791857a5b7991ecad295b5b969849bb7b15a890ab54b86'
    url "https://www.daisydiskapp.com/downloads/DaisyDisk_#{version.dots_to_underscores}.zip"
  else
    version '4.6.2'
    sha256 'c3c3a7c6fea1c9ee72b5b7f8e6257b281aa1530f2219e33705af6d7d37d4e271'
    url 'https://www.daisydiskapp.com/downloads/DaisyDisk.zip'
    appcast 'https://daisydiskapp.com/downloads/appcastReleaseNotes.php?appEdition=Standard&osVersion=10.13'
  end

  name 'DaisyDisk'
  homepage 'https://daisydiskapp.com/'

  app 'DaisyDisk.app'

  uninstall delete:    '/Library/PrivilegedHelperTools/com.daisydiskapp.DaisyDiskAdminHelper',
            launchctl: 'com.daisydiskapp.DaisyDiskAdminHelper'

  zap trash: [
               '~/Library/Application Support/DaisyDisk',
               '~/Library/Caches/com.daisydiskapp.DaisyDiskStandAlone',
               '~/Library/Preferences/com.daisydiskapp.DaisyDiskStandAlone.plist',
             ]
end


text:
<?php

class Horde_UI_Widget {

    /**
     * Any variables that should be preserved in all of the widget's
     * links.
     *
     * @var array
     */
    var $_preserve = array();

    /**
     * The name of this widget.  This is used as the basename for variables
     * we access and manipulate.
     *
     * @var string
     */
    var $_name;

    /**
     * A reference to a Variables:: object this widget will use and
     * manipulate.
     *
     * @var Variables
     */
    var $_vars;

    /**
     * An array of name => value pairs which configure how this widget
     * behaves.
     *
     * @var array
     */
    var $_config;

    /**
     * Holds the name of a callback function to call on any URLS before they
     * are used/returned. If an array, it is taken as an object/method name, if
     * a string, it is taken as a php function.
     *
     * @var callable
     */
    var $_url_callback = array('Horde', 'applicationUrl');

    /**
     * Construct a new UI Widget interface.
     *
     * @param string $name      The name of the variable which will track this
     *                          UI widget's state.
     * @param Variables &$vars  A Variables:: object.
     * @param array $config     The widget's configuration.
     */
    function Horde_UI_Widget($name, &$vars, $config = array())
    {
        $this->_name = $name;
        $this->_vars = &$vars;

        if (array_key_exists('url_callback', $config)) {
            $this->_url_callback = $config['url_callback'];
            unset($config['url_callback']);
        }
        $this->_config = $config;
    }

    /**
     * Instructs Horde_UI_Widget to preserve a variable or a set of variables.
     *
     * @param string|array $var  The name of the variable to preserve, or
     *                           (since Horde 3.2) an array of variables to
     *                           preserve.
     * @param mixed $value       If preserving a single key, the value of the
     *                           variable to preserve.
     */
    function preserve($var, $value = null)
    {
        if (is_array($var)) {
            foreach ($var as $key => $value) {
                $this->_preserve[$key] = $value;
            }
        } else {
            $this->_preserve[$var] = $value;
        }
    }

    /**
     * @access private
     */
    function _addPreserved($link)
    {
        foreach ($this->_preserve as $varName => $varValue) {
            $link = Util::addParameter($link, $varName, $varValue);
        }
        return $link;
    }

    /**
     * Render the widget.
     *
     * @abstract
     *
     * @param mixed $data  The widget's state data.
     */
    function render()
    {}

    /**
     * @protected
     */
    function _link($link)
    {
        if (is_callable($this->_url_callback)) {
            return call_user_func($this->_url_callback, $link);
        }

        return $link;
    }

}


text:
const game = new Phaser.Game(800, 600, Phaser.AUTO, 'game-area', {preload, create, update}, false, false );

let player: Phaser.Sprite;
let cursors: Phaser.CursorKeys;
let playerSpeed = 250, playerScale = 3;
let gamepadDebug: HTMLSpanElement;
let gamepads: Phaser.Gamepad;

function preload() {
    game.load.spritesheet('linkRunning', 'images/LinkRunning.gif', 24, 28);
    gamepadDebug = document.getElementById("gamepadDebug");
}

function create() {
    player = game.add.sprite(40, 100, 'linkRunning');
    player.animations.add('runRight', [0,1,2,3,4,5,6,7], 30);
    player.scale.x = playerScale;
    player.scale.y = playerScale;
    player.anchor.x = 0.5;
    player.anchor.x = 0.5;
    game.physics.enable(player, Phaser.Physics.ARCADE);

    gamepads = new Phaser.Gamepad(game);

    game.input.gamepad.addCallbacks(this, {
      onAxis: (pad: Phaser.SinglePad, axis: number, value: number) => {
        const axis0 = pad.axis(0);
        const axis1 = pad.axis(1);
        padStatus[pad.index] = `Pad ${pad.index} (${(<any>pad)._rawPad['id']}): Zero: ${axis0}, One: ${axis1}`;
        pad0mainstick = {x: axis0 || 0, y: axis1 || 0};
      }
    })

    game.input.gamepad.start();

    cursors = game.input.keyboard.createCursorKeys();
}

var padStatus: string[] = [];
var pad0mainstick: {x: number, y: number} = undefined;

function update() {

  gamepadDebug.innerHTML = `gamepads supported: ${gamepads.supported}.  gamepads connected: ${gamepads.padsConnected}.  gamepad info: ${JSON.stringify(padStatus)}`;

  player.body.velocity.setTo(0, 0);

  if (pad0mainstick) {
    player.body.velocity.x = playerSpeed * pad0mainstick.x;
    player.body.velocity.y = playerSpeed * pad0mainstick.y;
    if (pad0mainstick.x > 0) {
      player.scale.x = playerScale;
    } else if (pad0mainstick.x < 0) {
      player.scale.x = -playerScale;
    }
    player.animations.play('runRight');
  }

  if (cursors.left.isDown) {
    player.body.velocity.x -= playerSpeed;
    player.scale.x = -playerScale;
    player.animations.play('runRight');
  }
  if (cursors.right.isDown) {
    player.body.velocity.x += playerSpeed;
    player.scale.x = playerScale;
    player.animations.play('runRight');
  }
  if (cursors.up.isDown) {
    player.body.velocity.y -= playerSpeed;
    player.animations.play('runRight');
  }
  if (cursors.down.isDown) {
    player.body.velocity.y += playerSpeed;
    player.animations.play('runRight');
  }

  if (player.body.velocity.x === 0 && player.body.velocity.y === 0) {
    player.animations.stop();
    player.frame = 8;
  }

}


text:
require "test_helper"

feature "As a site owner I would like to add more lists so that I can add more content" do
  scenario "creating a list" do
    visit new_list_path

    fill_in "Name", with: "How to make a new list"

    click_on "Create List"

    page.must_have_content "How to make a new list"
    page.wont_have_content "Lists Index"
  end
end


text:
var async = require('async');
var Promise = require('bluebird');
var exec = require('child_process').exec;
var csv = require('csv');
var fs = require('fs');
var path = require('path');
var request = require('request');
var unzip = require('unzip2');
var Batch = require('./batch');
var Writable = require('stream').Writable;
var expandTilde = require('expand-tilde');
var HashMap = require('hashmap');
var q;

function download(knex, config, callback) {
  var log = (config.verbose === false) ? function() {} : console.log;

  q = async.queue(downloadGTFS, 1);

  var batchSize = parseInt(config.batch_size)
  if (batchSize <= 0) {
    batchSize = 200;
  }

  // loop through all agencies specified
  // If the agency_key is a URL, download that GTFS file, otherwise treat
  // it as an agency_key and get file from gtfs-data-exchange.com
  config.agencies.forEach(function(item) {
    var agency = {};

    if (typeof(item) == 'string') {
      agency.agency_key = item;
      agency.agency_url = 'http://www.gtfs-data-exchange.com/agency/' + item + '/latest.zip';
    } else if (item.url) {
      agency.agency_key = item.agency_key;
      agency.agency_url = item.url;
    } else if (item.path) {
      agency.agency_key = item.agency_key;
      agency.path = item.path;
    }

    if (!agency.agency_key) {
      handleError(new Error('No URL or Agency Key or path provided.'));
    }

    q.push(agency);
  });

  q.drain = function(e) {
    if (e) handleError(e);

    log('All agencies completed (' + config.agencies.length + ' total)');
    callback();
  };

  function handleError(error) {
    console.error(error || 'Unknown Error');
    callback(error);
  };

  function downloadGTFS(task, cb) {
    var downloadDir = 'downloads';
    var gtfsDir = 'downloads';
    var agency_key = task.agency_key;
    var agencyEntryId = null;
    var lastModified = null;

    log(agency_key + ': Starting');

    // TODO: Replace with Bluebird.
    async.series([
      cleanupFiles,
      getFiles,
      handleImport,
      cleanupFiles
    ], function(e, results) {
      if (e) {
        log(agency_key + ': Error: ' + e);
        console.error('Stack:\n', e.stack);
      }
      else log(agency_key + ': Completed');
      cb();
    });

    function cleanupFiles(cb) {
      //remove old downloaded file
      exec((process.platform.match(/^win/) ? 'rmdir /Q /S ' : 'rm -rf ') + downloadDir, function(e) {
        try {
          //create downloads directory
          fs.mkdirSync(downloadDir);
          cb();
        } catch (e) {
          if (e.code == 'EEXIST') {
            cb();
          } else {
            handleError(e);
          }
        }
      });
    }

    function getFiles(cb) {
      if (task.agency_url) {
        downloadFiles(cb);
      } else if (task.path) {
        readFiles(cb);
      }
    }

    function downloadFiles(cb) {
      // do download
      var file_protocol = require('url').parse(task.agency_url).protocol;
      if (file_protocol === 'http:' || file_protocol === 'https:') {
        log(agency_key + ': Downloading');
        request(task.agency_url, processFile).pipe(fs.createWriteStream(downloadDir + '/latest.zip'));

        function processFile(e, response, body) {
          if (response && response.statusCode != 200) {
            cb(new Error('Couldn\'t download files'));
          }
          log(agency_key + ': Download successful');

          var lastModifiedHeader = response.headers['last-modified'];
          if (!lastModifiedHeader) {
            lastModified = new Date();
            log(agency_key + ': Last modified: Not available');
          } else {
            lastModified = new Date(lastModifiedHeader);
            log(agency_key + ': Last modified: ' + lastModified);
          }

          fs.createReadStream(downloadDir + '/latest.zip')
            .pipe(unzip.Extract({
              path: downloadDir
            }).on('close', cb))
            .on('error', function(e) {
              log(agency_key + ': Error Unzipping File');
              handleError(e);
            });
        }
      } else {
        if (!fs.existsSync(task.agency_url)) {
          return cb(new Error('File does not exists'));
        }

        fs.createReadStream(task.agency_url)
          .pipe(fs.createWriteStream(downloadDir + '/latest.zip'))
          .on('close', function() {
            fs.createReadStream(downloadDir + '/latest.zip')
              .pipe(unzip.Extract({
                path: downloadDir
              }).on('close', cb))
              .on('error', handleError);
          })
          .on('error', handleError);
      }
    }

    function readFiles(cb) {
      var filePath = expandTilde(task.path);
      if (path.extname(filePath) === '.zip') {
        // local file is zipped
        fs.createReadStream(filePath)
          .pipe(unzip.Extract({
            path: downloadDir
          }).on('close', cb))
          .on('error', handleError);
      } else {
        // local file is unzipped, just read it from there.
        gtfsDir = filePath;
        cb();
      }
    }

    function handleImport(cb) {

      knex.transaction(function(trx) {

        return new Promise.resolve()
        .then(function () {
          return removeAgency(trx);
        })
        .then(function() { return importAgencies(trx); })
        .then(function() { return importCalendars(trx); })
        .then(function() { return importCalendarDates(trx); })
        .then(function() { return importStops(trx); })
        .then(function() { return importRoutes(trx); })
        .then(function() { return importShapes(trx); })
        .then(function() { return importTrips(trx); })
        .then(function() { return importStopTimes(trx); })
        // The following optional files are not implemented yet.
        //.then(importFareAttributes),
        //.then(importFareRules),
        //.then(importFeedInfos),
        //.then(importFrequencies),
        //.then(importTransfers)
        .then(function() {
          // Finally update the import date.
          return trx("agency").where({ agency_entry_id: agencyEntryId })
          .update({ last_update: lastModified })
        });
      })
      .then(function(inserts) {
        cb();
      })
      .catch(function(error) {
        cb(error);
      });

      function removeAgency(trx) {

        // Clean up caches.
        cachedTripRefs = new HashMap();
        cachedStopRefs = new HashMap();
        cachedRouteRefs = new HashMap();
        cachedServiceRefs = new HashMap();
        cachedAgencyRefs = new HashMap();
        cachedShapeRefs = new HashMap();

        // First get the agency_entry_id.
        return trx('agency_entry').select('id').where({
            agency_key: agency_key
        }).then(function (results) {
          var agencyEntryId = (results[0] != null ? results[0].id : null);
          if (!agencyEntryId) {
            log(agency_key + ': No previous entries for the agency key')
            return;
          } else {
            log(agency_key + ': Removing previous entries with the same agency key');
            return Promise.resolve(agencyEntryId);
          }
        }).then(function (agencyEntryId) {
          // For optimal performance, clean up the larges data sets separately.

          var tablesWithEntryId = ['stop_time', 'stop', 'trip', 'route', 'service'];

          return Promise.resolve(tablesWithEntryId)
          .map(function (tableName) {
            return trx(tableName).where({
              agency_entry_id: agencyEntryId
            }).del();
          })
          .then(function (){
            // Everything else should just cascade.
            return trx('agency_entry').where({
              id: agencyEntryId
            }).del();
          });
        });
      }

      function readGtfsFile(fileName, batchSize, batchHandler) {
        return new Promise(function (resolve, reject) {

          var filepath = path.join(gtfsDir, fileName);

          if (!fs.existsSync(filepath)) {
            log(agency_key + ': No ' + fileName + ' file found at ' + gtfsDir);
            return reject('No file: ' + fileName);
          }
          log(agency_key + ': Reading ' + fileName);

          // Create a writable stream to get the row batch.
          var ws = Writable({ objectMode: true });
          ws._write = function(rows, enc, next) {
            batchHandler(rows)
            .then(function() {
              // Next batch.
              next();
            })
            .catch(function(err) {
              // Bridge the error.
              reject(err);
            });
          };

          var gtfs = fs.createReadStream(filepath)
          .pipe(csv.parse({
            columns: true,
            relax: true,
            skip_empty_lines: true
          }))
          .pipe(Batch({ batchSize: batchSize }))
          .pipe(ws);

          gtfs.on('finish', function() {
            resolve();
          });
        });
      }

      function asWritable(cb) {
        var ws = Writable({ objectMode: true });
        ws._write = function(chunk, enc, next) {
          cb(chunk, function() {
            next();
          });
        };
        return ws;
      }

      function importAgencies(trx) {
        console.time('agencies');
        // First create entry for the agency.
        return trx("agency_entry").insert({ agency_key: agency_key })
        .returning('id')
        .tap(function(id) {
          // Set the global id for all imported data.
          agencyEntryId = id[0];
        })
        .then(function() {

          return readGtfsFile('agency.txt', batchSize, function(rows, next) {

            return Promise.map(rows, function(row) {
              // Reformat the fields.
              row.agency_entry_id = agencyEntryId;

              // agency_id can be null, if only one agency.
              if (rows.length == 1 && row.agency_id == null) {
                row.agency_id = agency_key;
              }

              return trx('agency').insert(row)
              .returning('id')
              .tap(function(result) {
                addAgencyRef(row.agency_id, result[0]);
              });
            })
            .tap(next);

          });
        });
      }

      function importCalendars(trx) {
        return readGtfsFile('calendar.txt', batchSize, function(rows, next) {

          return Promise.resolve(rows)
          .map(function (row) {
            // Reformat the fields.
            row.monday = toInt(row.monday);
            row.tuesday = toInt(row.tuesday);
            row.wednesday = toInt(row.wednesday);
            row.thursday = toInt(row.thursday);
            row.friday = toInt(row.friday);
            row.saturday = toInt(row.saturday);
            row.sunday = toInt(row.sunday);

            row.start_date = toDate(row.start_date);
            row.end_date = toDate(row.end_date);

            // Create a service for the calendar entry.
            return trx('service').insert({
              agency_entry_id: agencyEntryId,
              service_id: row.service_id
            })
            .returning('id')
            .tap(function(result) {
              addServiceRef(row.service_id, result[0]);
            })
            .then(function(id) {
              // Set the global id for all imported data.
              row.service_id = id[0];
              return row;
            });
          })
          .then(function(results) {
            return trx('calendar').insert(results)
            .tap(next);

          });
        });
      }

      function promiseService(service) {
        return trx('service').insert(service)
        .returning('id')
        .tap(function(result) {
          addServiceRef(service.service_id, result[0]);
        })
        .then(function(ids) {
          if (ids != null) {
            return ids[0];
          } else {
            handleError("Could not insert service: " + service);
          }
        });
      }

      function importCalendarDates(trx) {
        return readGtfsFile('calendar_dates.txt', batchSize, function(rows, next) {

          return Promise.resolve(rows)
          .map(function (row) {
            // Reformat the fields.
            row.exception_type = toInt(row.exception_type);
            row.date = toDate(row.date);

            // First try to find existing service.
            return trx('service').select('id').where({
              service_id: row.service_id
            }).then(function (results) {
              if (results.length > 0) {
                row.service_id = results[0].id;
                return row;
              } else {
                // No service, create a new one.
                return promiseService({
                  agency_entry_id: agencyEntryId,
                  service_id: row.service_id
                }).then(function(serviceId) {
                  row.service_id = serviceId;
                  return row;
                });
              }
            });
          })
          .then(function(results) {
            return trx('calendar_date').insert(results)
            .tap(next);
          });
        })
        .catch(function() {
          log(agency_key + ': Skipping calendar_dates.txt')
          return Promise.resolve();
        });
      }

      function importStops(trx) {
        return readGtfsFile('stops.txt', batchSize, function(rows, next) {

          return Promise.resolve(rows)
          .map(function(row) {
            row.agency_entry_id = agencyEntryId;

            return trx('stop').insert(row)
            .returning('id')
            .tap(function(result) {
              addStopRef(row.stop_id, result[0]);
            });
          })
          .tap(next);

        });
      }

      function importRoutes(trx) {
        return readGtfsFile('routes.txt', batchSize, function(rows, next) {

          return Promise.resolve(rows)
          .map(function (row) {
            // Reformat the fields.
            row.agency_entry_id = agencyEntryId;
            row.route_type = toInt(row.route_type);
            row.agency_id = getAgencyRef(row.agency_id);

            return trx('route').insert(row)
            .returning('id')
            .then(function(result) {
              addRouteRef(row.route_id, result[0]);
            });
          })
          .tap(next);

        });
      }

      function importFareAttributes(trx) {
        // 'fare_attributes.txt'
      }

      function importFareRules(trx) {
        // 'fare_rules.txt'
      }

      function importFeedInfos(trx) {
        // 'feed_info.txt'
      }

      function importFrequencies(trx) {
        // 'frequencies.txt'
      }

      function importTrips(trx) {
        return readGtfsFile('trips.txt', batchSize, function(rows, next) {

          return Promise.resolve(rows)
          .map(function (row) {

            // trip_id: string not null
            row.agency_entry_id = agencyEntryId;
            row.route_id = getRouteRef(row.route_id);
            row.service_id = getServiceRef(row.service_id);
            // trip_headsign: string
            // trip_short_name: string
            row.direction_id = toInt(row.direction_id);
            // block_id: string
            row.shape_id = getShapeRef(row.shape_id);
            row.wheelchair_accessible = toInt(row.wheelchair_accessible);
            row.bikes_allowed = toInt(row.bikes_allowed);

            return trx('trip').insert(row)
            .returning('id')
            .tap(function (result) {
              addTripRef(row.trip_id, result[0]);
            });
          })
          .tap(next);

        });
      }

      function importShapes(trx) {
        return readGtfsFile('shapes.txt', batchSize, function(rows, next) {

          // Get the unique shape IDs first.
          var rowsByShapeId = groupByShapeId(rows);

          return Promise.resolve(rowsByShapeId)
          .map(function(group) {
            return Promise.props({
              shape_id: getOrCreateShapeRef(group.shape_id, trx),
              rows: group.rows,
            });
          })
          .map(function(group) {
            return Promise.resolve(group.rows)
            .map(function(row){
              return {
                shape_id: group.shape_id,
                shape_pt_lon: toFloat(row.shape_pt_lon),
                shape_pt_lat: toFloat(row.shape_pt_lat),
                shape_pt_sequence: toInt(row.shape_pt_sequence),
                shape_dist_traveled: toFloat(row.shape_dist_traveled)
              };
            })
          })
          .map(function(shape_sequences) {
            return trx('shape_sequence').insert(shape_sequences);
          })
          .tap(next);

        })
        .catch(function () {
          log(agency_key + ': Skipping shapes.txt')
          return Promise.resolve();
        });
      }

      function importStopTimes(trx) {
        return readGtfsFile('stop_times.txt', batchSize, function(rows, next) {

          return Promise.resolve(rows)
          .map(function (row) {

            row.agency_entry_id = agencyEntryId;
            row.trip_id = getTripRef(row.trip_id);
            row.stop_id = getStopRef(row.stop_id);
            row.arrival_time = row.arrival_time;
            row.departure_time = row.departure_time;
            row.stop_sequence = toInt(row.stop_sequence);
            row.stop_headsign = row.stop_headsign;
            row.pickup_type = toInt(row.pickup_type);
            row.drop_off_type = toInt(row.drop_off_type);
            row.shape_dist_traveled = toFloat(row.shape_dist_traveled);
            row.timepoint = toInt(row.timepoint);

            return row;
          })
          .tap(function(rows) {
            return trx('stop_time').insert(rows);
          })
          .tap(next);

        });
      }

      function importTransfers(trx) {
        //processGtfsFile('transfers.txt', cb);
      }
    }
  }

  var cachedTripRefs = new HashMap();
  var cachedStopRefs = new HashMap();
  var cachedRouteRefs = new HashMap();
  var cachedServiceRefs = new HashMap();
  var cachedAgencyRefs = new HashMap();
  var cachedShapeRefs = new HashMap();

  function addAgencyRef(id, ref) {
    cachedAgencyRefs.set(id, ref);
  }

  function getAgencyRef(id) {
    var ref = cachedAgencyRefs.get(id);
    if (ref == null) {
      // In case we only have one agency ID, use that.
      var refs = cachedAgencyRefs.values();
      if (refs.length == 1) {
        ref = refs[0];
      } else {
        handleError('Could not determine agency with ID: ' + id);
      }
    }

    return ref;
  }

  function addTripRef(id, ref) {
    cachedTripRefs.set(id, ref);
  }

  function getTripRef(id) {
    return getRef(cachedTripRefs, id, 'trip');
  }

  function addStopRef(id, ref) {
    cachedStopRefs.set(id, ref);
  }

  function getStopRef(id) {
    return getRef(cachedStopRefs, id, 'stop');
  }

  function addRouteRef(id, ref) {
    cachedRouteRefs.set(id, ref);
  }

  function getRouteRef(id) {
    return getRef(cachedRouteRefs, id, 'route');
  }

  function addServiceRef(id, ref) {
    cachedServiceRefs.set(id, ref);
  }

  function getServiceRef(id) {
    return getRef(cachedServiceRefs, id, 'service');
  }

  function getShapeRef(id) {
    // Shape ID can be null.
    if (id === null || id === '') return null;
    else return getRef(cachedShapeRefs, id, 'shape');
  }

  function getRef(hashMap, id, relation) {
    var ref = hashMap.get(id);
    if (ref == null) {
      handleError('No such ' + relation + ' id: ' + id);
    }
    return ref;
  }

  function getOrCreateShapeRef(id, knex) {
    var shapeId = cachedShapeRefs.get(id);
    if (shapeId != null) {
      return Promise.resolve(shapeId);
    } else {
      return knex('shape').insert({ shape_id: id })
      .returning('id')
      .then(function(result) {
        if (result[0]  == null) {
          handleError('No such shape_id: ' + id + '\n' + JSON.stringify(result));
        }
        return result[0];
      })
      .tap(function(shapeRef) {
        cachedShapeRefs.set(id, shapeRef);
      });
    }
  }
}

module.exports = download;

// Helpers

function toInt(value) {
  var ret = parseInt(value);
  return isNaN(ret) ? null : ret;
}

function toFloat(value) {
  var ret = parseFloat(value);
  var result = isNaN(ret) ? null : ret;
  return result;
}

function toDate(str) {
  // Eg. 20160831
  var y = str.substring(0,4);
  var m = str.substring(4,6);
  var d = str.substring(6,8);
  return new Date(y, m, d);
}

function groupByShapeId(rows) {
  var dict = rows.reduce(function (acc, row) {
    var d = acc[row.shape_id];
    if (!d) {
      d = [];
      acc[row.shape_id] = d;
    }
    d.push(row);
    return acc;
  }, {});

  // Make it an array.
  var result = [];
  for (var key in dict) {
    result.push({
      shape_id: key,
      rows: dict[key]
    });
  }
  return result;
}


text:
This is a simple Kafka connector (formerly called a "copycat connector"). This repo is intended to be a simple skeleton, that you can copy/paste to get started with developing your own Kafka connector.

This repo contains a fork of the connect-file plugin from Kafka trunk. The code itself has not changed. However, I renamed the package, so that there is no chance that you will accidentally get the connect-file plugin from trunk.

This things specific to this repo are the build files, as well as the instructions in this README that tell you how to get started.

Instructions for building
-------------------------
```
$ git clone https://github.com/wushujames/kafka-connector-skeleton connect-file
$ (cd connect-file && ./gradlew build)
```

Instructions for running
------------------------
1.  Run zookeeper somehow.
    ```
    Here are instructions on how to run it using docker.
    $ docker run -d --name zookeeper -p 2181:2181 confluent/zookeeper
    ```

2.  Download and run kafka 0.9.0 locally by following the instructions at http://kafka.apache.org/documentation.html#quickstart
    ```
    $ curl -o kafka_2.11-0.9.0.0.tgz http://www.us.apache.org/dist/kafka/0.9.0.0/kafka_2.11-0.9.0.0.tgz
    $ tar xvfz kafka_2.11-0.9.0.0.tgz
    $ cd kafka_2.11-0.9.0.0
    $ ./bin/kafka-server-start.sh config/server.properties
    ```

3.  Run your connect-file-source plugin
    ```
    $ export CLASSPATH=/path/to/connect-file/build/libs/connect-file.jar
    $ kafka_2.11-0.9.0.0/bin/connect-standalone.sh connect-file/connect-standalone.properties  connect-file/connect-file-source.properties
    ```

4.  Write stuff to test.txt (that is the that this connector will read from, as configured in connect-file-source.properties)
    ```
    $ echo `date` >> test.txt
    ```

5.  Read the data out from the kafka topic named 'test' (that is the that this connector will write to, as configured in connect-file-source.properties)
    ```
    $ kafka_2.11-0.9.0.0/bin/kafka-console-consumer.sh  --zookeeper localhost:2181 --topic test
    {"schema":{"type":"string","optional":false},"payload":"Thu Oct 15 23:03:15 PDT 2015"}
    ```

6.  Run your connect-file-sink plugin
    ```
    $ export CLASSPATH=/path/to/connect-file/build/libs/connect-file.jar
    $ kafka_2.11-0.9.0.0/bin/connect-standalone.sh connect-file/connect-standalone.properties  connect-file/connect-file-sink.properties
    ```

7.  Check that the file-sink plugin has written the data to the file
    ```
    $ cat test.sink.txt
    Thu Oct 15 23:03:15 PDT 2015
    ```


text:
from django.contrib.auth import authenticate

import amo.tests
from users.models import UserProfile

class TestAmoUserBackend(amo.tests.TestCase):
    fixtures = ['users/test_backends']

    def test_success(self):
        assert authenticate(username='jbalogh@mozilla.com', password='foo')

    def test_failure(self):
        assert not authenticate(username='jbalogh@mozilla.com', password='x')


text:
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Ghpr.NUnit.Utils;
using NUnit.Framework;
using NUnit.Framework.Interfaces;

namespace Ghpr.NUnitTests
{
    [TestFixture]
    public class TestingScreenshotTaking
    {
        [TearDown]
        public void TakeScreenIfFailed()
        {
            var res = TestContext.CurrentContext.Result.Outcome;
            if (res.Equals(ResultState.Failure) || res.Equals(ResultState.Error))
            {
                ScreenHelper.SaveScreenshot(TakeScreen());
            }
        }

        public static byte[] TakeScreen()
        {
            var b = Screen.PrimaryScreen.Bounds;
            var ic = new ImageConverter();
            using (var btm = new Bitmap(b.Width, b.Height))
            using (var g = Graphics.FromImage(btm))
            {
                g.CopyFromScreen(b.X, b.Y, 0, 0, btm.Size, CopyPixelOperation.SourceCopy);
                return (byte[])ic.ConvertTo(btm, typeof(byte[]));
            }
        }

        public static string SaveScreen(byte[] screen, string fileName)
        {
            var folder = @"C:\Screenshots";
            Directory.CreateDirectory(folder);
            var fullPath = Path.Combine(folder, fileName);
            File.WriteAllBytes(fullPath, screen);
            return fullPath;
        }

        [Test(Description = "This is example of taking screenshots inside test")]
        [Category("Screenshots")]
        public void TestMethodPassed()
        {
            Console.WriteLine("Taking screen...");
            var bytes = TakeScreen();
            //all you need to do is to pass byte[] to ScreenHelper:
            ScreenHelper.SaveScreenshot(bytes);
            Console.WriteLine("Done.");
        }

        [Test(Description = "This is example of taking screenshots inside test")]
        [Category("Screenshots")]
        public void TestMethodFailed()
        {
            Console.WriteLine("Taking screen...");
            var bytes = TakeScreen();
            //all you need to do is to pass byte[] to ScreenHelper:
            ScreenHelper.SaveScreenshot(bytes);
            Console.WriteLine("Done.");
            Assert.Fail("Noooooo..... Test is failed.");
        }

        [Test(Description = "This is example of saving screenshots using NUnit context")]
        [Category("Screenshots")]
        public void TestMethod()
        {
            Console.WriteLine("Taking screen...");
            var bytes = TakeScreen();
            var fullPath1 = SaveScreen(bytes, Guid.NewGuid() + ".png");
            var fullPath2 = SaveScreen(bytes, Guid.NewGuid() + ".png");
            var fullPath3 = SaveScreen(bytes, Guid.NewGuid() + ".png");
            //all you need to do is to add full path to TestContext:
            TestContext.AddTestAttachment(fullPath1);
            TestContext.AddTestAttachment(fullPath2);
            TestContext.AddTestAttachment(fullPath3);
            Console.WriteLine("Done.");
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    bean-discovery-mode, explicit bean archive

    Java Platform, Enterprise Edition (Java EE) 7 - Java Platform, Enterprise Edition: The Java EE Tutorial
    25.1 Packaging CDI Applications
    http://docs.oracle.com/javaee/7/tutorial/cdi-adv001.htm

    15.6. Packaging and deployment - 15.6.1. Explicit bean archive, 15.6.2. Implicit bean archive
    https://docs.jboss.org/weld/reference/latest/en-US/html/ee.html#packaging-and-deployment
-->
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
       version="1.1" bean-discovery-mode="all">
</beans>


text:
import { Metadata_artwork } from "__generated__/Metadata_artwork.graphql"
import colors from "Assets/Colors"
import { garamond } from "Assets/Fonts"
import StyledTextLink from "Components/TextLink"
import React from "react"
import { createFragmentContainer, graphql } from "react-relay"
import styled from "styled-components"
import { DetailsFragmentContainer as Details } from "./Details"

export interface MetadataProps extends React.HTMLProps<MetadataContainer> {
  artwork: Metadata_artwork
  extended?: boolean
}

export class MetadataContainer extends React.Component<MetadataProps> {
  static defaultProps = {
    extended: true,
  }

  render() {
    const { artwork, className, extended } = this.props

    return (
      <StyledTextLink href={artwork.href}>
        <div className={className}>
          <Details
            includeLinks={false}
            showSaleLine={extended}
            artwork={artwork}
          />
        </div>
      </StyledTextLink>
    )
  }
}

export const Metadata = styled(MetadataContainer)`
  ${garamond("s15")};
  color: ${colors.graySemibold};
  margin-top: 12px;
  text-align: left;
`

export default createFragmentContainer(Metadata, {
  artwork: graphql`
    fragment Metadata_artwork on Artwork {
      ...Details_artwork
      ...Contact_artwork
      href
    }
  `,
})


text:
CREATE TABLE users (
    id INTEGER PRIMARY KEY NOT NULL,
    email TEXT UNIQUE NOT NULL,
    password VARCHAR(100) NOT NULL,
    salt VARCHAR(100) NOT NULL,
    created_at DATETIME DEFAULT current_timestamp,
    modified_at DATETIME DEFAULT current_timestamp
);

CREATE TABLE wp_domains (
    id INTEGER PRIMARY KEY NOT NULL,
    user_id INTEGER NOT NULL,
    domain TEXT NOT NULL,

    FOREIGN KEY(user_id) REFERENCES users(id)
);

CREATE TABLE published_posts (
    user_id INTEGER NOT NULL,
    domain_id INTEGER NOT NULL,
    post_id INTEGER NOT NULL,
    facebook BOOLEAN NOT NULL DEFAULT FALSE,
    linkedin BOOLEAN NOT NULL DEFAULT FALSE,
    tumblr BOOLEAN NOT NULL DEFAULT FALSE,
    twitter BOOLEAN NOT NULL DEFAULT FALSE,
    created_at DATETIME DEFAULT current_timestamp,

    FOREIGN KEY(user_id) REFERENCES users(id),
    FOREIGN KEY(domain_id) REFERENCES wp_domains(id)
);

CREATE TABLE auth_twitter (
    user_id INTEGER UNIQUE NOT NULL,
    oauth_token VARCHAR(200),       -- TODO: Set to exact length.
    oauth_secret VARCHAR(200),      -- TODO: Set to exact length.
    oauth_verifier VARCHAR(200),    -- TODO: Set to exact length.
    access_token VARCHAR(200),      -- TODO: Set to exact length.
    access_secret VARCHAR(200),     -- TODO: Set to exact length.
    modified_at DATETIME DEFAULT CURRENT_TIMESTAMP,

    FOREIGN KEY(user_id) REFERENCES users(id)
);

CREATE TABLE auth_tumblr (
    user_id INTEGER UNIQUE NOT NULL,
    oauth_token VARCHAR(200),       -- TODO: Set to exact length.
    oauth_secret VARCHAR(200),      -- TODO: Set to exact length.
    oauth_verifier VARCHAR(200),    -- TODO: Set to exact length.
    access_token VARCHAR(200),      -- TODO: Set to exact length.
    access_secret VARCHAR(200),     -- TODO: Set to exact length.
    modified_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

CREATE TRIGGER update_users_set_modtime BEFORE UPDATE ON users
FOR EACH ROW BEGIN
    UPDATE users SET modified_at = current_timestamp;
END;

CREATE TRIGGER update_auth_twitter_set_modtime BEFORE UPDATE ON auth_twitter
FOR EACH ROW BEGIN
    UPDATE auth_twitter SET modified_at = current_timestamp;
END;

CREATE TRIGGER update_auth_tumblr_set_modtime BEFORE UPDATE ON auth_tumblr
FOR EACH ROW BEGIN
    UPDATE auth_tumblr SET modified_at = current_timestamp;
END;