text:
title: How I'd Improve Projection Systems
layout: post
summary: Two suggestions for projection system authors.
date:   2013-12-16 12:30:00
---

I'm a big fan of baseball projections. They're a welcome sight around the
in the doldrums between seasons, and they're fun to debate.

In prototyping a unified dashboard for mixing and remixing projections (more on that later),
I've spent ample time with most major distributions.
There are two points, I feel, that would make working with this data
less troublesome.

1. **Include a license.**

   Including a license is an essential step for anyone releasing data into the wild.
   Without a license, it's terminally unclear if I can build around your data;
   knowing what rights and attribution you retain in your
   distribution would be *great*.
   At the very least, include note about how I may use your data.
   And, explicitly stating "no license" tells me more than not
   having a license ever could.

   Please consider a Creative Commons license, like
   CC BY or CC BY-ND.

2. **Strive to include at least one globally-available player ID.**

   Not all player names are unique. If you're projecting major and minor leaguers,
   you're going to have name duplication.

   The Chadwick Bureau
   has done the hard work
   to build a player Rosetta Stone incorporating Retrosheet, MLBAM, FanGraphs, B.Pro, NPB, and more.
   It's not perfect, but it should prove helpful in filling gaps. It has for me.

   I realize this potentially introduces more complexity than authors
   can afford or can afford to care about. Failing that, please include as many peripherals
   (team, age, bats, throws) as possible. Matching using only these data points is not ideal,
   but their availability goes a long way toward disambiguation.
   These peripherals are also what could be used in the case where
   a player does not have a database from any major source.

#### Bonus request

**Split player names into first and last names.**

First and last names are always useful, especially when disambiguating without an ID.
Please consider splitting names if possible.


text:
package org.apache.solr.schema;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.solr.common.params.CoreAdminParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.core.AbstractBadConfigTestBase;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.handler.admin.CoreAdminHandler;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
import org.junit.After;
import org.junit.Before;

public class TestManagedSchema extends AbstractBadConfigTestBase {

  private static File tmpSolrHome;
  private static File tmpConfDir;

  private static final String collection = "collection1";
  private static final String confDir = collection + "/conf";

  @Before
  private void initManagedSchemaCore() throws Exception {
    createTempDir();
    final String tmpSolrHomePath
        = TEMP_DIR + File.separator + TestManagedSchema.class.getSimpleName() + System.currentTimeMillis();
    tmpSolrHome = new File(tmpSolrHomePath).getAbsoluteFile();
    tmpConfDir = new File(tmpSolrHome, confDir);
    File testHomeConfDir = new File(TEST_HOME(), confDir);
    FileUtils.copyFileToDirectory(new File(testHomeConfDir, "solrconfig-managed-schema.xml"), tmpConfDir);
    FileUtils.copyFileToDirectory(new File(testHomeConfDir, "solrconfig-basic.xml"), tmpConfDir);
    FileUtils.copyFileToDirectory(new File(testHomeConfDir, "schema-minimal.xml"), tmpConfDir);
    // initCore will trigger an upgrade to managed schema, since the solrconfig has
    // <schemaFactory class="ManagedIndexSchemaFactory" ... />
    initCore("solrconfig-managed-schema.xml", "schema-minimal.xml", tmpSolrHome.getPath());
  }

  @After
  private void deleteCoreAndTempSolrHomeDirectory() throws Exception {
    deleteCore();
    FileUtils.deleteDirectory(tmpSolrHome);
  }

  public void testUpgrade() throws Exception {
    File managedSchemaFile = new File(tmpConfDir, "managed-schema");
    assertTrue(managedSchemaFile.exists());
    String managedSchema = FileUtils.readFileToString(managedSchemaFile, "UTF-8");
    assertTrue(managedSchema.contains("DO NOT EDIT"));
    File upgradedOriginalSchemaFile = new File(tmpConfDir, "schema-minimal.xml.bak");
    assertTrue(upgradedOriginalSchemaFile.exists());
    assertSchemaResource(collection, "managed-schema");
  }

  public void testUpgradeThenRestart() throws Exception {
    assertSchemaResource(collection, "managed-schema");
    deleteCore();
    File nonManagedSchemaFile = new File(tmpConfDir, "schema-minimal.xml");
    assertFalse(nonManagedSchemaFile.exists());
    initCore("solrconfig-managed-schema.xml", "schema-minimal.xml", tmpSolrHome.getPath());
    File managedSchemaFile = new File(tmpConfDir, "managed-schema");
    assertTrue(managedSchemaFile.exists());
    String managedSchema = FileUtils.readFileToString(managedSchemaFile, "UTF-8");
    assertTrue(managedSchema.contains("DO NOT EDIT"));
    File upgradedOriginalSchemaFile = new File(tmpConfDir, "schema-minimal.xml.bak");
    assertTrue(upgradedOriginalSchemaFile.exists());
    assertSchemaResource(collection, "managed-schema");
  }

