text:
layout:	post
author: Asim Aslam
title:	"Micro 3.0 (M3O) is a platform for cloud native development"
date:	2020-11-05 10:00:00
---

This is the official announcement for the release of Micro 3.0 better known as M3O - a platform for cloud native development.
Our 3.0 release is a major refactor and consolidation of the existing tooling into something that addresses the entire workflow
of build, run, manage and consume all from the developers perspective.

Read on to learn more or go straight to the [latest release](https://github.com/micro/micro/releases/latest).
Head to [m3o.com](https://m3o.com) for the hosted offering.

## Overview

Micro focuses on developer productivity for the backend. It's clear that the Cloud has become infinitely more complex
over the past few years. Micro attempts to create order out of that chaos by distilling it all down to a handful of
primitives for distributed systems development.

Why should you care? If you're reading this you've no doubt encountered the tedious nature of infrastructure management,
wrangling a kubernetes cluster on AWS or the thousands of things you need to do to cobble together a platform before
starting to build a product. We think we've nailed the solution for that just as Android did for Mobile. Keep reading
if you want to find out more.

## Quick Flashback

Micro started out as a [toolkit for microservices](/blog/2016/03/20/micro.html) development,
incorporating an api gateway, web dashboard and cli to interact with services built using a Go RPC framework.
Back then it felt like getting anyone to buy into PaaS again was going to be a losing battle. So we chose
to write single purpose tools around an RPC framework thinking it might allow people to adopt it piece by piece
until they saw the need for a platform. It was really straight forward right until it wasn't.

There was a simple Go framework plus some surrounding
components to query and interact with them, but like any long lived project, the complexity grew as we
tried to solve for that platform experience that just couldn't be done with a swiss army knife. The repo
exploded with a number of independent libraries. To the creator its obvious what these are all for but to
the user there is nothing but cognitive overload.

In 2019 we went through a [consolidation](/blog/2019/06/10/the-great-consolidation.html) of all those libraries
which helped tremendously but there was still always one outstanding question. What's the difference between
[micro](https://github.com/micro/micro) and [go-micro](https://github.com/micro/go-micro)? It's a good
question and one we've covered before. We saw go-micro as a framework and micro as a toolkit but these
words were basically empty and meaningless because multiple projects working in coordination really need a
crisp story that makes sense and we didn't have one.

In 2020 we're looking to rectify that but let's first let's talk about platforms.

## PaaS in 2020

5 years ago the world exploded with a proliferation of "cloud native" tooling as containers and
container orchestration took centre stage. More specifically, Docker and Kubernetes redefined the
technology landscape along with a more conscious move towards building software in the cloud.

Micro took a forward looking view even as far back as 2015. It was clear distributed systems and cloud native
was going to become the dominant model for backend services development over the coming years but, what wasn't clear
is just how long we'd spend wrangling all sorts tools like docker, kubernetes, grpc, istio and everything else.
It felt like we were rebuilding the stack and weren't really ready to talk about development aspects of it all.

In fact at that time, people mostly wanted to kick the tyres on all these tools and piece something together.
Running kubernetes yourself became all the rage and even using service mesh as the holy grail for solving
all your distributed systems problems. Many of us have come to realise while all of this tech is fun
it's not actually solving development problems.

We've gotten to the point of managed kubernetes and even things like Google Cloud Run or DigitalOcean App
Platform, but none of these things are helping with a development model for a cloud native era. Our
frustrations with the existing developer experience have grown and Micro felt like something that
could solve for all that, but only if we took a drastic step to overhaul it.

We think PaaS 3.0 is not just about running your container or even your source code but something that
encapsulates the entire developer experience including a model for writing code for the cloud. Based on that
Micro 3.0 aka M3O is a platform for cloud native development.

## What even is Cloud Native?

What is cloud native? What does it mean to build for the cloud? What is a cloud service?

Cloud native is basically a descriptive term for something that was built to run in the cloud. That's it. It's not
magic, it might sound like a buzzword, but the reality is it simply means, that piece of software was built
to run in the cloud. How does that differ from the way we used to build before? Well the idea behind the cloud
is that its ephemeral, scalable and everything can be accessed via an API.

Our expectation for services running in the cloud is that they're mostly stateless, leveraging external services
for the persistence, that they are identified by name rather than IP address and they themselves provide an
API that can be consumed by multiple clients such as web, mobile and cli or other services.

Cloud native applications are horizontally scalable and operate within domain boundaries that divide them as
separate apps which communicate over the network via their APIs rather than as one monolithic entity.
We think cloud services require a fundamentally different approach to software creation and why Micro 3.0
was designed with this in mind.

## Micro 3.0 aka M3O

Micro 3.0 (M3O) reimagines Micro as a platform for cloud native development. What does that mean? Well we think of
it as PaaS 3.0, a complete solution for source to running and beyond. Micro has moved from just being a Go
framework to incorporating a standalone server and hosted platform. Our hosted offering is called
[M3O](https://m3o.com), a hat tip to Micro 3.0 or M[icr]o, whichever way you want to see it.

Another way to think about it. What Git is to GitHub, Micro is to the M3O platform. Let's dig into it.

Micro 3.0 includes the following.

### Server

The server is our abstraction for cloud infrastructure and underlying systems you might need for writing
distributed systems. The server encapsulates all of these concerns as gRPC services which you can
query via any language. The goal here is to say developers don't really need to be thinking about infrastructure
but what they do need is design patterns and primitives for building distributed systems.

<img src="/images/micro-3.0.png" />

The server includes the following:

- **Authentication**: Auth whether its authentication or authorization is part of the system. Create JWT tokens, define access rules, use one system to govern everything in a simple and straight forward manner. Whether it's for a user or a service.

- **Configuration**: Dynamic config management allows you to store relevant config that needs to be updated without having to restart services. Throw API keys and business logic related configuration into the secure config service and let your services pick up the changes.

- **Key-Value Storage**: We're focused on best practices for microservices development which means keeping services mostly stateless. To do this we're providing persistent storage on the platform. Key-Value allows you to rapidly write code and store data in the format you care about.

- **Event Streaming**: Distributed systems are fundamentally in need of an event driven architecture to breakdown the tight dependencies between them. Using event streaming and pubsub allows you to publish and subscribe to relevant events async.

- **Service Registry**: Micro and M3O bake in service discovery so you can browse a directory of services to explore your service APIs and enable you to query services by name. Micro is all about microservices and multi-service development.

- **Service Network**: Because you don't want to have to resolve those service names to addresses and deal with the load balancing aspect, the server bakes in a "service mesh" which will handle your inter-service requests (as gRPC) and route to the
appropriate instance.

- **Identity Proxy**: We include a separate identity proxy for external requests using gRPC via the CLI and other means. This enables you to query from your local machine or anywhere else using valid auth credentials and have it seamlessly work as if
you were in the platform itself.

- **API Gateway**: Finally there's an API gateway that automatically exposes your services to the outside world over HTTP. Internally writing service to service using gRPC makes sense, but at the end of the day we want to build APIs consumed from clients via HTTP.

### Clients

The server provides inter-service communication and two means of external communication with a HTTP API and gRPC proxy but that
experience is made much better when there's user experience on the client side that works. Right now we've got two ways of doing this.

- **Command Line**: The CLI provides a convenient and simple way to talk to the server via gRPC requests through the proxy.
The most convenient commands are builtin but every service you write also gets beautiful dynamic generated commands
for each endpoint.

- **gRPC SDKs**: Every service in the server is accessible via gRPC. We're code generating clients for the server itself
so you can access them from any language. What this enables is a wide array of experiences on the client side without
having to handcraft libraries for each language.

- **Web Interface**: Coming soon is a dynamically generated web interface that creates a simple query mechanism through a
browser for any of your services. We've got a http api, gRPC proxy and command line interface but feel like the browser
could use some love too.

### Framework

One thing we really understood from our time working on go-micro was that the developer experience really matters. We
see Go as the dominant language for the cloud and believe most backend services in the cloud will be written in Go. For
that reason we continue to include a Service Framework which acts as a framework for building your services and accessing
the underlying systems of the server.

The Service Framework provides pre-initialised packages for all of the features of the server and creates a convenient
initialiser for defining your own services starting with `service.New`. A Service has a name, endpoints, contains
a server of its own and a client to query other services. The framework does enough for you but then attempts to
get out of your way so the rest is up to you.

A main package for a Micro service looks something like this

```go
package main

import (
	"github.com/micro/micro/v3/service"
	"github.com/micro/micro/v3/service/logger"
	"github.com/micro/services/helloworld/handler"
)

func main() {
	// Create service
	srv := service.New(
		service.Name("helloworld"),
	)

	// Register Handler
	srv.Handle(new(handler.Helloworld))

	// Run the service
	if err := srv.Run(); err != nil {
		logger.Fatal(err)
	}
}
```

When you want to make use of something like the Config service just import it like so.

```go
import "github.com/micro/micro/v3/service/config"

val, err := config.Get("key")
```

You can find many more examples in [github.com/micro/services](https://github.com/micro/services).

## Environments

From our experience writing software isn't constrained to a single environment. Most of the time we're doing
some form of local development followed by a push to staging and then production. We don't really see tools
capturing that workflow effectively. Thinking about how to do this now we've built in environments as
a first class system.

M3O offers 3 builtin environments; local, dev and platform.

- **Local** - is Micro running on your local machine
- **Dev** - is a free development environment in the cloud
- **Platform** - is a paid secure, scalable and supported production environment

Our goal here is to really direct the flow from local > dev > platform as the lifecycle for any backend service
development. Start by running the server locally, writing your code and getting it to work. Ship it to the
dev environment for further testing but also to collaborate with others and serve it publicly. Then if you're
interested in a scalable and supported production environment, pay for the platform environment. That's it.

Interact with the environments like so.

```sh
# view the environments
micro env

# set the environment
micro env set dev

# add a new environment
micro env add foobar proxy.foo.com:443
```

Micro isn't constrained to our built in environments. You can add others as you wish.

### Local Environment

The local environment is just that, your local laptop. Its where development starts and normally
this requires you to run all sorts of crazy infrastructure. Micro focuses on providing pluggable
abstractions as gRPC services so your service just talks gRPC directly to Micro and we hide the
details from you. Locally that means we're using best effort stuff like mdns, file storage, etc.

We've almost made it drop dead simple to start locally. You just run one command.

```sh
micro server
```

This will boot all the services you need and let you build a service that will look identical
in any cloud environment running Micro as a Service.

Set your environment to the local server when using it.

```sh
micro env set local
```

Curl `localhost:8080` with your namespace

```sh
curl -H "Micro-Namespace: $NAMESPACE" "http://localhost:8080/helloworld?name=Alice"
```

Get your namespace like so

```sh
micro user namespace
```

This might be blank locally but you'll get the idea for how namespace isolation works in a bit.

### Dev Environment

The 'dev' environment is a free cloud hosted environment that provides Micro 3.0 as a Service. What we've
learned in the past few years is that open source is not enough. There's some great open source tools out there
but as soon as we get to deployment there's so many hurdles to overcome. The dev enviroment provides
everyone the ability to get up and running in minutes with the same tools you'd use for local development
in the cloud.

All you have to do is set the env to 'dev' and use it like local.

If you're using the dev environment URLs are `*.m3o.dev`. Find more details at [m3o.dev](https://m3o.dev)

### Platform Environment

The 'platform' environment is a secure, scalable and supported production environment for where you'd likely
run customer facing services and products. This is a paid tier with 2x the resource limits of dev to start
including slack & email support along with SLAs. You can think of it as the equivalent of a production platform
you've come to know at any work place.

Our goal with Local, Dev and Platform is to invoke that workflow we've all come to know and expect as a real
product. These are totally separate environments and they're managed exactly as that with M3O as well.

## Multi-Tenancy and Namespacing

With the advent of a system like kubernetes and a push towards the cloud we can see that there's really a need
to move towards shared resource usage. The cloud isn't cheap and we don't all need to be running separate
kubernetes clusters. In fact wouldn't it be great if we could share that? Well Micro is doing it. We build in
multi-tenancy using the same logic kubernetes does called Namespaces.

We've mapped this same experience locally so you get a rudimentary form of namespacing for local dev but
mostly we're making use of kubernetes namespaces in production along with a whole host of custom written
isolation mechanisms for authentication, storage, configuration, event streaming, etc so Micro 3.0
can be used to host more than one tenant.

Whether you decide to self host and share your cluster for dev, staging and production we felt like
multi-tenancy needs to become a defacto standard in 2020. How it works in practice. Each tenant
get's a namespace. That namespace has its own isolated set of users and resources in each subsystem.
When you make any request as a user or service, a JWT token is passed with that so the
underlying systems can route to the appropriate resources.

Once you've signed up to the dev environment your namespace will be set for you. You can get it using
the command

```sh
micro user namespace
```

When you're using any sort of CLI commands, your namespace and auth token are automatically injected
into request including refreshing those tokens. The same happens for any of your services running
on Micro. If you want to use the http API or the public api url [api.m3o.dev] then go ahead
and grab your namespace and set the header as `Micro-Namespace`.

Additionally each namespace gets its own custom domain so the `foobar` namespace becomes `foobar.m3o.dev`
with say the helloworld service routing would be to `foobar.m3o.dev/helloworld`.

## Source to Running

Micro was built out of a frustration with the existing tools out there. One of the things I've really
been saying for a long time is that I wanted "source to running" in just one command. With
Heroku we sort of got that but it really took too much away from us. Back in 2010 Heroku was focused
on monolithic Rails development. Since then I've really said Heroku took too much away and AWS gave
too much back. We needed something in between.

Micro can take your source code, from a local directory or a repo thats hosted on github, gitlab or bitbucket.
In one command it will upload or pull from the relevant place, package it as a container and
run it. That's it. Source to running in just one command. No more need to deal with the pipeline,
no more hacking away at containers and the container registries. Write some code and run it.

## Development Model

Source to running is cool. It's what a PaaS is really for but one thing that's really been lacking even
with the new PaaS boom is a development model. As I eluded to, Heroku takes too much away and AWS
gives too much back. We're looking for a happy medium. One that doesn't require us to rely on VMs or
containers but on the other side doesn't limit us to monolithic development.

Micro has always focused on the practice of distributed systems development or microservices. The idea
of breaking down large monolithic apps into smaller separate services that do one thing well. To do
this we think you really have to bake the development model into the platform.

What we include is the concept of a Service which contains a Client and Server for both handling
requests and making queries to other services. We focus on standardisation around protobuf for API
definitions and using gRPC for the networking layering.

Not only that we're including pubsub for an event streaming architecture and other pieces like
nosql key-value storage and dynamic config management. We believe there are specific primitives
required to start building microservices and distributed systems and that's what Micro looks
to provide.

## Multi Language Clients

One of the key learnings we had from the development of a Go framework called [go-micro](https://github.com/asim/go-micro) was
that we mostly use a single language for each platform we develop for such as web, mobile and so on. Cloud will be no different.
We support Go for the Cloud, but think there needs to be an ecosystem for consumption of Go services and potentially extending beyond
where there's no way around using python, java, ruby, rust or javascript. Because Micro's interface is gRPC we code generate gRPC
clients and allow any language to leverage the Micro server.

In the past multi-language clients have been pain stakingly hand crafted and one thing we learned from building a framework,
it's incredibly hard to replicate this across languages also. With gRPC we've really found a happy medium of saying, there's
a built in service framework you can use to write code really elegantly with Go but gRPC allows us to reduce the scope of the
surface area and provide strongly typed clients that can support a different model of development, one that might have
more scope for pushing microservices to wide scale adoption in a way that wasn't possible with frameworks.

We additionally include grpc-web generated clients which enable frontend to quickly and easily make use of typed javascript
clients to leverage the same development as the backend. We've seen grpc-web slowly gain adoption internally at various
companies and think this might extend to the public domain fairly rapidly as well.

See the [micro/client/sdk](https://github.com/micro/micro/tree/master/client/sdk) directory for the generated clients. These will be
pubished to their respective package managers in the near future.

## Building API First Services

Micro was built to make microservices development much easier and to increase developer productivity on the backend, beyond
being able to consume those services using gRPC we think the world still really cares about HTTP/JSON based APIs and so
Micro include an API gateway which translates http/json to grpc requests automatically. This means everyone is building
API first services in the cloud without having to do anything.

Here's a quick example.

Say you write helloworld on the backend with the following proto

```proto
syntax = "proto3";

package helloworld;

service Helloworld {
	rpc Message(Request) returns (Response) {}
}

message Request {
	string name = 1;
}

message Response {
	string msg = 1;
}
```

Then expose this as the "helloworld" service on the M3O platform. You'll instantly be able to access this as $namespace.m3o.dev/helloworld/message

We use path based resolution to map a http request to gRPC. So /[service]/[method] becomes [Service.Method]. If your microservice name doesn't match
the proto for whatever reason (you have multiple proto Services) then it works slightly differently e.g your service name is foobar then the endpoint
becomes `/foobar/helloworld/message`.

One neat hack we've picked up from web browser is auto detecting an endpoint so we can shorthand something to something like /helloworld. With the web
if an index.html page is found its served. In our case if we find the `Call` method in your proto we'll automatically use it so /helloworld/call just
shortens to /helloworld.

With Stripe, Twilio, Segment and others become huge API players, we think the world is going in that direction and you are probably building http apis
too. So Micro builds in this in as a first class primitive. In future we'll also look to include support for graphql.

## Ten Commands

Alright so we talk a good game, but how easy is it? Well lets show you.

```sh
# Install the micro binary
curl -fsSL https://install.m3o.com/micro | /bin/bash

# Set env to dev for the free environment in the cloud
micro env set dev

# Signup before getting started
micro signup

# Create a new service (follow the instructions and push to Github)
micro new helloworld

# Deploy the service from github
micro run github.com/micro/services/helloworld

# Check the service status
micro status

# Query the logs
micro logs helloworld

# Call the service
micro helloworld --name=Alice

# Get your namespace
NAMESPACE=$(micro user namespace)

# Call service via the public http API
curl "https://$NAMESPACE.m3o.dev/helloworld?name=Alice"
```

Easy right? We see this as the common flow for most service development. Its a fast iterative loop
from generating a new template to shipping it and querying to make sure it works. There's
additional stuff in the developer experience like actually writing the service but we think that's
a separate post.

## Documentation

Another thing we really learned from the past is nothing like this works without great documentation
and tutorials. So we've written a whole suite of docs for Micro available at [micro.mu](https://micro.dev)
and provide help for using the M3O on [m3o.dev](https://m3o.dev/).

You can find other interesting resources at [Awesome Micro](https://github.com/micro/awesome-micro).

## Licensing

Micro continues to remain open source but licensed using [Polyform Shield](https://polyformproject.org/licenses/shield/1.0.0/)
which prevents the software for being picked up and run as a service. This is to contend with AWS and others
running open source for profit without contributing back. It's a longer conversation for another day.

## Motivations

We really believe that writing software for the cloud is too hard. That there's far too much choice and
time wasted focusing on how to piece everything together. There are tradeoffs to adopting a PaaS but
ultimately our focus is **developer productivity**. By choosing one tool and one way we stop thinking
about the how and just get down to what we're trying to build.

M3O and Micro 3.0 look at the state of distributed systems development in the cloud native era and
try to drastically simplify that experience with a platform that bakes in the development model
so you can just get back to writing code.

## Deprecating Go Micro

We will now be ending support for [go-micro](https://github.com/micro/go-micro). Having personally
spent 6 years since inception on go-micro I feel as though its time to finally let it go. What
started as a tiny library to help write Kubernetes-as-a-Service back in 2014 turned into a widely
used open source framework for Go microservices development. Having now amassed more than 14k stars
you might wonder why we leave it behind. The truth is, while it solved a problem for many it never
became what it was intended for.

Go Micro was built on the premise that developers need a simpler way to build distributed systems.
With strongly defined abstractions and a pluggable architecture it did that well but that became
really unwieldy to manage. With an MxN matrix of complexity, Go Micro became the thing it was
trying to fight against. As we attempted to hone on this platform effort, it just became very
clear that to do that we'd need to start fresh.

Go Micro will live on as an independent library under my own personal account on GitHub but
it will no longer be supported as an official Micro project. Hopefully it finds second life in
some other ways but for now we say goodbye.

If you'd like to upgrade from Go Micro v2 to Micro v3 please see this [upgrade guide](/v2-to-v3-upgrade-guide).

## Next Steps

You can use the Micro 3.O as a self-hosted open source solution locally, on a VPS or managed kubernetes,
whatever works for you. Our goal is to facilitate a vastly superior developer experience for building
services in the Cloud. Come join [Discord](https://discord.gg/hbmJEct) or [Slack](https://slack.m3o.com)
to chat more about it. And lastly head to to [m3o.com](https://m3o.com) if you're tired of the way you're
building software for today and want to learn of a better way that's going to make you 10x more productive.

So to revisit. To get started for free in the cloud based dev environment just run the following commands.

```sh
# Install the micro binary
curl -fsSL https://install.m3o.com/micro | /bin/bash

# Set the env to the dev environment
micro env set dev

# Signup before getting started
micro signup

# Create a new service (follow the instructions and push to Github)
micro new helloworld

# Deploy the service from github
micro run github.com/micro/services/helloworld

# Check the service status
micro status

# Query the logs
micro logs helloworld

# Call the service
micro helloworld --name=Alice

# Get your namespace
NAMESPACE=$(micro user namespace)

# Curl it via the public http API
curl "https://$NAMESPACE.m3o.dev/helloworld?name=Alice"
```

If you want to test things out locally first

```sh
# start the server locally
micro server

# set the environment to local
micro env set local

# login using user: admin pass: micro
micro login
```

And that's it! Please come chat with us in [Discord](https://discord.gg/hbmJEct) or [Slack](https://slack.m3o.com) and
[invite friends](https://m3o.dev/getting-started/invite-users) to test out the M3O platform.

To learn more about the M3O platform see the dev docs at [m3o.dev](https://m3o.dev). And for the open source docs
check out [micro.mu](https://micro.dev).

<br>
*Written by Asim Aslam*
<br>
Founder & CEO Micro


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Cat. Lich. Univers. 1: 505 (1922)

#### Original name
Trypethelium oligosporum Mont. & Bosch

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Random Destination Finder</title>

    <link rel="stylesheet" type="text/css" href="lib/css/bootstrap.min.css" />
    <link href="css/main.css" rel="stylesheet">
    <link rel="icon" type="image/ico" href="favicon.ico">

Home

About

Where to?

Where you are flying from?

            <input id="origin" type="text" class="form-control" placeholder="Start typing airport code/name...">

How far are you willing to fly?

    			<input id="radius" type="number" class="form-control" placeholder="Radius in miles..." aria-describedby="miles-addon">
    			miles

    		<button id="submit-button" type="submit" onclick="getRandomAirport($('#origin').val(),$('#radius').val())" class="btn btn-primary">Find my destination!</button>

You're going to...

Airport Name

Airport Code

Airport Classification

Distance from origin

//TODO

Country

How excited you should be

© Dave Allen 2017


text:
<?php
  $page_title = 'All sale';
  require_once('includes/load.php');
  // Checkin What level user has permission to view this page
   page_require_level(3);
?>
<?php
$sales = find_all_sale();
?>
<?php include_once('layouts/header.php'); ?>

    <?php echo display_msg($msg); ?>

            All Sales

            Add sale

                #
                 Usuario
                 Product name
                 Quantity
                 Total
                 Estado
                 Date
                 Actions

             <?php foreach ($sales as $sale):?>

               <?php echo count_id();?>
               <?php echo remove_junk($sale['username']); ?>
               <?php echo remove_junk($sale['name']); ?>
               <?php echo (int)$sale['qty']; ?>
               <?php echo remove_junk($sale['price']); ?>

                     <?php
                      if ($sale['status']== 1):
                     ?>
                      <button class="btn btn-success btn-xs">Enviado</button>
                      <?php
                      else:
                      ?>
                     <button onclick="editar(<?php echo (int)$sale['id'];?>)" class="btn btn-warning btn-xs">editar</button>
                     <?php
                     endif
                     ?>

               <?php echo $sale['date']; ?>

                     <a href="edit_sale.php?id=<?php echo (int)$sale['id'];?>" class="btn btn-warning btn-xs"  title="Edit" data-toggle="tooltip">

                     <a href="delete_sale.php?id=<?php echo (int)$sale['id'];?>" class="btn btn-danger btn-xs"  title="Delete" data-toggle="tooltip">

             <?php endforeach;?>

<?php include_once('layouts/footer.php'); ?>


text:
<?php

$string['thislanguage'] = 'Orphaned language with non-existing parent';
$string['parentlanguage'] = 'bbparent';


text:
package edu.ur.dspace.load;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;

import org.w3c.dom.DOMException;

import edu.ur.dspace.model.DspaceGroup;

/**
 * Interface for importing groups.
 *
 * @author Nathan Sarr
 *
 */
public interface GroupImporter {

	/**
	 * Import users in the XML file
	 *
	 * @param xmlFile - file containing the user data.
	 */
	public void importGroups(File xmlFile) throws DOMException, ParseException, IOException;

	/**
	 * Get the users out of the xml file.
	 *
	 * @param xmlFile
	 * @return
	 */
	public List<DspaceGroup> getGroups(File xmlFile) throws DOMException, ParseException, IOException;

}


text:
package cs518.samples.intentdata3;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

/**
 *
 * This class does two things 1 receive data from the Intent of the Activity
 * that started it. 2 create a new Intent to send data back to the Activity that
 * started it.
 *
 * It displays the received data on the UI.
 *
 * @author Tricia
 *
 */
public class Activity3 extends Activity {
	boolean returnHit = false;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity3_main);

		String value = getIntent().getExtras().getString("DATA1");
		TextView tv2 = (TextView) findViewById(R.id.a3tv2);

		if (value == null || value.isEmpty()) {
			tv2.setText(R.string.nodata);
			tv2.setTextColor(Color.RED);
		} else {
			MainActivity.logIt("DATA1 " + value);
			tv2.setText(value);
			tv2.setTextColor(Color.MAGENTA);
		}
	} // onCreate()

	public void returnData(View view) {
		EditText et1 = (EditText) findViewById(R.id.a3et1);
		Intent i = new Intent();
		i.putExtra("DATA3", et1.getText().toString());
		setResult(RESULT_OK, i);
		returnHit = true;
		finish();
	}

	@Override
	public void finish() {
		if (!returnHit) {
		Intent i = new Intent();
		i.putExtra("DATA2", "Data dropped, back button was hit!");
		setResult(RESULT_CANCELED, i);
		}
		super.finish();
	}

}  // Activity2


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Ignition.FormIgnition.Sc.Bases
{
	public class IgnitionFormCondition
	{
	}
}


text:
package org.usfirst.frc.team2471.robot;

import edu.wpi.first.wpilibj.AnalogInput;
import edu.wpi.first.wpilibj.CANTalon;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.PowerDistributionPanel;
import edu.wpi.first.wpilibj.Solenoid;

/**
 * The RobotMap is a mapping from the ports sensors and actuators are wired into
 * to a variable name. This provides flexibility changing wiring, makes checking
 * the wiring easier and significantly reduces the number of magic numbers
 * floating around.
 */
public class RobotMap {
	// For example to map the left and right motors, you could define the
	// following variables to use with your drivetrain subsystem.
	// public static int leftMotor = 1;
	// public static int rightMotor = 2;

	// If you are using multiple modules, make sure to define both the port
	// number and the module. For example you with a rangefinder:
	// public static int rangefinderPort = 1;
	// public static int rangefinderModule = 1;

	/* ------------------------- Robot __________________________________*/

	// 2016 testing CIMs port 0 and 1

	public static PowerDistributionPanel pdp;

	/* -------------------- Drive Train -------------------------------- */
	public static CANTalon lDrive1;
	public static CANTalon lDriveMiddle;
	public static CANTalon lDrive2;
	public static Encoder leftE;

	public static CANTalon rDrive1;
	public static CANTalon rDriveMiddle;
	public static CANTalon rDrive2;
	public static Encoder rightE;

	public static Solenoid shifter;

	public static Solenoid lPTO;
	public static Solenoid rPTO;

	public static int gear;

	/* _______________________Sucker stuff__________________________________ */
	public static CANTalon ftop;
	public static CANTalon fbottom;
	public static CANTalon orbital;

	public static Solenoid fextend;

	public static DigitalInput ltop;
	public static DigitalInput lbottom;

	public static AnalogInput sensorTest;

	public static Solenoid bunnyGrabber;

	public static void init() {

		// Drivetrain
		lDrive1 = new CANTalon(0); // TODO: get ids when electrical is ready
		lDriveMiddle = new CANTalon(1);
		lDrive2 = new CANTalon(2);
		leftE = new Encoder(6, 7);
		leftE.setDistancePerPulse(0.05/12);  // ( Math.PI * 3.0 / 200.0 / 12.0 )  // diameter, ticks per rev, inches per foot

		rDrive1 = new CANTalon(3);
		rDriveMiddle = new CANTalon(4);
		rDrive2 = new CANTalon(5);
		rightE = new Encoder(0, 1);
		rightE.setDistancePerPulse(-0.05/12);  // ( -Math.PI * 3.0 / 200.0 / 12.0 )  // diameter, ticks per rev, inches per foot
		shifter = new Solenoid(0);

		gear = 0;

		// Intake/Outtake
		fbottom = new CANTalon(6);
		ftop = new CANTalon(7);

		orbital = new CANTalon(8);

		fextend = new Solenoid(7);
		fextend.set(true);

		ltop = new DigitalInput(4);
		lbottom = new DigitalInput(5);

		bunnyGrabber = new Solenoid(1);

		pdp = new PowerDistributionPanel();

		sensorTest = new AnalogInput(0);
	}
}


text:
require_relative '../lib/fast_excel'

workbook = FastExcel.open("example_chart.xlsx", constant_memory: true)
worksheet = workbook.add_worksheet

for i in 0..5
  for n in 0..3
    worksheet.write_number(i, n, (i + 1) * (n + 1), nil)
  end
end

chart = workbook.add_chart(Libxlsxwriter::enum_type(:chart_type)[:column])

chart.add_series("Bob", "Sheet1!$A$1:$A$5")
chart.add_series("Alice", "Sheet1!$B$1:$B$5")
chart.add_series("Montgomery", "Sheet1!$C$1:$C$5")

worksheet.insert_chart(1, 7, chart)

workbook.close
puts "Saved to file example_chart.xlsx"


text:
using namespace ndnrtc;
using namespace webrtc;
using namespace std;

//******************************************************************************
//******************************************************************************
#pragma mark - static
int NdnAudioSender::getStreamControlPrefix(const ParamsStruct &params,
                                           string &prefix)
{
    int res = RESULT_OK;
    string streamPrefix;

    MediaSender::getStreamPrefix(params, streamPrefix);

    string streamThread = ParamsStruct::validate(params.streamThread,
                                                 DefaultParamsAudio.streamThread,
                                                 res);
    // RTP and RTCP are published under the same prefix
#if 0
    string rtcpSuffix = "control";
#else
    string rtcpSuffix = NdnRtcNamespace::NdnRtcNamespaceComponentStreamFrames;
#endif
    prefix = *NdnRtcNamespace::buildPath(false,
                                         &streamPrefix,
                                         &streamThread,
                                         &rtcpSuffix,
                                         NULL);

    return res;
}

//******************************************************************************
#pragma mark - public
int NdnAudioSender::init(const shared_ptr<ndn::Transport> transport)
{
    int res = RESULT_OK;

    res = MediaSender::init(transport);

    if (RESULT_FAIL(res))
        return res;

    string prefix;

    res = NdnAudioSender::getStreamControlPrefix(params_, prefix);

    if (RESULT_GOOD(res))
        rtcpPacketPrefix_.reset(new Name(prefix.c_str()));

    return res;
}

int NdnAudioSender::publishRTPAudioPacket(unsigned int len, unsigned char *data)
{
    // update packet rate meter
    NdnRtcUtils::frequencyMeterTick(packetRateMeter_);

    NdnAudioData::AudioPacket packet {false, NdnRtcUtils::millisecondTimestamp(),
        len, data};
    PacketData::PacketMetadata metadata = {getCurrentPacketRate()};
    NdnAudioData adata(packet, metadata);

    publishPacket(adata.getLength(), adata.getData());
    packetNo_++;

    return 0;
}

int NdnAudioSender::publishRTCPAudioPacket(unsigned int len, unsigned char *data)
{
    NdnAudioData::AudioPacket packet {true, NdnRtcUtils::millisecondTimestamp(),
        len, data};
    NdnAudioData adata(packet);

    publishPacket(adata.getLength(), adata.getData());
    packetNo_++;

    return 0;
}
//******************************************************************************
#pragma mark - intefaces realization - <#interface#>

//******************************************************************************
#pragma mark - private


text:
/**
 * @file Functions.hpp
 *
 * collection of rather simple mathematical functions that get used over and over again
 */

#pragma once

#include "Limits.hpp"

#include <matrix/matrix/math.hpp>

namespace math
{

// Type-safe signum function with zero treated as positive
template<typename T>
int signNoZero(T val)
{
	return (T(0) <= val) - (val < T(0));
}

/*
 * So called exponential curve function implementation.
 * It is essentially a linear combination between a linear and a cubic function.
 * @param value [-1,1] input value to function
 * @param e [0,1] function parameter to set ratio between linear and cubic shape
 * 		0 - pure linear function
 * 		1 - pure cubic function
 * @return result of function output
 */
template<typename T>
const T expo(const T &value, const T &e)
{
	T x = constrain(value, (T) - 1, (T) 1);
	T ec = constrain(e, (T) 0, (T) 1);
	return (1 - ec) * x + ec * x * x * x;
}

/*
 * So called SuperExpo function implementation.
 * It is a 1/(1-x) function to further shape the rc input curve intuitively.
 * I enhanced it compared to other implementations to keep the scale between [-1,1].
 * @param value [-1,1] input value to function
 * @param e [0,1] function parameter to set ratio between linear and cubic shape (see expo)
 * @param g [0,1) function parameter to set SuperExpo shape
 * 		0 - pure expo function
 * 		0.99 - very strong bent curve, stays zero until maximum stick input
 * @return result of function output
 */
template<typename T>
const T superexpo(const T &value, const T &e, const T &g)
{
	T x = constrain(value, (T) - 1, (T) 1);
	T gc = constrain(g, (T) 0, (T) 0.99);
	return expo(x, e) * (1 - gc) / (1 - fabsf(x) * gc);
}

/*
 * Deadzone function being linear and continuous outside of the deadzone
 * 1                ------
 *                /
 *             --
 *           /
 * -1 ------
 *        -1 -dz +dz 1
 * @param value [-1,1] input value to function
 * @param dz [0,1) ratio between deazone and complete span
 * 		0 - no deadzone, linear -1 to 1
 * 		0.5 - deadzone is half of the span [-0.5,0.5]
 * 		0.99 - almost entire span is deadzone
 */
template<typename T>
const T deadzone(const T &value, const T &dz)
{
	T x = constrain(value, (T) - 1, (T) 1);
	T dzc = constrain(dz, (T) 0, (T) 0.99);
	// Rescale the input such that we get a piecewise linear function that will be continuous with applied deadzone
	T out = (x - matrix::sign(x) * dzc) / (1 - dzc);
	// apply the deadzone (values zero around the middle)
	return out * (fabsf(x) > dzc);
}

template<typename T>
const T expo_deadzone(const T &value, const T &e, const T &dz)
{
	return expo(deadzone(value, dz), e);
}

/*
 * Constant, linear, constant function with the two corner points as parameters
 * y_high          -------
 *                /
 *               /
 *              /
 * y_low -------
 *         x_low   x_high
 */
template<typename T>
const T gradual(const T &value, const T &x_low, const T &x_high, const T &y_low, const T &y_high)
{
	if (value < x_low) {
		return y_low;

	} else if (value > x_high) {
		return y_high;

	} else {
		/* linear function between the two points */
		T a = (y_high - y_low) / (x_high - x_low);
		T b = y_low - a * x_low;
		return  a * value + b;
	}
}

/*
 * Constant, linear, linear, constant function with the three corner points as parameters
 *  y_high               -------
 *                      /
 *                    /
 *  y_middle        /
 *                /
 *               /
 *              /
 * y_low -------
 *         x_low x_middle x_high
 */
template<typename T>
const T gradual3(const T &value,
		 const T &x_low, const T &x_middle, const T &x_high,
		 const T &y_low, const T &y_middle, const T &y_high)
{
	if (value < x_middle) {
		return gradual(value, x_low, x_middle, y_low, y_middle);

	} else {
		return gradual(value, x_middle, x_high, y_middle, y_high);
	}
}

} /* namespace math */


text:
import logging
from dl_data_validation_toolset.framework import base_test

class WiresTests(base_test.BaseTest):
    logger = logging.getLogger('data_tests.wires')

    def test_nonempty(self):
        data = self._file['image/wires']
        valid = len(data) > 0
        return {'Is Non Empty': valid}, valid

    def test_digits_exist(self):
        wiers = self._file['image/wires']
        valid = int(wiers is not None)
        valid += int(len(wiers) > 0)
        return {'N Wires': len(wiers)}, valid


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Basic Form - jQuery EasyUI Demo</title>
    <link rel="stylesheet" type="text/css" href="../../themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="../../themes/icon.css">
    <link rel="stylesheet" type="text/css" href="../demo.css">

Basic Form

Fill the form and submit it.

        <form id="ff" method="post">

                    Name:
                    <input class="easyui-validatebox" type="text" name="name" data-options="required:true"></input>

                    Email:
                    <input class="easyui-validatebox" type="text" name="email"
                               data-options="required:true,validType:'email'"></input>

                    Subject:
                    <input class="easyui-validatebox" type="text" name="subject"
                               data-options="required:true"></input>

                    Message:
                    <textarea name="message" style="height:60px;"></textarea>

                    Language:

                        <select class="easyui-combobox" name="language">
                            <option value="ar">Arabic</option>
                            <option value="bg">Bulgarian</option>
                            <option value="ca">Catalan</option>
                            <option value="zh-cht">Chinese Traditional</option>
                            <option value="cs">Czech</option>
                            <option value="da">Danish</option>
                            <option value="nl">Dutch</option>
                            <option value="en" selected="selected">English</option>
                            <option value="et">Estonian</option>
                            <option value="fi">Finnish</option>
                            <option value="fr">French</option>
                            <option value="de">German</option>
                            <option value="el">Greek</option>
                            <option value="ht">Haitian Creole</option>
                            <option value="he">Hebrew</option>
                            <option value="hi">Hindi</option>
                            <option value="mww">Hmong Daw</option>
                            <option value="hu">Hungarian</option>
                            <option value="id">Indonesian</option>
                            <option value="it">Italian</option>
                            <option value="ja">Japanese</option>
                            <option value="ko">Korean</option>
                            <option value="lv">Latvian</option>
                            <option value="lt">Lithuanian</option>
                            <option value="no">Norwegian</option>
                            <option value="fa">Persian</option>
                            <option value="pl">Polish</option>
                            <option value="pt">Portuguese</option>
                            <option value="ro">Romanian</option>
                            <option value="ru">Russian</option>
                            <option value="sk">Slovak</option>
                            <option value="sl">Slovenian</option>
                            <option value="es">Spanish</option>
                            <option value="sv">Swedish</option>
                            <option value="th">Thai</option>
                            <option value="tr">Turkish</option>
                            <option value="uk">Ukrainian</option>
                            <option value="vi">Vietnamese</option>
                        </select>

        </form>

        Submit
        Clear


text:
using NSwag;

namespace Jab.Interfaces
{
    /// <summary>
    /// A swagger operation (i.e. web method) called by jab.
    /// </summary>
    public interface IJabApiOperation
    {

        /// <summary>
        /// The <see cref="SwaggerService"/>.
        /// </summary>
        SwaggerService Service { get; }

        /// <summary>
        /// The path (non host portion of the URL).
        /// </summary>
        string Path { get; }

        /// <summary>
        /// The HTTP method or verb used to call the web service.
        /// </summary>
        SwaggerOperationMethod Method { get; }

        /// <summary>
        /// The <see cref="SwaggerOperation"/>.
        /// </summary>
        SwaggerOperation Operation { get; }
    }
}


text:
import { MakeRequest, MRActions, MRReturn } from '../../common-types';
export declare type DefaultParams = {
    spaceId?: string;
    environmentId?: string;
    organizationId?: string;
};
/**
 * @private
 */
export declare type OptionalDefaults<T> = Omit<T, keyof DefaultParams> & ('organizationId' extends keyof T ? {
    organizationId?: string;
} : Record<string, unknown>) & ('spaceId' extends keyof T ? {
    spaceId?: string;
} : Record<string, unknown>) & ('environmentId' extends keyof T ? {
    environmentId?: string;
} : Record<string, unknown>);
/**
 * @private
 */
export declare type WrapParams = {
    makeRequest: MakeRequest;
    defaults?: DefaultParams;
};
/**
 * @private
 */
export declare type WrapFn<ET extends keyof MRActions, Action extends keyof MRActions[ET], Params = 'params' extends keyof MRActions[ET][Action] ? MRActions[ET][Action]['params'] : undefined, Payload = 'payload' extends keyof MRActions[ET][Action] ? MRActions[ET][Action]['payload'] : undefined, Headers = 'headers' extends keyof MRActions[ET][Action] ? MRActions[ET][Action]['headers'] : undefined, Return = MRReturn<ET, Action>> = Params extends undefined ? () => Return : Payload extends undefined ? (params: Params) => Return : Headers extends undefined ? (params: Params, payload: Payload) => Return : (params: Params, payload: Payload, headers: Headers) => Return;
/**
 * @private
 */
export declare const wrap: <ET extends keyof MRActions, Action extends keyof MRActions[ET]>({ makeRequest, defaults }: WrapParams, entityType: ET, action: Action) => WrapFn<ET, Action, "params" extends keyof MRActions[ET][Action] ? MRActions[ET][Action][keyof MRActions[ET][Action] & "params"] : undefined, "payload" extends keyof MRActions[ET][Action] ? MRActions[ET][Action][keyof MRActions[ET][Action] & "payload"] : undefined, "headers" extends keyof MRActions[ET][Action] ? MRActions[ET][Action][keyof MRActions[ET][Action] & "headers"] : undefined, MRReturn<ET, Action>>;


text:
package org.apache.beam.sdk.extensions.sql.meta.provider.kafka;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.beam.sdk.extensions.sql.impl.schema.BeamTableUtils.beamRow2CsvLine;
import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkArgument;

import com.alibaba.fastjson.JSON;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.apache.beam.runners.direct.DirectOptions;
import org.apache.beam.sdk.coders.KvCoder;
import org.apache.beam.sdk.coders.RowCoder;
import org.apache.beam.sdk.coders.StringUtf8Coder;
import org.apache.beam.sdk.extensions.protobuf.PayloadMessages;
import org.apache.beam.sdk.extensions.protobuf.ProtoMessageSchema;
import org.apache.beam.sdk.extensions.sql.impl.BeamSqlEnv;
import org.apache.beam.sdk.extensions.sql.impl.rel.BeamSqlRelUtils;
import org.apache.beam.sdk.extensions.sql.meta.Table;
import org.apache.beam.sdk.extensions.sql.meta.provider.TableProvider;
import org.apache.beam.sdk.io.thrift.ThriftCoder;
import org.apache.beam.sdk.io.thrift.ThriftSchema;
import org.apache.beam.sdk.io.thrift.payloads.ItThriftMessage;
import org.apache.beam.sdk.options.Default;
import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.Validation;
import org.apache.beam.sdk.schemas.RowMessages;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.schemas.utils.AvroUtils;
import org.apache.beam.sdk.state.BagState;
import org.apache.beam.sdk.state.StateSpec;
import org.apache.beam.sdk.state.StateSpecs;
import org.apache.beam.sdk.state.ValueState;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.MapElements;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.SimpleFunction;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.Row;
import org.apache.beam.sdk.values.TypeDescriptor;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.MoreObjects;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableSet;
import org.apache.commons.csv.CSVFormat;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocolFactory;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.testcontainers.containers.KafkaContainer;
import org.testcontainers.utility.DockerImageName;

/** Integration Test utility for KafkaTableProvider implementations. */
@RunWith(Parameterized.class)
// TODO(https://github.com/apache/beam/issues/21230): Remove when new version of errorprone is
// released (2.11.0)
@SuppressWarnings("unused")
public class KafkaTableProviderIT {
  private static final String KAFKA_CONTAINER_VERSION = "5.5.2";

  @Rule public transient TestPipeline pipeline = TestPipeline.create();

  @ClassRule
  public static final KafkaContainer KAFKA_CONTAINER =
      new KafkaContainer(
          DockerImageName.parse("confluentinc/cp-kafka").withTag(KAFKA_CONTAINER_VERSION));

  private static KafkaOptions kafkaOptions;

  private static final Schema TEST_TABLE_SCHEMA =
      Schema.builder()
          .addInt64Field("f_long")
          .addInt32Field("f_int")
          .addStringField("f_string")
          .build();

  @Parameters
  public static Collection<Object[]> data() {
    return Arrays.asList(
        new Object[][] {
          {new KafkaJsonObjectProvider(), "json_topic"},
          {new KafkaAvroObjectProvider(), "avro_topic"},
          {new KafkaProtoObjectProvider(), "proto_topic"},
          {new KafkaCsvObjectProvider(), "csv_topic"},
          {new KafkaThriftObjectProvider(), "thrift_topic"}
        });
  }

  @Parameter public KafkaObjectProvider objectsProvider;

  @Parameter(1)
  public String topic;

  @Before
  public void setUp() {
    kafkaOptions = pipeline.getOptions().as(KafkaOptions.class);
    kafkaOptions.setKafkaTopic(topic);
    kafkaOptions.setKafkaBootstrapServerAddress(KAFKA_CONTAINER.getBootstrapServers());
    checkArgument(
        !KAFKA_CONTAINER.getBootstrapServers().contains(","),
        "This integration test expects exactly one bootstrap server.");
  }

  private static String buildLocation() {
    return kafkaOptions.getKafkaBootstrapServerAddress() + "/" + kafkaOptions.getKafkaTopic();
  }

  @Test
  @SuppressWarnings("FutureReturnValueIgnored")
  public void testFake2() throws BeamKafkaTable.NoEstimationException {
    Table table =
        Table.builder()
            .name("kafka_table")
            .comment("kafka table")
            .location(buildLocation())
            .schema(TEST_TABLE_SCHEMA)
            .type("kafka")
            .properties(JSON.parseObject(objectsProvider.getKafkaPropertiesString()))
            .build();
    BeamKafkaTable kafkaTable = (BeamKafkaTable) new KafkaTableProvider().buildBeamSqlTable(table);
    produceSomeRecordsWithDelay(100, 20);
    double rate1 = kafkaTable.computeRate(20);
    produceSomeRecordsWithDelay(100, 10);
    double rate2 = kafkaTable.computeRate(20);
    Assert.assertTrue(rate2 > rate1);
  }

  static final transient Map<Long, Boolean> FLAG = new ConcurrentHashMap<>();

  @Test
  public void testFake() throws InterruptedException {
    pipeline.getOptions().as(DirectOptions.class).setBlockOnRun(false);
    String createTableString =
        String.format(
            "CREATE EXTERNAL TABLE kafka_table(\n"
                + "f_long BIGINT NOT NULL, \n"
                + "f_int INTEGER NOT NULL, \n"
                + "f_string VARCHAR NOT NULL \n"
                + ") \n"
                + "TYPE 'kafka' \n"
                + "LOCATION '%s'\n"
                + "TBLPROPERTIES '%s'",
            buildLocation(), objectsProvider.getKafkaPropertiesString());
    TableProvider tb = new KafkaTableProvider();
    BeamSqlEnv env = BeamSqlEnv.inMemory(tb);

    env.executeDdl(createTableString);

    PCollection<Row> queryOutput =
        BeamSqlRelUtils.toPCollection(pipeline, env.parseQuery("SELECT * FROM kafka_table"));

    queryOutput
        .apply(ParDo.of(new FakeKvPair()))
        .setCoder(KvCoder.of(StringUtf8Coder.of(), RowCoder.of(TEST_TABLE_SCHEMA)))
        .apply(
            "waitForSuccess",
            ParDo.of(
                new StreamAssertEqual(
                    ImmutableSet.of(generateRow(0), generateRow(1), generateRow(2)))));
    queryOutput.apply(logRecords(""));
    pipeline.run();
    TimeUnit.SECONDS.sleep(4);
    produceSomeRecords(3);

    for (int i = 0; i < 200; i++) {
      if (FLAG.getOrDefault(pipeline.getOptions().getOptionsId(), false)) {
        return;
      }
      TimeUnit.MILLISECONDS.sleep(90);
    }
    Assert.fail();
  }

  @Test
  public void testFakeNested() throws InterruptedException {
    Assume.assumeFalse(topic.equals("csv_topic"));
    pipeline.getOptions().as(DirectOptions.class).setBlockOnRun(false);
    String createTableString =
        String.format(
            "CREATE EXTERNAL TABLE kafka_table(\n"
                + "headers ARRAY<ROW<key VARCHAR, `values` ARRAY<VARBINARY>>>,"
                + "payload ROW<"
                + "f_long BIGINT NOT NULL, \n"
                + "f_int INTEGER NOT NULL, \n"
                + "f_string VARCHAR NOT NULL \n"
                + ">"
                + ") \n"
                + "TYPE 'kafka' \n"
                + "LOCATION '%s'\n"
                + "TBLPROPERTIES '%s'",
            buildLocation(), objectsProvider.getKafkaPropertiesString());
    TableProvider tb = new KafkaTableProvider();
    BeamSqlEnv env = BeamSqlEnv.inMemory(tb);

    env.executeDdl(createTableString);

    PCollection<Row> queryOutput =
        BeamSqlRelUtils.toPCollection(
            pipeline,
            env.parseQuery(
                "SELECT kafka_table.payload.f_long, kafka_table.payload.f_int, kafka_table.payload.f_string FROM kafka_table"));

    queryOutput
        .apply(ParDo.of(new FakeKvPair()))
        .setCoder(KvCoder.of(StringUtf8Coder.of(), RowCoder.of(TEST_TABLE_SCHEMA)))
        .apply(
            "waitForSuccess",
            ParDo.of(
                new StreamAssertEqual(
                    ImmutableSet.of(generateRow(0), generateRow(1), generateRow(2)))));
    queryOutput.apply(logRecords(""));
    pipeline.run();
    TimeUnit.SECONDS.sleep(4);
    produceSomeRecords(3);

    for (int i = 0; i < 200; i++) {
      if (FLAG.getOrDefault(pipeline.getOptions().getOptionsId(), false)) {
        return;
      }
      TimeUnit.MILLISECONDS.sleep(90);
    }
    Assert.fail();
  }

  private static MapElements<Row, Void> logRecords(String suffix) {
    return MapElements.via(
        new SimpleFunction<Row, Void>() {
          @Override
          public @Nullable Void apply(Row input) {
            System.out.println(input.getValues() + suffix);
            return null;
          }
        });
  }

  /** This is made because DoFn with states should get KV as input. */
  public static class FakeKvPair extends DoFn<Row, KV<String, Row>> {
    @ProcessElement
    public void processElement(ProcessContext c) {
      c.output(KV.of("fake_key", c.element()));
    }
  }

  /** This DoFn will set a flag if all the elements are seen. */
  public static class StreamAssertEqual extends DoFn<KV<String, Row>, Void> {
    private final Set<Row> expected;

    StreamAssertEqual(Set<Row> expected) {
      super();
      this.expected = expected;
    }

    @StateId("seenValues")
    private final StateSpec<BagState<Row>> seenRows =
        StateSpecs.bag(RowCoder.of(TEST_TABLE_SCHEMA));

    @StateId("count")
    private final StateSpec<ValueState<Integer>> countState = StateSpecs.value();

    @ProcessElement
    public void process(
        ProcessContext context,
        @StateId("seenValues") BagState<Row> seenValues,
        @StateId("count") ValueState<Integer> countState) {
      // I don't think doing this will be safe in parallel
      int count = MoreObjects.firstNonNull(countState.read(), 0);
      count = count + 1;
      countState.write(count);
      seenValues.add(context.element().getValue());

      if (count >= expected.size()) {
        if (StreamSupport.stream(seenValues.read().spliterator(), false)
            .collect(Collectors.toSet())
            .containsAll(expected)) {
          System.out.println("in second if");
          FLAG.put(context.getPipelineOptions().getOptionsId(), true);
        }
      }
    }
  }

  private static Row generateRow(int i) {
    return Row.withSchema(TEST_TABLE_SCHEMA).addValues((long) i, i % 3 + 1, "value" + i).build();
  }

  @SuppressWarnings("FutureReturnValueIgnored")
  private void produceSomeRecords(int num) {
    Producer<String, byte[]> producer = new KafkaProducer<>(producerProps());
    Stream.iterate(0, i -> ++i)
        .limit(num)
        .forEach(
            i -> {
              ProducerRecord<String, byte[]> record = objectsProvider.generateProducerRecord(i);
              producer.send(record);
            });
    producer.flush();
    producer.close();
  }

  @SuppressWarnings("FutureReturnValueIgnored")
  private void produceSomeRecordsWithDelay(int num, int delayMilis) {
    Producer<String, byte[]> producer = new KafkaProducer<>(producerProps());
    Stream.iterate(0, i -> ++i)
        .limit(num)
        .forEach(
            i -> {
              ProducerRecord<String, byte[]> record = objectsProvider.generateProducerRecord(i);
              producer.send(record);
              try {
                TimeUnit.MILLISECONDS.sleep(delayMilis);
              } catch (InterruptedException e) {
                throw new RuntimeException("Could not wait for producing", e);
              }
            });
    producer.flush();
    producer.close();
  }

  private Properties producerProps() {
    Properties props = new Properties();
    props.put("bootstrap.servers", kafkaOptions.getKafkaBootstrapServerAddress());
    props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
    props.put("value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");
    props.put("buffer.memory", 33554432);
    props.put("acks", "all");
    props.put("request.required.acks", "1");
    props.put("retries", 0);
    props.put("linger.ms", 1);
    return props;
  }

  private abstract static class KafkaObjectProvider implements Serializable {

    protected abstract ProducerRecord<String, byte[]> generateProducerRecord(int i);

    protected abstract String getPayloadFormat();

    protected String getKafkaPropertiesString() {
      return "{ "
          + (getPayloadFormat() == null ? "" : "\"format\" : \"" + getPayloadFormat() + "\",")
          + "}";
    }
  }

  private static class KafkaJsonObjectProvider extends KafkaObjectProvider {
    @Override
    protected ProducerRecord<String, byte[]> generateProducerRecord(int i) {
      return new ProducerRecord<>(
          kafkaOptions.getKafkaTopic(), "k" + i, createJson(i).getBytes(UTF_8));
    }

    @Override
    protected String getPayloadFormat() {
      return "json";
    }

    private String createJson(int i) {
      return String.format(
          "{\"f_long\": %s, \"f_int\": %s, \"f_string\": \"%s\"}", i, i % 3 + 1, "value" + i);
    }
  }

  private static class KafkaProtoObjectProvider extends KafkaObjectProvider {
    private final SimpleFunction<Row, byte[]> toBytesFn =
        ProtoMessageSchema.getRowToProtoBytesFn(PayloadMessages.ItMessage.class);

    @Override
    protected ProducerRecord<String, byte[]> generateProducerRecord(int i) {
      return new ProducerRecord<>(
          kafkaOptions.getKafkaTopic(), "k" + i, toBytesFn.apply(generateRow(i)));
    }

    @Override
    protected String getPayloadFormat() {
      return "proto";
    }

    @Override
    protected String getKafkaPropertiesString() {
      return "{ "
          + "\"format\" : \"proto\","
          + "\"protoClass\": \""
          + PayloadMessages.ItMessage.class.getName()
          + "\"}";
    }
  }

  private static class KafkaCsvObjectProvider extends KafkaObjectProvider {

    @Override
    protected ProducerRecord<String, byte[]> generateProducerRecord(int i) {
      return new ProducerRecord<>(
          kafkaOptions.getKafkaTopic(),
          "k" + i,
          beamRow2CsvLine(generateRow(i), CSVFormat.DEFAULT).getBytes(UTF_8));
    }

    @Override
    protected String getPayloadFormat() {
      return null;
    }
  }

  private static class KafkaAvroObjectProvider extends KafkaObjectProvider {

    private final SimpleFunction<Row, byte[]> toBytesFn =
        AvroUtils.getRowToAvroBytesFunction(TEST_TABLE_SCHEMA);

    @Override
    protected ProducerRecord<String, byte[]> generateProducerRecord(int i) {
      return new ProducerRecord<>(
          kafkaOptions.getKafkaTopic(), "k" + i, toBytesFn.apply(generateRow(i)));
    }

    @Override
    protected String getPayloadFormat() {
      return "avro";
    }
  }

  private static class KafkaThriftObjectProvider extends KafkaObjectProvider {
    private final Class<ItThriftMessage> thriftClass = ItThriftMessage.class;
    private final TProtocolFactory protocolFactory = new TBinaryProtocol.Factory();
    private final SimpleFunction<Row, byte[]> toBytesFn =
        RowMessages.rowToBytesFn(
            ThriftSchema.provider(),
            TypeDescriptor.of(thriftClass),
            ThriftCoder.of(thriftClass, protocolFactory));

    @Override
    protected ProducerRecord<String, byte[]> generateProducerRecord(int i) {
      return new ProducerRecord<>(
          kafkaOptions.getKafkaTopic(), "k" + i, toBytesFn.apply(generateRow(i)));
    }

    @Override
    protected String getKafkaPropertiesString() {
      return "{ "
          + "\"format\" : \"thrift\","
          + "\"thriftClass\": \""
          + thriftClass.getName()
          + "\", \"thriftProtocolFactoryClass\": \""
          + protocolFactory.getClass().getName()
          + "\"}";
    }

    @Override
    protected String getPayloadFormat() {
      return "thrift";
    }
  }

  /** Pipeline options specific for this test. */
  public interface KafkaOptions extends PipelineOptions {

    @Description("Kafka server address")
    @Validation.Required
    @Default.String("localhost:9092")
    String getKafkaBootstrapServerAddress();

    void setKafkaBootstrapServerAddress(String address);

    @Description("Kafka topic")
    @Validation.Required
    @Default.String("test")
    String getKafkaTopic();

    void setKafkaTopic(String topic);
  }
}


text:
This is a group of scripts that I use to automate a lot of tedious tasks in development or day to day work. These scripts are written in Bash, PHP and Python.

**These scripts cannot be used for production purposes they are just sample scripts that you may use after reading and editing them.**


text:
Public Class Turno
    Private _jugadores As List(Of Jugador)
    Public Property jugadores() As List(Of Jugador)
        Get
            Return _jugadores
        End Get
        Set(ByVal value As List(Of Jugador))
            _jugadores = value
        End Set
    End Property

    Private _tiro As Integer
    Public Property tiro() As Integer
        Get
            Return _tiro
        End Get
        Set(ByVal value As Integer)
            _tiro = value
        End Set
    End Property

    Private _jugadorActual As New Jugador
    Public Property jugadorActual() As Jugador
        Get
            Return _jugadorActual
        End Get
        Set(ByVal value As Jugador)
            _jugadorActual = value
        End Set
    End Property

    Private _anotado As Boolean
    Public Property anotado() As Boolean
        Get
            Return _anotado
        End Get
        Set(ByVal value As Boolean)
            _anotado = value
        End Set
    End Property

End Class


text:
[![Build Status](https://travis-ci.org/jkamenik/simple-arel-rails.png)](https://travis-ci.org/jkamenik/simple-arel-rails)

This is entirely based off RailsCast #355: Hacking with Arel.  100% of the credit goes to Ryan Bates.

I haven't wanted to use Squeel or meta_where, but only because they add a lot more then I would ever use and have a syntax different then I liked.  And I actually don't like the predicate loader from the episode so I didn't include that.

## Background

Originally I had thought about extracting something similar from a project that I was doing and wanted to use "or" in where clauses easily.  The other Arel wrapper, though awesome, were more then I wanted.  Then I sumbled upon the Hacking with Arel Railscast (you do have a "pro" account, right?) and it turned out to be exactly what I wanted.  Justed need to write tests to ensure it behaved as expected.

## Installation

Add this line to your application's Gemfile:

    gem 'simple-arel-rails'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install simple-arel-rails

## Usage

    class User < ActiveRecord::Base
      scope :name,          ->(name)    {where(:name => name)}
      scope :title,         ->(title)   {where(:title => title)}
      scope :name_or_title, ->(test)    {name(test) | title(test)}
      scope :everyone_but,  ->(person)  {not name(test)}
      scope :hard_worker,   ->(company) {where(:company => company) & h_where(:hours_per_week => {:gt => 40})}
    end

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
'''
Created on 22.10.2014

@author: Philip
'''

import flask
import flask_login

import users.forms
import users.models
import utils.forms
import utils.redirect
from utils.views import get_column_names, create_table, alert_warning, alert_info, alert_success, \
    error_not_found, error_access_denied, create_action_urls

bp_users = flask.Blueprint("users", __name__)

@bp_users.route('/login', methods=['GET', 'POST'])
def login():
    form = users.forms.LoginForm()
    if form.validate_on_submit():
        user = users.models.User.query.filter_by(username=form.username.data).first()
        if user is not None and user.verify_password(form.password.data):
            flask_login.login_user(user, True)
            alert_info('You have been logged in')
            return utils.redirect.redirect_back('index')
        alert_warning('Invalid username or password')
    return flask.render_template('login.html', form=form)

@bp_users.route('/logout')
def logout():
    flask_login.logout_user()
    alert_info('You have been logged out')
    return flask.redirect(flask.url_for('.login'))

@bp_users.route('/register', methods=['GET', 'POST'])
def register():
    form = users.forms.RegisterForm()
    if form.validate_on_submit():
        users.models.User.create(form=form)
        alert_success('Your account has been created')
        return flask.redirect(flask.url_for('.login'))
    return flask.render_template('register.html', form=form)

@bp_users.route('/table')
@flask_login.login_required
def table():
    if not flask_login.current_user.is_admin():
        return error_access_denied('Users', 'index')
    models = users.models.User.query.all()
    columns = get_column_names(users.models.User())
    table = create_table(models, {'Edit': '.edit', 'Delete': '.delete'}, user_id='id')
    actions = create_action_urls({'Add': '.add'})
    return flask.render_template('table_page.html', title="Users", columns=columns, table=table, actions=actions)

@bp_users.route('/add', methods=['GET', 'POST'])
@flask_login.login_required
def add():
    if not flask_login.current_user.is_admin():
        return error_access_denied('Users', 'index')
    form = users.forms.UserForm()
    form.role.choices = [(role.index, str(role).capitalize()) for role in users.constants.Roles]
    if form.validate_on_submit():
        users.models.User.create(form=form)
        alert_success('The user has been saved')
        return flask.redirect(flask.url_for('.table'))

    return flask.render_template('add_page.html', type="User", form=form)

@bp_users.route('/edit/<int:user_id>', methods=['GET', 'POST'])
@flask_login.login_required
def edit(user_id):
    user = users.models.User.query.filter_by(id=user_id).first()
    if user is None:
        return error_not_found('User ID {}'.format(user_id), 'index')
    if not user.has_access(flask_login.current_user):
        return error_access_denied('User ID {}'.format(user_id), 'index')

    form = users.forms.UserForm(flask.request.form, user)
    # Set default of username field to check if changed (see custom validator
    # function validate_username)
    form.username.default = user.username
    if flask_login.current_user.is_admin():
        form.role.choices = [(role.index, str(role).capitalize()) for role in users.constants.Roles]
    else:
        form.role.choices = [(flask_login.current_user.role, flask_login.current_user.role_string)]

    if form.validate_on_submit():
        user.update(form=form)
        alert_success('The user has been saved')

    actions = create_action_urls({'Delete': '.delete'}, user, user_id='id')
    return flask.render_template('edit_page.html', type="User", name=user.username, form=form, actions=actions)

@bp_users.route('/delete/<int:user_id>', methods=['GET', 'POST'])
@flask_login.login_required
def delete(user_id):
    user = users.models.User.query.filter_by(id=user_id).first()
    if user is None:
        return error_not_found('User ID {}'.format(user_id), 'index')
    if not user.has_access(flask_login.current_user):
        return error_access_denied('User ID {}'.format(user_id), 'index')

    form = utils.forms.ConfirmationForm()
    if form.validate_on_submit():
        if form.radio.data == 'yes':
            user.delete()
            alert_success('The user has been deleted')
        return flask.redirect(flask.url_for('index'))

    return flask.render_template('delete_page.html', type="User", name=user.username, form=form)


text:
using Agenda.Dominio.Entidade;
using Agenda.Dominio.IRepositorio;
using Agenda.Repositorio.Helper;
using NHibernate;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Agenda.Repositorio.Repositorio
{
    public class PessoaRepositorio : RepositorioBase<Pessoa>, IPessoaRepositorio
    {
        public IList<Pessoa> RetornaAniversariantesDoMes()
        {
            var dataInicial = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
            var dataFinal = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");

            using (ISession session = NHibernateHelper.OpenSession())
                return session.CreateQuery("from Pessoa as p where p.PsaDataNascimento >= :dataInicial and p.PsaDataNascimento <= :dataFinal")
                            .SetString("dataInicial", dataInicial)
                            .SetString("dataFinal", dataFinal)
                            .List<Pessoa>();
        }

        public IList<Pessoa> RetornarContatoPorNome(string nome)
        {
            using (ISession session = NHibernateHelper.OpenSession())
                return session.CreateQuery(string.Format("from Pessoa as p where p.PsaNome like '%{0}%'", nome))
                            .List<Pessoa>();
        }

        public Pessoa RetornaPessoaPorId(int id)
        {
            return this.RetornaPorId(id);
        }
    }
}


text:
const commando = require('discord.js-commando');
const Discord = require('discord.js');
const fs = require('fs');
const string = require('../../string-manip.js');

class SkillSearchCommand extends commando.Command {

  constructor(client){
    super(client, {
      name: 'skill',
      aliases: ['s'],
      group: 'feh',
      memberName: 'skill',
      description: 'Search for a specific unit by `!skill [name]`',
      args: [
        {
          key: 'query',
          prompt: 'Name of the skill to search for?',
          type: 'string',
          validate: text => {
            if (text.length >= 3) return true;
            return 'Your query is too short. Must be at least 3 characters long.'
          }
        }
      ]
    });
  }

  async run(message, args){

    function sendMessage(map, learnable){
      const INLINE = true;
      const embed = new Discord.RichEmbed();

      switch (map['type']){
        case 'WEAPON':
          embed
            .setColor('0xfe4f6f')
            .setTitle( string.underline(map['name']) )
            .addField( 'Type', map['weaponType'], INLINE )
            .addField( 'Damage', map['damage(mt)'], INLINE )
            .addField( 'SP Cost', map['spCost'], INLINE )
            .addField( 'Inheritance Restriction', map['inheritRestriction'], INLINE )
            .addField( 'Effect', map['effect'] )
            .addField( 'Able to Learn at Rarity', learnable)
          ;
          break;
        case 'ASSIST':
           embed
            .setColor('0x00fedf')
            .setTitle( string.underline(map['name']) )
            .addField( 'Type', map['type'], INLINE )
            .addField( 'SP Cost', map['spCost'], INLINE )
            .addField( 'Inheritance Restriction', map['inheritRestriction'], INLINE )
            .addField( 'Effect', map['effect'] )
            .addField( 'Able to Learn at Rarity', learnable)
           ;
          break;
        case 'SPECIAL':
          embed
            .setColor('0xdf9be8')
            .setTitle( string.underline(map['name']) )
            .addField( 'Type', map['type'], INLINE )
            .addField( 'Cooldown', map['cooldown'], INLINE )
            .addField( 'SP Cost', map['spCost'], INLINE )
            .addField( 'Inheritance Restriction', map['inheritRestriction'], INLINE )
            .addField( 'Effect', map['effect'] )
            .addField( 'Able to Learn at Rarity', learnable)
          ;
          break;
        case 'PASSIVE_A':
          embed.setColor('0xfe4f6f')
            .setTitle( string.underline(map['name']) )
            .addField( 'Type', map['type'], INLINE )
            .addField( 'SP Cost', map['spCost'], INLINE )
            .addField( 'Inheritance Restriction', map['inheritRestriction'], INLINE )
            .addField( 'Effect', map['effect'] )
            .addField( 'Able to Learn at Rarity', learnable)
          ;
          break;
        case 'PASSIVE_B':
          embed.setColor('0x0094dd')
            .setTitle( string.underline(map['name']) )
            .addField( 'Type', map['type'], INLINE )
            .addField( 'SP Cost', map['spCost'], INLINE )
            .addField( 'Inheritance Restriction', map['inheritRestriction'], INLINE )
            .addField( 'Effect', map['effect'] )
            .addField( 'Able to Learn at Rarity', learnable)
          ;
          break;
        case 'PASSIVE_C':
          embed
            .setColor('0x00dc48')
            .setTitle( string.underline(map['name']) )
            .addField( 'Type', map['type'], INLINE )
            .addField( 'SP Cost', map['spCost'], INLINE )
            .addField( 'Inheritance Restriction', map['inheritRestriction'], INLINE )
            .addField( 'Effect', map['effect'] )
            .addField( 'Able to Learn at Rarity', learnable)
          ;
          break;
      }

      message.channel.send({embed});
    }

    // main
    const { query } = args;

    fs.readFile('./blobs/skills.json', 'utf-8', function (err, data) {
      if (err) throw err;

      var map = JSON.parse(data);
      var validatedQuery = string.validate(query);
      var objectFound = false;

      // find skill
      for (var k in map){

      	// if partially matches at beginning of string, consider it found
        if ( (string.validate(k)).indexOf(validatedQuery) == 0 ) {
          objectFound = map[k];
        }

      }

      // if skill exists, read heroes.json
      if (objectFound){

        fs.readFile('./blobs/heroes.json', 'utf-8', function (err, data) {
          if (err) throw err;

          var map = JSON.parse(data);
          var results = '';
          var resultStack = [];

          // find all heroes with skill and concatenate results
          for (var k in map){
            if (map[k]['skills'][objectFound['name']]){
              resultStack.push( map[k]['skills'][objectFound['name']] + '★: ' + k + '\n' );
            }
          }

          resultStack.sort();

          for (var i=0; i < resultStack.length; i++){
          	results += resultStack[i];
          }

          results = string.codify(results);
          sendMessage(objectFound, results);

        });

      }

      // O(1) look up, not possible without sacrificing input flexibility
      //
      // if (map[query]){
      //   sendMessage(map[query]);
      // } else {
      //   console.log('Not found.');
      // }
    });

  } // end run
} // end class

module.exports = SkillSearchCommand;


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace System.Windows.Media.Effects
{
    internal struct BitmapEffectInputData
    {
        public BitmapEffect BitmapEffect;
        public BitmapEffectInput BitmapEffectInput;

        public BitmapEffectInputData(BitmapEffect bitmapEffect,
                                    BitmapEffectInput bitmapEffectInput)
        {
            BitmapEffect = bitmapEffect;
            BitmapEffectInput = bitmapEffectInput;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Controllers;

namespace Handlebars.WebApi
{

    public class HandlebarsFormatterAttribute : Attribute, IControllerConfiguration
    {

        public static HandlebarsMediaTypeFormatter Formatter
        {
            set { _formatter = value; }
            get { return _formatter; }
        }

        public static HandlebarsJsonFormatter JsonFormatter
        {
            set { _json = value; }
            get { return _json; }
        }

        private static HandlebarsMediaTypeFormatter _formatter;
        private static HandlebarsJsonFormatter _json;

        public string Area
        {
            get;
            set;
        }

        public void Initialize(HttpControllerSettings controllerSettings,
                               HttpControllerDescriptor controllerDescriptor)
        {
            controllerSettings.Formatters.Remove(controllerSettings.Formatters.JsonFormatter);
            controllerSettings.Formatters.Insert(0, _formatter);
            controllerSettings.Formatters.Insert(1, _json);

            if (!string.IsNullOrEmpty(Area))
                controllerDescriptor.Properties["hb-prefix"] = Area;

            // ensure we can control the media type via a querystring (for handlebars proxy)
            // controllerSettings.Formatters
            //                   .JsonFormatter
            //                   .MediaTypeMappings
            //                   .Add(new QueryStringMapping("x-format", "json", new MediaTypeHeaderValue("application/json")));

        }
    }
}


text:
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance  http://www.springmodules.org/schema/cache/springmodules-cache.xsd http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd"    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd
     ">  <display-name>MyBatisPro05</display-name>
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>

    <!-- Spring配置文件 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	<!-- 编码过滤器 -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<async-supported>true</async-supported>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!-- Spring监听器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- 添加对springmvc的支持 -->
	<servlet>
		<servlet-name>springMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-mvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
		<async-supported>true</async-supported>
	</servlet>
	<servlet-mapping>
		<servlet-name>springMVC</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
</web-app>


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.subscription.fluent.models;

import com.azure.core.annotation.Immutable;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

/** The list of aliases. */
@Immutable
public final class PutAliasListResultInner {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(PutAliasListResultInner.class);

    /*
     * The list of alias.
     */
    @JsonProperty(value = "value", access = JsonProperty.Access.WRITE_ONLY)
    private List<PutAliasResponseInner> value;

    /*
     * The link (url) to the next page of results.
     */
    @JsonProperty(value = "nextLink", access = JsonProperty.Access.WRITE_ONLY)
    private String nextLink;

    /**
     * Get the value property: The list of alias.
     *
     * @return the value value.
     */
    public List<PutAliasResponseInner> value() {
        return this.value;
    }

    /**
     * Get the nextLink property: The link (url) to the next page of results.
     *
     * @return the nextLink value.
     */
    public String nextLink() {
        return this.nextLink;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (value() != null) {
            value().forEach(e -> e.validate());
        }
    }
}


text: val a = macro ??? // error


text:
layout: post
title: "Working with data (tidyr and dplyr)"
instructor: Anne Chambers
permalink: /2_seminar/
materials: files/2_tidyr_dplyr.zip
---

This week we will focus on dealing with data. We'll present basic data manipulation skills you will need for starting your data analysis in R using tidyr and dplyr packages.


text:
import { TestBed, inject } from '@angular/core/testing';

import { PredictionService } from './prediction.service';

describe('PredictionService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [PredictionService]
    });
  });

  it('should be created', inject([PredictionService], (service: PredictionService) => {
    expect(service).toBeTruthy();
  }));
});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>TBCryptHash.HashGetInfo</title>
<link rel="stylesheet" href="../fpdoc.css" type="text/css">

[Overview][Constants][Types][Classes][Index]
Reference for unit 'BCrypt' (#TBCryptHash)

TBCryptHash.HashGetInfo

Declaration

Source position: BCrypt.pas line 245

<tt> public function TBCryptHash.HashGetInfo(</tt>

<tt>  const Hash: AnsiString</tt>

<tt>):RTPasswordInformation;</tt>


text:
<?php

namespace Ekyna\Bundle\OrderBundle\DependencyInjection;

use Ekyna\Bundle\AdminBundle\DependencyInjection\AbstractExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * Class EkynaOrderExtension
 * @package Ekyna\Bundle\OrderBundle\DependencyInjection
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class EkynaOrderExtension extends AbstractExtension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $config = $this->configure($configs, 'ekyna_order', new Configuration(), $container);

        $container->setParameter('ekyna_order.document_logo', $config['document_logo']);
    }

    /**
     * {@inheritDoc}
     */
    public function prepend(ContainerBuilder $container)
    {
        parent::prepend($container);

        $bundles = $container->getParameter('kernel.bundles');

        $container->prependExtensionConfig('ekyna_user', [
            'account' => [
                'enable'    => true,
                'profile'   => true,
                'register'  => true,
                'resetting' => true,
                'address'   => true,
            ],
        ]);

        if (array_key_exists('AsseticBundle', $bundles)) {
            $container->prependExtensionConfig('assetic', [
                'bundles' => ['EkynaOrderBundle']
            ]);
        }
    }
}


text:
<!DOCTYPE html>

<title>input type=file multiple inputs, same name, same form</title>

Select the local/opera.png file in the first file input. Select the local/empty.txt file in the second file input. Press submit. A page containing the word 'PASS' should appear.

<form action="../res/check_md5.php" method="POST" enctype="multipart/form-data">

<input id="f1" type="file" name="test_file" readonly />

<input id="f2" type="file" name="test_file" readonly />

<input id="s" type="submit" />

  <input type="hidden" name="md5" value="d41d8cd98f00b204e9800998ecf8427e" />
</form>


text:
package com.facebook.react.uimanager;

import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_JAVA_BRIDGE;

import com.facebook.react.common.MapBuilder;
import com.facebook.systrace.Systrace;
import com.facebook.systrace.SystraceMessage;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;

/**
 * Helps generate constants map for {@link UIManagerModule} by collecting and merging constants from
 * registered view managers.
 */
/* package */ class UIManagerModuleConstantsHelper {

  private static final String BUBBLING_EVENTS_KEY = "bubblingEventTypes";
  private static final String DIRECT_EVENTS_KEY = "directEventTypes";

  /**
   * Generates a lazy discovery enabled version of {@link UIManagerModule} constants. It only
   * contains a list of view manager names, so that JS side is aware of the managers there are.
   * Actual ViewManager instantiation happens when {@code UIManager.SpecificViewManager} call happens.
   * The View Manager is then registered on the JS side with the help of
   * {@code UIManagerModule.getConstantsForViewManager}.
   */
  /* package */ static Map<String, Object> createConstants(
      UIManagerModule.ViewManagerResolver resolver) {
    Map<String, Object> constants = UIManagerModuleConstants.getConstants();
    constants.put("ViewManagerNames", resolver.getViewManagerNames());
    return constants;
  }

  /* package */ static Map<String, Object> getDefaultExportableEventTypes() {
    return MapBuilder.<String, Object>of(
        BUBBLING_EVENTS_KEY, UIManagerModuleConstants.getBubblingEventTypeConstants(),
        DIRECT_EVENTS_KEY, UIManagerModuleConstants.getDirectEventTypeConstants());
  }

  /**
   * Generates map of constants that is then exposed by {@link UIManagerModule}.
   * Provided list of {@param viewManagers} is then used to populate content of
   * those predefined fields using
   * {@link ViewManager#getExportedCustomBubblingEventTypeConstants} and
   * {@link ViewManager#getExportedCustomDirectEventTypeConstants} respectively. Each view manager
   * is in addition allowed to expose viewmanager-specific constants that are placed under the key
   * that corresponds to the view manager's name (see {@link ViewManager#getName}). Constants are
   * merged into the map of {@link UIManagerModule} base constants that is stored in
   * {@link UIManagerModuleConstants}.
   * TODO(6845124): Create a test for this
   */
  /* package */ static Map<String, Object> createConstants(
        List<ViewManager> viewManagers,
        @Nullable Map<String, Object> allBubblingEventTypes,
        @Nullable Map<String, Object> allDirectEventTypes) {
    Map<String, Object> constants = UIManagerModuleConstants.getConstants();

    // Generic/default event types:
    // All view managers are capable of dispatching these events.
    // They will be automatically registered with React Fiber.
    Map genericBubblingEventTypes = UIManagerModuleConstants.getBubblingEventTypeConstants();
    Map genericDirectEventTypes = UIManagerModuleConstants.getDirectEventTypeConstants();

    // Cumulative event types:
    // View manager specific event types are collected as views are loaded.
    // This information is used later when events are dispatched.
    if (allBubblingEventTypes != null) {
      allBubblingEventTypes.putAll(genericBubblingEventTypes);
    }
    if (allDirectEventTypes != null) {
      allDirectEventTypes.putAll(genericDirectEventTypes);
    }

    for (ViewManager viewManager : viewManagers) {
      final String viewManagerName = viewManager.getName();

      SystraceMessage.beginSection(
              TRACE_TAG_REACT_JAVA_BRIDGE, "UIManagerModuleConstantsHelper.createConstants")
          .arg("ViewManager", viewManagerName)
          .arg("Lazy", false)
          .flush();

      try {
        Map viewManagerConstants = createConstantsForViewManager(
            viewManager,
            null,
            null,
            allBubblingEventTypes,
            allDirectEventTypes);
        if (!viewManagerConstants.isEmpty()) {
          constants.put(viewManagerName, viewManagerConstants);
        }
      } finally {
        Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
      }
    }

    constants.put("genericBubblingEventTypes", genericBubblingEventTypes);
    constants.put("genericDirectEventTypes", genericDirectEventTypes);
    return constants;
  }

  /* package */ static Map<String, Object> createConstantsForViewManager(
      ViewManager viewManager,
      @Nullable Map defaultBubblingEvents,
      @Nullable Map defaultDirectEvents,
      @Nullable Map cumulativeBubblingEventTypes,
      @Nullable Map cumulativeDirectEventTypes) {
    Map<String, Object> viewManagerConstants = MapBuilder.newHashMap();

    Map viewManagerBubblingEvents = viewManager.getExportedCustomBubblingEventTypeConstants();
    if (viewManagerBubblingEvents != null) {
      recursiveMerge(cumulativeBubblingEventTypes, viewManagerBubblingEvents);
      recursiveMerge(viewManagerBubblingEvents, defaultBubblingEvents);
      viewManagerConstants.put(BUBBLING_EVENTS_KEY, viewManagerBubblingEvents);
    } else if (defaultBubblingEvents != null) {
      viewManagerConstants.put(BUBBLING_EVENTS_KEY, defaultBubblingEvents);
    }

    Map viewManagerDirectEvents = viewManager.getExportedCustomDirectEventTypeConstants();
    if (viewManagerDirectEvents != null) {
      recursiveMerge(cumulativeDirectEventTypes, viewManagerDirectEvents);
      recursiveMerge(viewManagerDirectEvents, defaultDirectEvents);
      viewManagerConstants.put(DIRECT_EVENTS_KEY, viewManagerDirectEvents);
    } else if (defaultDirectEvents != null) {
      viewManagerConstants.put(DIRECT_EVENTS_KEY, defaultDirectEvents);
    }

    Map customViewConstants = viewManager.getExportedViewConstants();
    if (customViewConstants != null) {
      viewManagerConstants.put("Constants", customViewConstants);
    }
    Map viewManagerCommands = viewManager.getCommandsMap();
    if (viewManagerCommands != null) {
      viewManagerConstants.put("Commands", viewManagerCommands);
    }
    Map<String, String> viewManagerNativeProps = viewManager.getNativeProps();
    if (!viewManagerNativeProps.isEmpty()) {
      viewManagerConstants.put("NativeProps", viewManagerNativeProps);
    }

    return viewManagerConstants;
  }

  /**
   * Merges {@param source} map into {@param dest} map recursively
   */
  private static void recursiveMerge(@Nullable Map dest, @Nullable Map source) {
    if (dest == null || source == null || source.isEmpty()) {
      return;
    }

    for (Object key : source.keySet()) {
      Object sourceValue = source.get(key);
      Object destValue = dest.get(key);
      if (destValue != null && (sourceValue instanceof Map) && (destValue instanceof Map)) {
        recursiveMerge((Map) destValue, (Map) sourceValue);
      } else {
        dest.put(key, sourceValue);
      }
    }
  }
}


text:
void InitAll(v8::Local<v8::Object> exports) {
  EntityExtractor::Init(exports);
  RelationExtractor::Init(exports);
}

NODE_MODULE(mitie, InitAll)