  public void testUpgradeThenRestartNonManaged() throws Exception {
    deleteCore();
    // After upgrade to managed schema, fail to restart when solrconfig doesn't contain
    // <schemaFactory class="ManagedIndexSchemaFactory">...</schemaFactory>
    assertConfigs("solrconfig-basic.xml", "schema-minimal.xml", tmpSolrHome.getPath(),
                  "Can't find resource 'schema-minimal.xml'");
  }

  public void testUpgradeThenRestartNonManagedAfterPuttingBackNonManagedSchema() throws Exception {
    assertSchemaResource(collection, "managed-schema");
    deleteCore();
    File nonManagedSchemaFile = new File(tmpConfDir, "schema-minimal.xml");
    assertFalse(nonManagedSchemaFile.exists());
    File upgradedOriginalSchemaFile = new File(tmpConfDir, "schema-minimal.xml.bak");
    assertTrue(upgradedOriginalSchemaFile.exists());

    // After upgrade to managed schema, downgrading to non-managed should work after putting back the non-managed schema.
    FileUtils.moveFile(upgradedOriginalSchemaFile, nonManagedSchemaFile);
    initCore("solrconfig-basic.xml", "schema-minimal.xml", tmpSolrHome.getPath());
    assertSchemaResource(collection, "schema-minimal.xml");
  }

  private void assertSchemaResource(String collection, String expectedSchemaResource) throws Exception {
    final CoreContainer cores = h.getCoreContainer();
    cores.setPersistent(false);
    final CoreAdminHandler admin = new CoreAdminHandler(cores);
    SolrQueryRequest request = req(CoreAdminParams.ACTION, CoreAdminParams.CoreAdminAction.STATUS.toString());
    SolrQueryResponse response = new SolrQueryResponse();
    admin.handleRequestBody(request, response);
    assertNull("Exception on create", response.getException());
    NamedList responseValues = response.getValues();
    NamedList status = (NamedList)responseValues.get("status");
    NamedList collectionStatus = (NamedList)status.get(collection);
    String collectionSchema = (String)collectionStatus.get(CoreAdminParams.SCHEMA);
    assertEquals("Schema resource name differs from expected name", expectedSchemaResource, collectionSchema);
  }
}

redpajama_set_name: RedPajamaGithub


text:
import rhinoscriptsyntax as rs

__commandname__ = "makeSliceSurface"

def makeSliceSurface(surface, maxAngle):

    explodedSurfaces = rs.ExplodePolysurfaces(surface)

    newSurfaces = []
    rs.DeleteObject(surface)

    baseVec = (0,0,1)

    for i in explodedSurfaces:
        vec = rs.SurfaceNormal(i, [0,0])
        angle = rs.VectorAngle(baseVec, vec)

        if angle > maxAngle:
            rs.DeleteObject(i)
        else:
            newSurfaces.append(i)

    joinedSurface = rs.JoinSurfaces(newSurfaces)

    return joinedSurface

def main():
    surface = rs.GetObject("select surface")
    angle = rs.GetReal("max angle")
    makeSliceSurface(surface, angle)

def RunCommand(is_interactive):
    main()

'''
if __name__ == "__main__":
    main()
'''


text:
package com.tw.go.task.check_mk;

import org.json.JSONObject;

public class ActivateChangesJob extends CheckMkJob
{
    public ActivateChangesJob(ICheckMkClient checkMkClient) {
        super(checkMkClient);
        Action="activate_changes";
        Parameters="&allow_foreign_changes=1&mode=dirty";
    }

    @Override
    public String Execute(JSONObject requestObject) throws Exception {
        JSONObject jsonResult = ExecuteWebRequest(requestObject);
        if(!jsonResult.get("result_code").toString().equals("0"))
        {
            throw new ActivateChangesException(jsonResult);
        }
        return "Changes activated";
    }
}


text:
#include <stdlib.h>
#include "node.h"
#include "nan.h"

using namespace v8;
using namespace node;

namespace {

class proxy_container {
public:
  Persistent<Object> proxy;
  Persistent<Object> emitter;
  // we need a reference to our weak object.
  // modifying nan to give us access to the persistent obj is the only way.
  // if we save another persistent reference and not make it weak, it simply won't ever be gc'ed
  _NanWeakCallbackInfo<Object, proxy_container> *cbinfo;
};

Persistent<ObjectTemplate> proxyClass;

NanCallback *globalCallback;

bool IsDead(Handle<Object> proxy) {
  assert(proxy->InternalFieldCount() == 1);
  proxy_container *cont = reinterpret_cast<proxy_container*>(
    NanGetInternalFieldPointer(proxy, 0)
  );
  return cont == NULL || cont->cbinfo->persistent.IsEmpty();
}

Handle<Object> Unwrap(Handle<Object> proxy) {
  assert(!IsDead(proxy));
  proxy_container *cont = reinterpret_cast<proxy_container*>(
    NanGetInternalFieldPointer(proxy, 0)
  );
  Local<Object> _target = NanNew<Object>(cont->cbinfo->persistent);
  return _target;
}

Handle<Object> GetEmitter(Handle<Object> proxy) {
  proxy_container *cont = reinterpret_cast<proxy_container*>(
    NanGetInternalFieldPointer(proxy, 0)
  );
  assert(cont != NULL);
  Local<Object> _emitter = NanNew<Object>(cont->emitter);
  return _emitter;
}

#define UNWRAP                            \
  NanScope();                             \
  Handle<Object> obj;                     \
  const bool dead = IsDead(args.This());  \
  if (!dead) obj = Unwrap(args.This());   \

NAN_PROPERTY_GETTER(WeakNamedPropertyGetter) {
  UNWRAP
  NanReturnValue(dead ? Local<Value>() : obj->Get(property));
}

NAN_PROPERTY_SETTER(WeakNamedPropertySetter) {
  UNWRAP
  if (!dead) obj->Set(p


text:
import * as React from 'react';
import { visualize, story, snap } from 'storybook-snapper';
import { ALIGNMENT, SKIN, Tabs, VARIANT, TabsProps } from '.';
import { TPAComponentsProvider } from '../TPAComponentsConfig';

const items = [0, 1, 2, 4].map((i) => ({ title: `Title ${i}` }));

interface TabsVisualProps {
  tabsProps: TabsProps;
  mobile: boolean;
  compact?: boolean;
}

class TabsVisual extends React.Component<TabsVisualProps> {
  static defaultProps = {
    tabsProps: {},
    mobile: false,
  };

  render() {
    const { tabsProps, mobile, compact } = this.props as any;
    const style = compact ? { margin: '10px', maxWidth: 200 } : undefined;

    return (
      <TPAComponentsProvider value={{ mobile }}>
        <div style={style}>
          <Tabs {...tabsProps} />
        </div>
      </TPAComponentsProvider>
    );
  }
}

visualize('Tabs', () => {
  const renderTest = (renderProps?: any) => {
    const { props, mobile, compact } = renderProps || {};
    return (
      <TabsVisual
        tabsProps={{
          items,
          activeTabIndex: 0,
          ...props,
        }}
        compact={compact}
        mobile={mobile}
      />
    );
  };

  story('basic', () => {
    snap('default', renderTest());

    snap('mobile', renderTest({ mobile: true }));

    snap('with scroll arrows', renderTest({ compact: true }));
  });

  story('Alignments', () => {
    Object.values(ALIGNMENT).map((alignment) => {
      snap(alignment, renderTest({ props: { alignment } }));
    });
  });

  story('Variants', () => {
    Object.values(VARIANT).map((variant) => {
      snap(variant, renderTest({ props: { variant } }));
    });
  });

  story('Skins', () => {
    Object.values(SKIN).map((skin) => {
      snap(skin, renderTest({ props: { skin } }));
    });
  });

  story('Tab link', () => {
    const linkTabs = Array.from({ length: 3 }, (_, index) => ({
      title: `Link tab ${index + 1}`,
      href: `/some-href-${index}`,
    }));

    snap(
      'tab href',
      renderTest({
        props: { items: linkTabs },
      }),
    );
  });
});


text:
package org.apache.curator.framework.recipes.locks;

import org.apache.curator.framework.CuratorFramework;
import java.util.List;

interface LockInternalsDriver extends LockInternalsSorter
{
    public PredicateResults getsTheLock(CuratorFramework client, List<String> children, String sequenceNodeName, int maxLeases) throws Exception;
}


text:
<Alloy>

</Alloy>


text:
package cz.ladicek.annDocuGen.mavenPlugin;

import cz.ladicek.annDocuGen.annotationProcessor.gson.GsonHolder;
import cz.ladicek.annDocuGen.annotationProcessor.model.DocumentationData;
import cz.ladicek.annDocuGen.annotationProcessor.model.DocumentedClass;
import cz.ladicek.annDocuGen.annotationProcessor.model.TypeName;
import cz.ladicek.annDocuGen.annotationProcessor.view.DocumentationWriter;
import cz.ladicek.annDocuGen.annotationProcessor.view.FileCreator;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import org.apache.maven.shared.artifact.filter.PatternIncludesArtifactFilter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

@Mojo(name = "aggregate", defaultPhase = LifecyclePhase.PREPARE_PACKAGE,
        requiresDependencyResolution = ResolutionScope.COMPILE)
public class AnnDocuGenAggregate extends AbstractAnnDocuGenMojo {
    @Parameter(defaultValue = "${project}", required = true, readonly = true)
    private MavenProject project;

    /** Directory where aggregate AnnDocuGen documentation should be generated. */
    @Parameter(property = "annDocuGen.aggregateDirectory",
            defaultValue = "${project.build.directory}/annDocuGen", required = true)
    protected File aggregateDirectory;

    /**
     * A list of dependency patterns for artifacts that will always be included. If such artifact doesn't contain
     * AnnDocuGen output, it will be treated as an error.
     */
    @Parameter
    private List<String> includes;

    /**
     * A list of dependency patterns for artifacts that will always be excluded, even if they contain AnnDocuGen output.
     */
    @Parameter
    private List<String> excludes;

    private ArtifactFilter includesFilter;
    private ArtifactFilter excludesFilter;

    public void execute() throws MojoExecutionException {
        if (skip) {
            getLog().info("Skipping AnnDocuGen aggregation");
            return;
        }

        try {
            setUpFilters();
            List<DocumentationData> allDocumentationData = collectDocumentationData();
            DocumentationData data = aggregate(allDocumentationData);
            FileCreator fileCreator = new MavenPluginFileCreator(aggregateDirectory);
            new DocumentationWriter(data, fileCreator).write();
        } catch (IOException e) {
            failOnError("IOException: Error while creating aggregate", e);
        } catch (AnnDocuGenMissingException e) {
            failOnError("AnnDocuGen missing", e);
        }
    }

    private void setUpFilters() {
        if (includes != null && !includes.isEmpty()) {
            includesFilter = new PatternIncludesArtifactFilter(includes);
        }

        if (excludes != null && !excludes.isEmpty()) {
            // this is in fact correct, as I need to test if an artifact was _included_ in the "exclusion set"
            excludesFilter = new PatternIncludesArtifactFilter(excludes);
        }
    }

    private List<DocumentationData> collectDocumentationData() throws IOException, AnnDocuGenMissingException {
        List<DocumentationData> result = new ArrayList<DocumentationData>();
        for (Artifact artifact : project.getDependencyArtifacts()) {
            boolean includedExplicitly = includesFilter != null && includesFilter.include(artifact);
            boolean excludedExplicitly = excludesFilter != null && excludesFilter.include(artifact);

            if (excludedExplicitly) {
                getLog().info("Artifact " + artifact.getGroupId() + ":" + artifact.getArtifactId()
                        + ":" + artifact.getVersion() + " excluded");
                continue;
            }

            if ("jar".equals(artifact.getType())) {
                File artifactFile = artifact.getFile();
                if (artifactFile != null) {
                    DocumentationData documentationData = readDocumentationDataFromArtifactFile(artifactFile);

                    if (includedExplicitly && documentationData == null) {
                        throw new AnnDocuGenMissingException("Artifact " + artifact.getGroupId() + ":"
                                + artifact.getArtifactId() + ":" + artifact.getVersion()
                                + " doesn't contain AnnDocuGen output, but it was included explicitly");
                    }

                    if (documentationData != null) {
                        getLog().info("Artifact " + artifact.getGroupId() + ":" + artifact.getArtifactId()
                                + ":" + artifact.getVersion() + " included");
                        result.add(documentationData);
                    }
                }
            }
        }
        return result;
    }

    private DocumentationData aggregate(List<DocumentationData> allDocumentationData) {
        Set<TypeName> typeNames = new HashSet<TypeName>(); // for duplicate detection
        List<DocumentedClass> classes = new ArrayList<DocumentedClass>();

        for (DocumentationData documentationData : allDocumentationData) {
            for (DocumentedClass clazz : documentationData.documentedClasses()) {
                if (typeNames.contains(clazz.fullName)) {
                    getLog().warn("Duplicate class " + clazz.fullName + " found");
                } else {
                    typeNames.add(clazz.fullName);
                    classes.add(clazz);
                }
            }
        }

        return new DocumentationData(classes);
    }

    // ---

    private DocumentationData readDocumentationDataFromArtifactFile(File file) throws IOException {
        ZipFile zip = null;
        try {
            zip = new ZipFile(file);
            ZipEntry dataEntry = zip.getEntry("anndocugen-raw-data.json");
            if (dataEntry == null) {
                return null;
            }
            InputStream stream = zip.getInputStream(dataEntry);
            return GsonHolder.instance.fromJson(new InputStreamReader(stream, "utf-8"), DocumentationData.class);
        } finally {
            if (zip != null) {
                zip.close();
            }
        }
    }

    private static final class MavenPluginFileCreator implements FileCreator {
        private final File baseDir;

        private MavenPluginFileCreator(File baseDir) {
            this.baseDir = baseDir;
        }

        @Override
        public OutputStream newOutputStream(String path) throws IOException {
            return new FileOutputStream(ensureDirectoryExists(path));
        }

        @Override
        public Writer newWriter(String path) throws IOException {
            return new OutputStreamWriter(newOutputStream(path), "utf-8");
        }

        private File ensureDirectoryExists(String path) {
            File result = new File(baseDir, path);
            result.getParentFile().mkdirs();
            return result;
        }
    }
}


text:
import itertools
import time
import logging
from myutil.singleton import singleton
from myutil.singleton import Singleton
from tornado.ioloop import IOLoop
from tornado import gen
from tornado.iostream import StreamClosedError
from tornado.tcpserver import TCPServer
from tornado.options import options, define
import tornado.web

def handle_msg( session_id, msg ):
    GameServer().send_msg(session_id, "server send: {}".format(msg))

@singleton
class GameServer(TCPServer):
    def __init__(self):
        # super(GameServer, self).__init__()
        TCPServer.__init__(self)
        self.session_id = itertools.count(1)
        self.m_stream_dict = {}
        self.m_session_dict = {}

    def _on_connect(self, stream):
        if (stream not in self.m_stream_dict):
            next_session_id = next(self.session_id)
            self.m_stream_dict[stream] = next_session_id
            self.m_session_dict[next_session_id] = stream
            logging.info("[%d] new connect", next_session_id)
            return next_session_id

    def _on_disconnect(self, session_id):
        if(session_id in self.m_session_dict):
            stream = self.m_session_dict[session_id]
            del self.m_session_dict[session_id]
            del self.m_stream_dict[stream]
        else:
            logging.error("_on_disconnect error")

    # @gen.coroutine
    def send_msg(self, session_id, msg):
        if(session_id in self.m_session_dict):
            # yield self.m_session_dict[session_id].write(msg.encode("utf-8"))
            self.m_session_dict[session_id].write(msg.encode("utf-8"))
            logging.info("[%d] send msg: %s", session_id, msg)
        else:
            logging.error("[%d] send msg error, msg: %s", session_id, msg)

    @gen.coroutine
    def close(self, session_id, code=1, reason="normal"):
        if (session_id in self.m_session_dict):
            stream = self.m_session_dict[session_id]
            yield stream.write("[{}] close, code = {}, reason = {}\n".format(session_id, code, reason))
            yield stream.close()
        else:
            logging.error("[%d] connect close error, code = %d, reason = %s", session_id, code, reason)

    @gen.coroutine
    def handle_stream(self, stream, address):
        session_id = self._on_connect(stream)
        while True:
            try:
                data = yield stream.read_until(b"\n")
                data_utf8 = data.decode("utf-8")
                logging.info("[%d] recv msg: %s" % (session_id, data_utf8))
                # data = yield stream.read_bytes(read_len)
                handle_msg(session_id, data_utf8)
            except StreamClosedError:
                self._on_disconnect(session_id)
                logging.warning("[%d] disconnect at host %s, port %d", session_id, address[0], address[1] )
                break
            except Exception as e:
                logging.error(e)
            finally:
                pass

@singleton
class call_later_callback(object):
    def __init__(self):
        self.counter = itertools.count(1)

    def heartbeat(self):
        if(next(self.counter) % 60 == 0):
            logging.info("time:%s " % time.strftime('%m-%d %H:%M:%S', time.localtime()))
        IOLoop.current().call_later(1, self.heartbeat)

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("GET: Hello, world")

    def post(self, *args, **kwargs):
        self.write("POST: Hello world")

def start(*, tcp_port=8899, web_port=8888):
    define("tcp_port", default=tcp_port, help="Tcp port to listen on")
    define("web_port", default=web_port, help="Web port to listen on")
    options.parse_command_line()

    server = GameServer()
    server.listen(options.tcp_port)
    server.listen(8800)
    logging.info("Listening on TCP port %d", options.tcp_port)

    application = tornado.web.Application([
        (r"/", MainHandler),
    ])
    application.listen(options.web_port)
    logging.info("Listening on Web port %d", options.web_port)

    # IOLoop.current().call_later(1, call_later_callback().heartbeat)
    IOLoop.current().start()


text:
require 'mongo'

class Mongo::MongoReplicaSetClient

  def most_current_secondary(threshold = 0, prefer_hidden = true)
    replica = self['admin'].command( replSetGetStatus: 1 )
    secondaries = replica['members'].select { |m| m['state'] == 2 }.sort_by { |m| [m['optime'], m['name']] }
    most_current = secondaries.first

    hidden = self['local']['system']['replset'].find_one['members'].select { |mem| mem['hidden'] }.map { |mem| mem['host'] }

    if prefer_hidden && !hidden.include?(most_current['name'])
      secondaries[1..-1].each do |secondary|
        if hidden.include?(secondary['name']) && (most_current['optime'] - secondary['optime']) < threshold
          most_current = secondary
          break
        end
      end
    end

    @mongolly_logger.debug("Found most current secondary #{most_current['name']}, hidden: #{hidden.include? most_current['name']}")
    most_current['name']
  end

protected
  def snapshot_ebs_target(threshold = 0, prefer_hidden = true)
    most_current_secondary(threshold, prefer_hidden)
  end
end


text:
var http = require('http');
var mysql = require('mysql');
var express = require('express');
var app = express();
var exec = require('child_process').execFile;

var mysqlurl
if (process.env.VCAP_SERVICES) {
    var vcapenv = JSON.parse(process.env.VCAP_SERVICES);
    console.log("env")
    var found=false
    var vcapkeys = Object.keys(vcapenv)
    vcapkeys.forEach(function(vcapkey) {
        newObj = vcapenv[vcapkey]
        //crude, ok for now as it has to work with various service names
        tempjson = vcapenv[vcapkey][0];
        mysqlurl = tempjson["credentials"]
        return
    })
    console.log("mysqlurl")
    console.log(mysqlurl)
} else {
    var connStr = '{ \
            "name": "mytest",\
            "hostname": "localhost",\
            "host": "localhost",\
            "port": 3306,\
            "user": "docker",\
            "username": "docker",\
            "password": "docker",\
            "uri": "mysql://docker:docker@localhost:3306/mytest",\
            "database": "mytest"\
         }';
     mysqlurl = JSON.parse(connStr);
}
app.set('mysql_url', mysqlurl);
app.set('port', process.env.PORT || 3000);

console.log(app.get('mysql_url'));
// Create a connection to MySql Server and Database
var connection = mysql.createConnection(
    app.get('mysql_url')
);

app.get('/hello', function(req, res){
  res.send('Hello World'+JSON.stringify(app.get('mysql_url')));
});

app.get('/petinfo', function(req, res) {
    connection.query("SELECT * from PET", function(err, rows) {
        if (err != null) {
            res.end("Query error:" + err);
        } else {
            res.send(JSON.stringify(rows));
        }
    });
});

var populate_tables=function () {
    fs = require('fs')
    fs.readFile('./setup.sql', 'utf8', function (err,data) {
        if (err) {
            return console.log(err);
        }
        var stmts = data.split(";")
        for (i=0;i<stmts.length;i++) {
            connection.query(stmts[i], function(err, rows) {
                if (err != null) {
                    console.log("Query error:" + err);
                } else {
                    console.log("Success in setup")
                }
            });
         }
    });
}

var server = app.listen(app.get('port'), function() {
//http.createServer(app).listen(app.get('port'), function(){
    connection.connect(function(err) {
        if(err != null) {
            console.log('Error connecting to mysql:' + err+'\n');
        }
    });
    populate_tables();
//   console.log('Express server listening on port ' + app.get('port'));
    console.log('Listening on port %d', server.address().port);
});


text:
import sys
import codecs
from nltk import FreqDist

def main():
	args = sys.argv
	input_file = codecs.open(args[1], 'r', 'utf-8')
	fd = FreqDist()
	for line in input_file:
		tokens = line.split(" ")
		for token in tokens:
			fd[token.lower()] += 1

	print "Number of unique occurrences = ", fd.B()

if __name__ == "__main__":
	main()


text:
package com.github.mpilquist.locals

import scala.tools.nsc
import nsc.{ Global, Phase }
import nsc.plugins.{ Plugin, PluginComponent }
import nsc.transform.Transform
import nsc.symtab.Flags._
import nsc.ast.TreeDSL

class LocalImplicitsPlugin(val global: Global) extends Plugin {
  val name = "local-implicits"
  val description = "Introduces syntax for locally scoped implicits"
  val components = new LocalImplicitsTransform(this, global) :: Nil
}

class LocalImplicitsTransform(plugin: Plugin, val global: Global) extends PluginComponent with Transform with TreeDSL {
  import global._

  val runsAfter = "parser" :: Nil
  val phaseName = "local-implicit-scoper"

  val ImplyName = TermName("imply")

  def newTransformer(unit: CompilationUnit) = new Transformer() {
    override def transform(tree: Tree): Tree = {
      tree match {
        case Apply(Apply(Ident(ImplyName), implicits), blocks) =>
          if (blocks.size == 1) super.transform(expandImplicits(implicits, blocks.head))
          else super.transform(tree)

        case other => super.transform(other)
      }
    }
  }

  private def expandImplicits(implicits: List[Tree], block: Tree): Tree = {
    val implicitVals = implicits.zipWithIndex map { case (imp, idx) =>
      ValDef(Modifiers(IMPLICIT), TermName("implied$" + idx), TypeTree(), imp)
    }
    Block(implicitVals, block)
  }
}


text:
package softuni.controller;

import com.mvcFramework.annotations.controller.Controller;
import com.mvcFramework.annotations.parameters.RequestParam;
import com.mvcFramework.annotations.request.GetMapping;
import com.mvcFramework.annotations.request.PostMapping;
import com.mvcFramework.models.Model;
import softuni.models.bindingModels.ArticleModel;
import softuni.models.bindingModels.UserModel;
import softuni.services.ArticleService;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.servlet.http.HttpSession;
import java.util.List;

@Stateless
@Controller
public class ArticleCreateController {

    @Inject
    private ArticleService articleService;

    @GetMapping("/article/create-article")
    public String details(Model model, HttpSession session){

        model.addAttribute("title", "New Article");

        UserModel userModel = (UserModel) session.getAttribute("loggedUser");

        if (userModel != null) {

            model.addAttribute("view", "article/create-article.jsp");
        } else {

            model.addAttribute("view", "home/index.jsp");
        }

        return "base-layout";
    }

    @PostMapping("/article/create-article")
    public String processArticle(@RequestParam("title") String title,
                                 @RequestParam("content") String content,
                                 HttpSession session,
                                 Model model) {

        UserModel userModel = (UserModel) session.getAttribute("loggedUser");
        ArticleModel article = this.articleService.create(title, content, userModel);

        if (article.getTitle() == null || article.getContent() == null) {

            List<String> errors = article.getErrors();

            if (errors.size() > 0) {

                model.addAttribute("errors", errors);
            }
        }

        return "redirect:/";
    }
}


text:
<?php
declare(strict_types = 1);

namespace Domain\Repository;

use Domain\{
    Entity\Citation\Identity,
    Entity\Citation,
    Specification\Citation\Specification,
    Exception\CitationNotFound,
};
use Innmind\Immutable\Set;

interface CitationRepository
{
    /**
     * @throws CitationNotFound
     */
    public function get(Identity $identity): Citation;
    public function add(Citation $citation): self;
    public function remove(Identity $identity): self;
    public function has(Identity $identity): bool;
    public function count(): int;

    /**
     * @return Set<Citation>
     */
    public function all(): Set;

    /**
     * @return Set<Citation>
     */
    public function matching(Specification $specification): Set;
}


text:
const createElement = (type, props, children) => {
  return { type, props, children };
};

function render() {
  return [
    createElement("import", {
      "src": "./item.wxml"
    }, null),
    createElement("template", {
      "is": "item",
      "data": "{{text: 'forbar'}}"
    }, null),
    createElement("view", {
      "class": "login"
    }, [createElement("text", {
        "class": "h1 title center"
      }, ["login"]),
      createElement("form", {
        "bindsubmit": "onLogin"
      }, [createElement("input", {
          "name": "username",
          "type": "text",
          "placeholder": "username"
        }, null),
        createElement("input", {
          "name": "password",
          "type": "password",
          "placeholder": "password"
        }, null),
        createElement("button", {
          "type": "primary",
          "formType": "submit"
        }, ["login"])
      ]),
      createElement("navigator", {
        "class": "join"
      }, ["join us?"])
    ])
  ];
}

console.log(render());


text:
/**
  *Used to export symbols for win systems
  */

#if(UNIX)
    #ifdef lms_EXPORTS
     #define lms_EXPORT __declspec(dllexport)
    #else
     #define lms_EXPORT __declspec(dllimport)
    #endif
#else
    #define lms_EXPORT
#endif


text:
namespace blink {

class CSSAnimationData final : public CSSTimingData {
 public:
  CSSAnimationData();
  explicit CSSAnimationData(const CSSAnimationData&);

  std::unique_ptr<CSSAnimationData> Clone() const {
    return base::WrapUnique(new CSSAnimationData(*this));
  }

  bool AnimationsMatchForStyleRecalc(const CSSAnimationData& other) const;
  bool operator==(const CSSAnimationData& other) const {
    return AnimationsMatchForStyleRecalc(other);
  }

  Timing ConvertToTiming(size_t index) const;

  const Vector<AtomicString>& NameList() const { return name_list_; }
  const Vector<double>& IterationCountList() const {
    return iteration_count_list_;
  }
  const Vector<Timing::PlaybackDirection>& DirectionList() const {
    return direction_list_;
  }
  const Vector<Timing::FillMode>& FillModeList() const {
    return fill_mode_list_;
  }
  const Vector<EAnimPlayState>& PlayStateList() const {
    return play_state_list_;
  }

  Vector<AtomicString>& NameList() { return name_list_; }
  Vector<double>& IterationCountList() { return iteration_count_list_; }
  Vector<Timing::PlaybackDirection>& DirectionList() { return direction_list_; }
  Vector<Timing::FillMode>& FillModeList() { return fill_mode_list_; }
  Vector<EAnimPlayState>& PlayStateList() { return play_state_list_; }

  static const AtomicString& InitialName();
  static Timing::PlaybackDirection InitialDirection() {
    return Timing::PlaybackDirection::NORMAL;
  }
  static Timing::FillMode InitialFillMode() { return Timing::FillMode::NONE; }
  static double InitialIterationCount() { return 1.0; }
  static EAnimPlayState InitialPlayState() { return EAnimPlayState::kPlaying; }

 private:
  Vector<AtomicString> name_list_;
  Vector<double> iteration_count_list_;
  Vector<Timing::PlaybackDirection> direction_list_;
  Vector<Timing::FillMode> fill_mode_list_;
  Vector<EAnimPlayState> play_state_list_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_CSS_CSS_ANIMATION_DATA_H_


text:
#include "berryBlueBerryTestDriver.h"

#include "internal/berryTestRegistry.h"

#include "cppunit/TestRunner.h"
#include "cppunit/TestResult.h"
#include "cppunit/TestResultCollector.h"

namespace berry
{

BlueBerryTestDriver::BlueBerryTestDriver(
    const QList<ITestDescriptor::Pointer>& descriptors,
    bool uitests,
    const QString& testName,
    bool wait)
  : descriptors(descriptors)
  , uitests(uitests)
  , testName(testName)
  , wait(wait)
{

}

int BlueBerryTestDriver::Run()
{
  CppUnit::TestRunner runner;

  unsigned int testCounter = 0;
  foreach (const ITestDescriptor::Pointer& descr, descriptors)
  {
    if (descr->IsUITest() == uitests)
    {
      CppUnit::Test* test = descr->CreateTest();
      runner.addTest(test);
      ++testCounter;
    }
  }

  if (testCounter == 0)
  {
    std::cout << "No " << (uitests ? "UI " : "") << "tests registered."
        << std::endl;
    return 0;
  }

  /*
  std::vector<std::string> args;
  args.push_back("BlueBerryTestDriver");
  if (testName.empty())
    args.push_back("-all");
  else
    args.push_back(testName);
  if (wait)
    args.push_back("-wait");

  return runner.run(args) ? 0 : 1;
  */

  CppUnit::TestResult controller;

  CppUnit::TestResultCollector result;
  controller.addListener(&result);

  runner.run(controller);
  return result.wasSuccessful() ? 0 : 1;
}

int BlueBerryTestDriver::Run(const QString& pluginId, bool uitests)
{
  TestRegistry testRegistry;
  const QList<ITestDescriptor::Pointer>& tests = testRegistry.GetTestsForId(
      pluginId);

  BlueBerryTestDriver driver(tests, uitests);
  return driver.Run();
}

}


text:
/*!
 * Fi-ware web style
 *
 *
 * 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.
 * ========================================================== */

!function ($) {

  "use strict"; // jshint ;_;

 /* CAROUSEL CLASS DEFINITION
  * ========================= */

  var Carousel = function (element, options) {
    this.$element = $(element)
    this.options = options
    this.options.slide && this.slide(this.options.slide)
    this.options.pause == 'hover' && this.$element
      .on('mouseenter', $.proxy(this.pause, this))
      .on('mouseleave', $.proxy(this.cycle, this))
  }

  Carousel.prototype = {

    cycle: function (e) {
      if (!e) this.paused = false
      this.options.interval
        && !this.paused
        && (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
      return this
    }

  , to: function (pos) {
      var $active = this.$element.find('.active')
        , children = $active.parent().children()
        , activePos = children.index($active)
        , that = this

      if (pos > (children.length - 1) || pos < 0) return

      if (this.sliding) {
        return this.$element.one('slid', function () {
          that.to(pos)
        })
      }

      if (activePos == pos) {
        return this.pause().cycle()
      }

      return this.slide(pos > activePos ? 'next' : 'prev', $(children[pos]))
    }

  , pause: function (e) {
      if (!e) this.paused = true
      clearInterval(this.interval)
      this.interval = null
      return this
    }

  , next: function () {
      if (this.sliding) return
      return this.slide('next')
    }

  , prev: function () {
      if (this.sliding) return
      return this.slide('prev')
    }

  , slide: function (type, next) {
      var $active = this.$element.find('.active')
        , $next = next || $active[type]()
        , isCycling = this.interval
        , direction = type == 'next' ? 'left' : 'right'
        , fallback  = type == 'next' ? 'first' : 'last'
        , that = this
        , e = $.Event('slide')

      this.sliding = true

      isCycling && this.pause()

      $next = $next.length ? $next : this.$element.find('.item')[fallback]()

      if ($next.hasClass('active')) return

      if ($.support.transition && this.$element.hasClass('slide')) {
        this.$element.trigger(e)
        if (e.isDefaultPrevented()) return
        $next.addClass(type)
        $next[0].offsetWidth // force reflow
        $active.addClass(direction)
        $next.addClass(direction)
        this.$element.one($.support.transition.end, function () {
          $next.removeClass([type, direction].join(' ')).addClass('active')
          $active.removeClass(['active', direction].join(' '))
          that.sliding = false
          setTimeout(function () { that.$element.trigger('slid') }, 0)
        })
      } else {
        this.$element.trigger(e)
        if (e.isDefaultPrevented()) return
        $active.removeClass('active')
        $next.addClass('active')
        this.sliding = false
        this.$element.trigger('slid')
      }

      isCycling && this.cycle()

      return this
    }

  }

 /* CAROUSEL PLUGIN DEFINITION
  * ========================== */

  $.fn.carousel = function (option) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('carousel')
        , options = $.extend({}, $.fn.carousel.defaults, typeof option == 'object' && option)
      if (!data) $this.data('carousel', (data = new Carousel(this, options)))
      if (typeof option == 'number') data.to(option)
      else if (typeof option == 'string' || (option = options.slide)) data[option]()
      else if (options.interval) data.cycle()
    })
  }

  $.fn.carousel.defaults = {
    interval: 5000
  , pause: 'hover'
  }

  $.fn.carousel.Constructor = Carousel

 /* CAROUSEL DATA-API
  * ================= */

  $(function () {
    $('body').on('click.carousel.data-api', '[data-slide]', function ( e ) {
      var $this = $(this), href
        , $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
        , options = !$target.data('modal') && $.extend({}, $target.data(), $this.data())
      $target.carousel(options)
      e.preventDefault()
    })
  })

}(window.jQuery);