text:
Funding FormPreview

<a href="<?php echo base_url();?>administrator/dashboard"> Home

<a href="<?php echo base_url();?>administrator/fund-list"> Funding List

 Slider

								<?php if($this->session->flashdata('error')){?>

                                        <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
                                        Alert!<?php echo $this->session->flashdata('error') ;?>

                                   <?php }  if($this->session->flashdata('sucess')) {?>

                                        <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
                                        Alert!<?php echo  $this->session->flashdata('sucess');?>

									<?php }?>

                                <form role="form" method="post" name="content_frm" id="content_frm" action="<?php echo base_url();?>admin/funding/funding_action" enctype="multipart/form-data" >
								<input type="hidden"  name="fund_id" id="fund_id" value="<?php echo $fund_id;?>" />

								<input type="hidden"  name="fund_old_image" id="fund_old_title" value="<?php if($fund_id>0){ echo $list[0]->fund_image;	}?>" />

												 Funding Title
												<input class="form-control" type="text" id="fund_title" name="fund_title" value="<?php if($fund_id>0){echo $list[0]->fund_title;}?>" required="required">
												Posted

												<input class="form-control" type="text" id="posted_date" name="fund_posted" value="<?php if($fund_id>0){echo $list[0]->fund_posted;}?>" required="required">

												Company Name
												<input class="form-control" type="text" id="fund_company" name="fund_company" value="<?php if($fund_id>0){echo $list[0]->fund_company; }?>" required="required">
												Deadlint

												<input class="form-control" type="text"  id="deadline_date" name="fund_decline" value="<?php if($fund_id>0){echo $list[0]->fund_decline;	}?>" required="required">

												Reward
												<input type="text" class="form-control" id="fund_reward" name="fund_reward" value="<?php if($fund_id>0){echo $list[0]->fund_reward;	}?>" required="required">
												Cover Picture
												<input class="form-control" type="file"  id="fund_coverpic" name="fund_coverpic" value="" required="required">

												ID
												<input class="form-control" type="text"  id="fund_customID" name="fund_customID" value="<?php if($fund_id>0){echo $list[0]->fund_customID;	}?>" required="required">
												Country
												<input class="form-control" type="text"  id="fund_country" name="fund_country" value="<?php if($fund_id>0){echo $list[0]->fund_country;}?>" required="required">

												Funding Infromation
												<textarea class="form-control" name="fund_info" id="fund_info"><?php if($fund_id>0) {echo $list[0]->fund_info;}?></textarea>

                                        <button type="submit" class="btn btn-primary" name="cat_button" value="<?php echo $but_value?>">Submit</button>

                                </form>


text:
include $(TOPDIR)/config.mk

all:
ifeq ($(notdir $(shell find ./ -name lib-dram)), lib-dram)

	make -C lib-dram
else
	@echo "libdram exist"

endif

ifeq ($(CONFIG_ARCH_HOMELET),y)
	cp ./libdram-homlet ./libdram.o
else
	cp ./libdram-pad ./libdram.o
endif
#########################################################################

# defines $(obj).depend target
include $(SRCTREE)/rules.mk

sinclude $(obj).depend

#########################################################################

redpajama_set_name: RedPajamaGithub


text:
package org.larsworks.bitcoin.app.core.util.ssl;

import org.larsworks.bitcoin.app.core.exceptions.BitcoinAppException;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import java.io.InputStream;
import java.net.URL;
import java.security.KeyStore;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

/**
 * @author Lars Kleen
 * @since ?version
 *        Date: 27.09.15
 *        Time: 13:23
 */
public class UnsignedX509CertificateHandler implements UnsignedCertificateHandler {
    @Override
    public SSLSocketFactory createSSLSocketFactory(InputStream inputStream) {
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(inputStream);

            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, null);
            keyStore.setCertificateEntry("1", certificate);

            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustManagerFactory.getTrustManagers(), null);

            return sslContext.getSocketFactory();

        } catch (Exception e) {
            throw new BitcoinAppException(e);
        }
    }
}


text:
<?php

include_once __DIR__ . "/../../src/Autoloader.php";
PhpXmlRpc\Autoloader::register();

/**
 * Forward an xmlrpc request to another server, and return to client the response received.
 *
 * DO NOT RUN AS IS IN PRODUCTION - this is an open relay !!!
 *
 * @param PhpXmlRpc\Request $req (see method docs below for a description of the expected parameters)
 *
 * @return PhpXmlRpc\Response
 */
function forward_request($req)
{
    $encoder = new \PhpXmlRpc\Encoder();

    // create client
    $timeout = 0;
    $url = $encoder->decode($req->getParam(0));
    $client = new PhpXmlRpc\Client($url);

    if ($req->getNumParams() > 3) {
        // we have to set some options onto the client.
        // Note that if we do not untaint the received values, warnings might be generated...
        $options = $encoder->decode($req->getParam(3));
        foreach ($options as $key => $val) {
            switch ($key) {
                case 'Cookie':
                    break;
                case 'Credentials':
                    break;
                case 'RequestCompression':
                    $client->setRequestCompression($val);
                    break;
                case 'SSLVerifyHost':
                    $client->setSSLVerifyHost($val);
                    break;
                case 'SSLVerifyPeer':
                    $client->setSSLVerifyPeer($val);
                    break;
                case 'Timeout':
                    $timeout = (integer)$val;
                    break;
            } // switch
        }
    }

    // build call for remote server
    /// @todo find a way to forward client info (such as IP) to server, either
    /// - as xml comments in the payload, or
    /// - using std http header conventions, such as X-forwarded-for...
    $reqMethod = $encoder->decode($req->getParam(1));
    $pars = $req->getParam(2);
    $req = new PhpXmlRpc\Request($reqMethod);
    foreach ($pars as $par) {
        $req->addParam($par);
    }

    // add debug info into response we give back to caller
    PhpXmlRpc\Server::xmlrpc_debugmsg("Sending to server $url the payload: " . $req->serialize());

    return $client->send($req, $timeout);
}

// run the server
$server = new PhpXmlRpc\Server(
    array(
        'xmlrpcproxy.call' => array(
            'function' => 'forward_request',
            'signature' => array(
                array('mixed', 'string', 'string', 'array'),
                array('mixed', 'string', 'string', 'array', 'struct'),
            ),
            'docstring' => 'forwards xmlrpc calls to remote servers. Returns remote method\'s response. Accepts params: remote server url (might include basic auth credentials), method name, array of params, and (optionally) a struct containing call options',
        ),
    )
);


text:
<?php
session_start();

if ($_SESSION['prize_banker'] || $_COOKIE['prize_banker']){
		header("Location: dashboard.php");
}

include "../inc/configuration.php";
include "../inc/functions.php";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>AdminTheme - Ultimate Admin Panel Solution</title>
	<meta name="description" content="" />
    <meta name="keywords" content="" />
    <meta name="robots" content="index,follow" />

    <link rel="stylesheet" type="text/css" media="all" href="css/style.css" />
	<link rel="Stylesheet" type="text/css" href="css/smoothness/jquery-ui-1.7.1.custom.css"  />

AdmintTheme

        <?php
		if ($_POST['submit']){
			$username = $_POST['username'];
			$password = strtolower($_POST['password']);
			if (!($_POST['rememberme'])){
				$rememberme = "off";
			}else{
				$rememberme = "on";
			}

			echo AdminLogin($username,$password,$rememberMe);
		}
		?>
	    	<form name="loginform" id="loginform" action="" method="post">

			Username<input type="text" name="username" id="username"  size="28" class="input"/>

			Password<input type="password" name="password" id="password"  size="28" class="input"/>

			Remember Me<input type="checkbox" name="rememberme" id="rememberme" value="on" class="input noborder" />

			<input id="save" class="loginbutton" type="submit" class="submit" name="submit" value="Log In" />

			</form>

			Forgot your username or password?


text:
// -----------------------------------------------------------------------
//  <copyright file="ClientSecret.cs" company="OSharp开源团队">
//      Copyright (c) 2014-2015 OSharp. All rights reserved.
//  </copyright>
//  <site>http://www.osharp.org</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2015-11-05 19:00</last-date>
// -----------------------------------------------------------------------

using OSharp.Core.Security.Models;

namespace OSharp.Demo.Models.OAuth
{
    /// <summary>
    /// 实体类——OAuth客户端密钥信息
    /// </summary>
    public class OAuthClientSecret : OAuthClientSecretBase<int, OAuthClient, int>
    { }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="TITLE_DATA_UPDATE_NOTIF_TITLE">Ελληνικός Κατάλογος</string>
    <string name="TITLE_DATA_UPDATED">Τα δεδομένα ενημερώθηκαν επιτυχώς</string>
    <string name="TITLE_GREECE_VISITOR">Greece Visitor\'s</string>
    <string name="TITLE_PHONEBOOK">PhoneBook</string>
    <string name="TITLE_EDIT_ENTRY">Επεξεργασία εγγραφής</string>
    <string name="TITLE_ADD_ENTRY">Προσθήκη εγγραφής</string>
    <string name="ACTION_SETTINGS">Ρυθμίσεις</string>
    <string name="LBL_VISIT_BYTECODE">Άνοιγμα της ιστοσελίδας</string>
    <string name="LBL_POLICE">Αστυνομία</string>
    <string name="LBL_HELPLINES">Γραμμή Βοήθειας</string>
    <string name="LBL_PUBLIC_SERVCES">Υπηρεσίες</string>
    <string name="LBL_EMBASSIES">Πρεσβείες</string>
    <string name="LBL_TRANSPORTATION">Μεταφορές</string>
    <string name="LBL_INFORMATION">Γενικές Πληροφορίες</string>
    <string name="LBL_EMERGENCY">Επείγοντα</string>
    <string name="LBL_HEALTHCARE">Υγειονομικά</string>
    <string name="LBL_SETTINGS">Ρυθμίσεις</string>
    <string name="LBL_CHECK_DATA_NOW">Έλεγχος δεδομένων τώρα</string>
    <string name="LBL_SEND_EMAIL">Ε-mail</string>
    <string name="LBL_SAVE">Αποθήκευση</string>
    <string name="TXT_CAT_DATA_SYNCH">Ενημερώσεις δεδομένων</string>
    <string name="TXT_TITLE_AUTO_DATA_CHECK">Αυτόματες ενημερώσεις</string>
    <string name="TXT_SUMMARY_AUTO_DATA_CHECK">Ενημέρωση δεδομένων όταν η συσκευή είναι συνδεδεμένη στο δίκτυο</string>
    <string name="TXT_TITLE_AUTO_DATA_CHECK_INTERVAL">Συχνότητα ελέγχων</string>
    <string name="TXT_SUMMARY_AUTO_DATA_CHECK_INTERVAL">Έλεγχος δεδομένων ανά %s ημέρες</string>
    <string name="TXT_ACTIVE">Ενεργό</string>
    <string name="TXT_INACTIVE">Ανενεργό</string>
    <string name="TXT_NEVER_CHECKED">Δεν έγινε έλεγχος</string>
    <string name="TXT_SEND_US_AN_EMAIL">Στείλε μας ένα σχόλιο</string>
    <string name="TXT_BYTECODE_EMAIL">phonebook@bytecode.gr</string>
    <string name="TXT_BYTECODE_URL">http://bytecode.gr</string>
    <string name="TXT_SEND_EMAIL_SUBJ">[PhoneBook Android App] Νέο Μήνυμα</string>
    <string name="TXT_VISIT_BYTECODE">Επίσκεψη στο ByteCode.gr</string>
    <string name="TITLE_SEND_EMAIL_CHOOSER">Επικοινώνησε με την ByteCode.gr</string>
    <string name="ΤΧΤ_EVERY_DAY">Ημερησίως</string>
    <string name="ΤΧΤ_EVERY_7_DAYS">Εβδομαδιαίως</string>
    <string name="ΤΧΤ_EVERY_30_DAYS">Μηνιαίως</string>
    <string name="ΤΧΤ_EVERY_90_DAYS">Ανα τρίμηνο</string>
    <string name="TXT_TITLE_LAST_DATA_UPDATE">Τελευταία ενημέρωση</string>
    <string name="TXT_UPDATE_STARTED">Η διαδικασία ανανέωσης δεδομένων ξεκίνησε</string>
    <string name="TXT_CLOSE">Κλείσιμο</string>
    <string name="TXT_UPDATE_NOW">Ανανέωση τώρα</string>
    <string name="TXT_UPDATE_ANYWAY">Ανανέωση δεδομένων</string>
    <string name="TXT_NEW_DATA_FOUND">Βρέθηκαν νέα δεδομένα</string>
    <string name="TXT_DATA_IS_UP_TO_DATE">Τα δεδομένα είναι ενημερωμένα.</string>
    <string name="NUM_DEFAULT_CALL_NUMBER">112</string>
    <string name="TXT_CAT_FEATURES">Πειραματικές λειτουργίες</string>
    <string name="TXT_HOVER_CALL">Hover display για κλήση ανάκγης</string>
    <string name="TITLE_HOVER_CALL">Hover Call</string>
    <string name="TXT_ADD">Προσθήκη</string>
    <string name="TXT_TIP_ORGANIZATION_NAME">Όνομα…</string>
    <string name="TXT_NAME">Ονομα</string>
    <string name="TXT_PHONE_NUMBER">Αριθμός…</string>
    <string name="TXT_TIP_PHONE_NUMBER">Αριθμός τηλεφώνου</string>
    <string name="TXT_WEBSITE_ADDRESS">Διεύθυνση ιστοσελίδας</string>
    <string name="TXT_TIP_WEBSITE_ADDRESS">Ιστοσελίδα (προαιρετικά)</string>
    <string name="TXT_SHARE_THIS_ENTRY">Δημοσιοποίηση της καταχώρησης</string>
    <string name="TXT_EDIT">Επεξεργασία</string>
    <string name="TXT_DELETE">Διαγραφή</string>
    <string name="TXT_MANAGE_ENTRY">Επεξεργασία καταχώρησης</string>
    <string name="TXT_ENTRY_REMOVED">Η καταχώρηση αφαιρέθηκε</string>
    <string name="TXT_CUSTOM">Δικά μου</string>
    <string name="TXT_EMPTY_ENTRY_LIST_TIP">Tap the plus symbol on the menu to add a new entry</string>
    <string name="TXT_UPDATE_CATEGORY">Update Category</string>
    <string name="ΤΧΤ_EMPTY"></string>
    <string name="ΤΧΤ_BYTECODE">Εφαρμογές από την ByteCode.gr</string>
    <string name="TXT_APPNAME">Greece PhoneBook</string>
    <string name="TXT_SHORT">ΤΧΤ_SHORT</string>
    <string name="TXT_LONG">asdasdasdasdad asd asdasdasd</string>
    <string name="ERROR_NOT_VALID_WEB_ADDRESS">This is not a valid Web Address</string>
    <string name="ERROR_REQUIRED_FIELD">Required data</string>
    <string name="ERROR_NO_NETWORK">Internet connection is not available at this time</string>
    <string name="TXT_CAT_BYTECODE">ByteCode.gr</string>

</resources>


text:
#include "virtual_fs.h"

const char *board_id = "1021";

const vfs_filename_t daplink_drive_name =     "MBED       ";


text:
DROP INDEX xml_tree_values_result_simple_path_idx;

ALTER TABLE xml_tree_values DROP COLUMN simple_path;


text:
"""
Test how lldb reacts to wrong commands
"""

from __future__ import print_function

import os
import time
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil

class UnknownCommandTestCase(TestBase):

    mydir = TestBase.compute_mydir(__file__)

    @no_debug_info_test
    def test_ambiguous_command(self):
        command_interpreter = self.dbg.GetCommandInterpreter()
        self.assertTrue(command_interpreter, VALID_COMMAND_INTERPRETER)
        result = lldb.SBCommandReturnObject()

        command_interpreter.HandleCommand("g", result)
        self.assertFalse(result.Succeeded())
        self.assertRegexpMatches(result.GetError(), "Ambiguous command 'g'. Possible matches:")
        self.assertRegexpMatches(result.GetError(), "gui")
        self.assertRegexpMatches(result.GetError(), "gdb-remote")
        self.assertEquals(1, result.GetError().count("gdb-remote"))

    @no_debug_info_test
    def test_unknown_command(self):
        command_interpreter = self.dbg.GetCommandInterpreter()
        self.assertTrue(command_interpreter, VALID_COMMAND_INTERPRETER)
        result = lldb.SBCommandReturnObject()

        command_interpreter.HandleCommand("qbert", result)
        self.assertFalse(result.Succeeded())
        self.assertEquals(result.GetError(), "error: 'qbert' is not a valid command.\n")


text:
<?php

namespace Eway\Rapid\Model\Support;

use Eway\Rapid\Model\Item;

/**
 * Trait HasItemsTrait.
 */
trait HasItemsTrait
{
    /**
     * @param array $items
     *
     * @return $this
     */
    public function setItemsAttribute($items)
    {
        if (!is_array($items)) {
            throw new \InvalidArgumentException('Items must be an array');
        }

        foreach ($items as $key => $item) {
            if (!($item instanceof Item)) {
                $items[$key] = new Item($item);
            }
        }

        $this->attributes['Items'] = $items;

        return $this;
    }
}


text:
ECHO "Clean It"
CALL clean-it.bat

ECHO "Build It"
CALL build-it.bat

ECHO "Remove DBS"
CALL remove-dbs.bat

ECHO "INVOKE IT"
CALL invoke-it.bat


text:
<!doctype html>

    <title>Rose-Hulman eSports</title>
    <link rel="shortcut icon" href="{{ url_for('static', filename='img/favicon.ico') }}">
    <meta name="viewport" content="width=device-width">
    <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css">

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

          </button>
          eSports Club

              Home

              About

              Members

              Events

Next Event: {{ nextE }}

Rose-Hulman eSports Club

Rose-Hulman's eSports Club is dedicated to bringing fans of competitive gaming together to enjoy the community and all the excitement that competitions can bring.

Learn more »

eSports Club News

League of Legends Tournament Announced

The Rose-Hulman eSports Club has announced our next League of Legends Tournament to be on March 14-15, 2015. We have been endorsed by Riot so there will be many RP prizes as well as a triumphant ryze skin for the winning team. The second day of the event will be for the two final teams to play a best of three. Go to our events page to find out more!

Posted on: 12/3/14

Looking to Next Year

The Rose-Hulman eSports Club got approved for its second year budget. The budget is much larger than the first which means we can make events that bring in more participants as well as create a better expereince at the events we host. We are planning to have a club meeting at the beginning of the academic year to figure out when these events should occur.

Posted on: 7/20/14

Our first club mixer has been announced!

The Rose-Hulman eSports Club will be hosting its first club mixer on May 3rd, 2014! This event will have brackets for multiple games as well as giveaways and free pizza. There will also be an ASUS representative present to demo some great stuff! Go to our events page to find out more!

Posted on: 4/21/14

Congratulations to team Sad Boys!

Team Sad Boys was able to win this years League of Legends tournament! Click Here to see the full bracket and here to watch some of the games that were streamed.

Posted on: 2/23/14

Our first competition has been announced!

The Rose-Hulman eSports Club will be hosting its first event on February 22nd, 2014! This event will be a League of Legends tournament consisting of a 5v5 bracket as well as a 1v1 bracket. Go to our events page to find out more!

Posted on: 1/21/14

Our site is finally up!

After some hard work from our members the Rose-Hulman eSports website is up and running! This will be the place that the club will post its events and provide detail about what our club does. Be on the watch for our first event shortly!

Posted on: 1/16/14

© Rose-Hulman eSports Club 2014


text:
package com.feilong.core.net.paramutiltest;

import static com.feilong.core.util.MapUtil.newHashMap;
import static org.apache.commons.lang3.StringUtils.EMPTY;
import static org.junit.Assert.assertEquals;

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

import com.feilong.core.net.ParamUtil;

public class ToNaturalOrderingJoinValueTest{

    @Test
    public void testtoNaturalOrderingJoinValueNullMap(){
        assertEquals(EMPTY, ParamUtil.toNaturalOrderingJoinValue(null));
    }

    @Test
    public void testtoNaturalOrderingJoinValueEmptyMap(){
        assertEquals(EMPTY, ParamUtil.toNaturalOrderingJoinValue(new HashMap<String, String>()));
    }

    //---------------------------------------------------------------

    @Test
    public void testtoNaturalOrderingJoinValue(){
        Map<String, String> map = newHashMap();
        map.put("service", "create_salesorder");
        map.put("_input_charset", "gbk");
        map.put("totalActual", "210.00");
        map.put("address", "江苏南通市通州区888组888号");

        assertEquals("gbk江苏南通市通州区888组888号create_salesorder210.00", ParamUtil.toNaturalOrderingJoinValue(map));
    }

    @Test
    public void testtoNaturalOrderingJoinValueNullValue(){
        Map<String, String> map = newHashMap();
        map.put("service", null);
        map.put("totalActual", "210.00");
        map.put("province", "江苏省");

        assertEquals("江苏省210.00", ParamUtil.toNaturalOrderingJoinValue(map));
    }

    @Test
    public void testtoNaturalOrderingJoinValueNullKey(){
        Map<String, String> map = newHashMap();
        map.put("totalActual", null);
        map.put(null, "create_salesorder");
        map.put("province", "江苏省");

        assertEquals("create_salesorder江苏省", ParamUtil.toNaturalOrderingJoinValue(map));
    }
}


text:
__author__ = '@abhinavbom a.k.a darkl0rd'

import sys
import os
import urllib2
from xml.dom import minidom
from urllib import quote

from lib.parse import *

# Base API URL
base_url = 'http://api.urlvoid.com/'

# API Key . Key can be obtained from api.urlvoid.com
api_key = '<Add API key Here>'+'/'
if api_key == '<Add API key Here>/':
    print "Please add your Urlvoid API key"
    sys.exit()

# plan identifier. change this value as per your plan in URLvoid. Free plans are designated by api1000 which is the
#default value here.

plan = 'api1000/'

#search for a host in URLvoid
detect = 'host/'

def urlvoid(url):
    c=0
    print "Conneting to URLVoid"
    while c < len(url):
        print url[c]
        final_url = base_url+plan+api_key+detect+url[c]
        #print final_url
        if HTTP_PROXY or HTTPS_PROXY:
            proxy = urllib2.ProxyHandler({'http': HTTP_PROXY, 'https': HTTPS_PROXY})
            opener = urllib2.build_opener(proxy)
            urllib2.install_opener(opener)
        req = urllib2.urlopen(final_url)
        resp = req.read()
        print resp
        tree = minidom.parseString(resp)
        print tree
        obs_value = tree.getElementsByTagName('detections')
        for value in obs_value:
            print value.firstChild.nodeValue

        #for detections in tree.iter('detections'):
        #    print detections.attrib
        #print resp
        c+=1


text:
import hashlib
import logging

import cryptography.hazmat.primitives.hashes as c_hashes
import cryptography.hazmat.primitives.kdf.hkdf as c_hkdf
import cryptography.hazmat.primitives.asymmetric.ec as c_ec
import cryptography.hazmat.primitives.serialization as c_ser
import cryptography.hazmat.primitives.asymmetric.utils as c_utils

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.backends import default_backend

import synapse.common as s_common

logger = logging.getLogger(__name__)

class PriKey:
    '''
    A helper class for using ECC private keys.
    '''
    def __init__(self, priv):
        self.priv = priv  # type: c_ec.EllipticCurvePrivateKey
        self.publ = PubKey(self.priv.public_key())

    def iden(self):
        '''
        Return a SHA256 hash for the public key (to be used as a GUID).

        Returns:
            str: The SHA256 hash of the public key bytes.
        '''
        return self.publ.iden()

    def sign(self, byts):
        '''
        Compute the ECC signature for the given bytestream.

        Args:
            byts (bytes): The bytes to sign.

        Returns:
            bytes: The RSA Signature bytes.
        '''
        chosen_hash = c_hashes.SHA256()
        hasher = c_hashes.Hash(chosen_hash, default_backend())
        hasher.update(byts)
        digest = hasher.finalize()
        return self.priv.sign(digest,
                              c_ec.ECDSA(c_utils.Prehashed(chosen_hash))
                              )

    def exchange(self, pubkey):
        '''
        Perform a ECDH key exchange with a public key.

        Args:
            pubkey (PubKey): A PubKey to perform the ECDH with.

        Returns:
            bytes: The ECDH bytes. This is deterministic for a given pubkey
            and private key.
        '''
        try:
            return self.priv.exchange(c_ec.ECDH(), pubkey.publ)
        except ValueError as e:
            raise s_common.BadEccExchange(mesg=str(e))

    def public(self):
        '''
        Get the PubKey which corresponds to the ECC PriKey.

        Returns:
            PubKey: A new PubKey object whose key corresponds to the private key.
        '''
        return PubKey(self.priv.public_key())

    @staticmethod
    def generate():
        '''
        Generate a new ECC PriKey instance.

        Returns:
            PriKey: A new PriKey instance.
        '''
        return PriKey(c_ec.generate_private_key(
            c_ec.SECP384R1(),
            default_backend()
        ))

    def dump(self):
        '''
        Get the private key bytes in DER/PKCS8 format.

        Returns:
            bytes: The DER/PKCS8 encoded private key.
        '''
        return self.priv.private_bytes(
            encoding=c_ser.Encoding.DER,
            format=c_ser.PrivateFormat.PKCS8,
            encryption_algorithm=c_ser.NoEncryption())

    @staticmethod
    def load(byts):
        '''
        Create a PriKey instance from DER/PKCS8 encoded bytes.

        Args:
            byts (bytes): Bytes to load

        Returns:
            PriKey: A new PubKey instance.
        '''
        return PriKey(c_ser.load_der_private_key(
                byts,
                password=None,
                backend=default_backend()))

class PubKey:
    '''
    A helper class for using ECC public keys.
    '''

    def __init__(self, publ):
        self.publ = publ  # type: c_ec.EllipticCurvePublicKey

    def dump(self):
        '''
        Get the public key bytes in DER/SubjectPublicKeyInfo format.

        Returns:
            bytes: The DER/SubjectPublicKeyInfo encoded public key.
        '''
        return self.publ.public_bytes(
            encoding=c_ser.Encoding.DER,
            format=c_ser.PublicFormat.SubjectPublicKeyInfo)

    def verify(self, byts, sign):
        '''
        Verify the signature for the given bytes using the ECC
        public key.

        Args:
            byts (bytes): The data bytes.
            sign (bytes): The signature bytes.

        Returns:
            bool: True if the data was verified, False otherwise.
        '''
        try:
            chosen_hash = c_hashes.SHA256()
            hasher = c_hashes.Hash(chosen_hash, default_backend())
            hasher.update(byts)
            digest = hasher.finalize()
            self.publ.verify(sign,
                             digest,
                             c_ec.ECDSA(c_utils.Prehashed(chosen_hash))
                             )
            return True
        except InvalidSignature as e:
            logger.exception('Error in publ.verify')
            return False

    def iden(self):
        '''
        Return a SHA256 hash for the public key (to be used as a GUID).

        Returns:
            str: The SHA256 hash of the public key bytes.
        '''
        return hashlib.sha256(self.dump()).hexdigest()

    @staticmethod
    def load(byts):
        '''
        Create a PubKey instance from DER/PKCS8 encoded bytes.

        Args:
            byts (bytes): Bytes to load

        Returns:
            PubKey: A new PubKey instance.
        '''
        return PubKey(c_ser.load_der_public_key(
                byts,
                backend=default_backend()))

def doECDHE(statprv_u, statpub_v, ephmprv_u, ephmpub_v,
            length=64,
            salt=None,
            info=None):
    '''
    Perform one side of an Ecliptic Curve Diffie Hellman Ephemeral key exchange.

    Args:
        statprv_u (PriKey): Static Private Key for U
        statpub_v (PubKey: Static Public Key for V
        ephmprv_u (PriKey): Ephemeral Private Key for U
        ephmpub_v (PubKey): Ephemeral Public Key for V
        length (int): Number of bytes to return
        salt (bytes): Salt to use when computing the key.
        info (bytes): Additional information to use when computing the key.

    Notes:
        This makes no assumption about the reuse of the Ephemeral keys passed
        to the function. It is the caller's responsibility to destroy the keys
        after they are used for doing key generation. This implementation is
        the dhHybrid1 scheme described in NIST 800-56A Revision 2.

    Returns:
        bytes: The derived key.
    '''
    zs = statprv_u.exchange(statpub_v)
    ze = ephmprv_u.exchange(ephmpub_v)
    z = ze + zs
    kdf = c_hkdf.HKDF(c_hashes.SHA256(),
                      length=length,
                      salt=salt,
                      info=info,
                      backend=default_backend())
    k = kdf.derive(z)
    return k


text:
import platform
from rhlib import BCFMode
from rhlib import get_bcf_mode
from send_lldp import send_lldp

def main():
    platform_os = platform.linux_distribution()[0]
    if "red hat" in platform_os.strip().lower():
        if BCFMode.MODE_P_V == get_bcf_mode():
            return
    send_lldp()

if __name__ == "__main__":
    main()


text:
all: brew bash docker

brew:
	sh ./brew.sh

bash:
	sh ./bashrc.sh

docker:
	sh ./docker.sh

envs: brew bash


text:
/**
 * FileTree Translation : Slovak sk_SK
 *
 * @author     Ing. Jozef Sakáloš
 * @translator Ing. Jozef Sakáloš
 * @date       21. March 2008
 *
 *
 * @license FileTree Translation file is licensed under the terms of
 * the Open Source LGPL 3.0 license.  Commercial use is permitted to the extent
 * that the code/component(s) do NOT become part of another Open Source or Commercially
 * licensed development library or toolkit without explicit permission.
 *
 * License details: http://www.gnu.org/licenses/lgpl.html
 */
if(Ext.ux.FileUploader){
    Ext.override(Ext.ux.FileUploader, {
        jsonErrorText:'JSON objekt sa nedá dekódovať',
        unknownErrorText:'Neznáma chyba'
    });
}

if(Ext.ux.UploadPanel){
    Ext.override(Ext.ux.UploadPanel, {
        addText:'Pridať',
        clickRemoveText:'Klikni na odobratie',
        clickStopText:'Klikni na zastavenie',
        emptyText:'Žiadne súbory',
        errorText:'Chyba',
        fileQueuedText:'Súbor {0} je pripravený na odoslanie' ,
        fileDoneText:'Súbor {0} bol úspešne odoslaný',
        fileFailedText:'Odosielanie súboru {0} zlyhalo',
        fileStoppedText:'Odosielanie súboru {0} zastavené užívateľom',
        fileUploadingText:'Odosielanie súboru {0}',
        removeAllText:'Odobrať všetky',
        removeText:'Odobrať',
        stopAllText:'Zastaviť všetky',
        uploadText:'Odoslať'
    });
}

if(Ext.ux.FileTreeMenu){
    Ext.override(Ext.ux.FileTreeMenu, {
    collapseText: 'Zbaliť všetky',
    deleteKeyName:'Kláves Delete',
    deleteText:'Vymazať',
    expandText: 'Rozbaliť všetky',
    newdirText:'Nová zložka',
    openBlankText:'Otvoriť v novom okne',
    openDwnldText:'Stiahnuť',
    openPopupText:'Otvoriť v dialógu',
    openSelfText:'Otvoriť v tomto okne',
    openText:'Otvoriť',
    reloadText:'Aktualizovať',
    renameText: 'Premenovať',
    uploadFileText:'Odoslať súbor',
    uploadText:'Odoslať'
    });
}

if(Ext.ux.FileTreePanel){
    Ext.override(Ext.ux.FileTreePanel, {
        confirmText:'Potvrdiť',
        deleteText:'Vymazať',
        errorText:'Chyba',
        existsText:'Súbor {0} už existuje',
        fileText:'Súbor',
        newdirText:'Nová zložka',
        overwriteText:'Chceš ho prepísať?',
        reallyWantText:'Naozaj chceš',
        rootText:'Koreň stromu'
    });
}

// eof


text:
export * from './report/aaci'
export * from './report/battle-api'
export * from './report/create-item'
export * from './report/create-ship'
export * from './report/drop-ship'
export * from './report/enemy-info'
export * from './report/night-battle-ci'
export * from './report/night-contact'
export * from './report/pass-event'
export * from './report/quest'
export * from './report/recipe'
export * from './report/remodel-item'
export * from './report/select-rank'
export * from './report/ship-stat'
export * from './report/quest-reward'


text:
using System.Collections.Generic;
using System.Linq.Expressions;
using InterSystems.Globals;

namespace GlobalsFramework.Linq.ExpressionProcessing
{
    internal sealed class ParameterExpressionProcessor : IExpressionProcessor
    {
        public bool CanProcess(Expression expression)
        {
            return expression.NodeType == ExpressionType.Parameter;
        }

        public ProcessingResult ProcessExpression(Expression expression, List<NodeReference> references, DataContext context)
        {
            return new ProcessingResult(true, context.CopyReferences(references));
        }
    }
}


text:
* Selectively compile nodes. (@norcalli)
* Updated for newer AST tree with literals, classes and any. (@norcalli)

## Version 0.2.1
* Fix indentation bug in the initializer.

## Version 0.2.0
* Switch to the new plugin structure of pegjs 0.8.
* Bundle CoffeeScript with the plugin for the browser.
* Make peg.js a peer dependency.
* Use browserify for building the web version.
* Make the github repo itself a valid npm module.
* Implement tests and the plugin itself in JavaScript to have less building.

## Version 0.1.0
* Initial release


text:
package eu.appbucket.queue.core.service2.estimator.duration;

import eu.appbucket.queue.core.domain.queue.QueueDetails;
import eu.appbucket.queue.core.domain.ticket.TicketEstimation;
import eu.appbucket.queue.core.domain.ticket.TicketUpdate;

import java.util.Collection;

public interface WaitingTimeEstimationStrategy {
	TicketEstimation estimateTimeToBeServiced(
            QueueDetails queueDetails, Collection<TicketUpdate> ticketUpdates, int ticketNumber);
}


text:
.class Landroid/widget/IMECursorAdapter$1;
.super Landroid/widget/CursorFilter;
.source "IMECursorAdapter.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Landroid/widget/IMECursorAdapter;->getFilter()Landroid/widget/Filter;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Landroid/widget/IMECursorAdapter;

# direct methods
.method constructor <init>(Landroid/widget/IMECursorAdapter;Landroid/widget/CursorFilter$CursorFilterClient;)V
    .locals 0
    .parameter
    .parameter "x0"

    .prologue
    .line 66
    iput-object p1, p0, Landroid/widget/IMECursorAdapter$1;->this$0:Landroid/widget/IMECursorAdapter;

    invoke-direct {p0, p2}, Landroid/widget/CursorFilter;-><init>(Landroid/widget/CursorFilter$CursorFilterClient;)V

    return-void
.end method

# virtual methods
.method protected performFiltering(Ljava/lang/CharSequence;)Landroid/widget/Filter$FilterResults;
    .locals 5
    .parameter "constraint"

    .prologue
    .line 69
    iget-object v3, p0, Landroid/widget/IMECursorAdapter$1;->mClient:Landroid/widget/CursorFilter$CursorFilterClient;

    invoke-interface {v3, p1}, Landroid/widget/CursorFilter$CursorFilterClient;->runQueryOnBackgroundThread(Ljava/lang/CharSequence;)Landroid/database/Cursor;

    move-result-object v0

    .line 70
    .local v0, cursor:Landroid/database/Cursor;
    if-eqz p1, :cond_2

    if-eqz v0, :cond_0

    invoke-interface {v0}, Landroid/database/Cursor;->getCount()I

    move-result v3

    if-nez v3, :cond_2

    .line 71
    :cond_0
    if-eqz v0, :cond_1

    invoke-interface {v0}, Landroid/database/Cursor;->isClosed()Z

    move-result v3

    if-nez v3, :cond_1

    invoke-interface {v0}, Landroid/database/Cursor;->close()V

    .line 77
    :cond_1
    iget-object v3, p0, Landroid/widget/IMECursorAdapter$1;->this$0:Landroid/widget/IMECursorAdapter;

    invoke-virtual {p1}, Ljava/lang/Object;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-virtual {v3, v4}, Landroid/widget/IMECursorAdapter;->stringCorrection(Ljava/lang/String;)Ljava/util/ArrayList;

    move-result-object v2

    .line 78
    .local v2, ret:Ljava/util/ArrayList;,"Ljava/util/ArrayList<Ljava/lang/String;>;"
    iget-object v3, p0, Landroid/widget/IMECursorAdapter$1;->this$0:Landroid/widget/IMECursorAdapter;

    invoke-virtual {v3, v2}, Landroid/widget/IMECursorAdapter;->reQueryOnBackgroundThread(Ljava/util/ArrayList;)Landroid/database/Cursor;

    move-result-object v0

    .line 82
    .end local v2           #ret:Ljava/util/ArrayList;,"Ljava/util/ArrayList<Ljava/lang/String;>;"
    :cond_2
    new-instance v1, Landroid/widget/Filter$FilterResults;

    invoke-direct {v1}, Landroid/widget/Filter$FilterResults;-><init>()V

    .line 83
    .local v1, results:Landroid/widget/Filter$FilterResults;
    if-eqz v0, :cond_3

    .line 84
    invoke-interface {v0}, Landroid/database/Cursor;->getCount()I

    move-result v3

    iput v3, v1, Landroid/widget/Filter$FilterResults;->count:I

    .line 85
    iput-object v0, v1, Landroid/widget/Filter$FilterResults;->values:Ljava/lang/Object;

    .line 90
    :goto_0
    return-object v1

    .line 87
    :cond_3
    const/4 v3, 0x0

    iput v3, v1, Landroid/widget/Filter$FilterResults;->count:I

    .line 88
    const/4 v3, 0x0

    iput-object v3, v1, Landroid/widget/Filter$FilterResults;->values:Ljava/lang/Object;

    goto :goto_0
.end method


text:
'use strict';

const irc = require('irc');
const allClients = [];

function maidIrc(io, env) {
	function createClient(socket, info, clientId) {
		// Create the IRC client instance
		console.log('Creating new IRC client instance');
		let _debug = false;

		if (env === 'development') {
			_debug = true;
		}

		const client = new irc.Client(info.server, info.nick, {
			userName: info.nick,
			realName: info.realName,
			password: info.nicknamePassword,
			port: info.port,
			localAddress: null,
			debug: _debug,
			showErrors: true,
			autoRejoin: true,
			autoConnect: false,
			channels: [info.channel],
			retryCount: null,
			retryDelay: 2000,
			secure: false,
			selfSigned: false,
			certExpired: false,
			floodProtection: true,
			floodProtectionDelay: 1000,
			sasl: false,
			stripColors: true,
			messageSplit: 512,
			encoding: false,
			webirc: {
				pass: '',
				ip: '',
				user: '',
			},
		});

		if (env === 'development') {
			client.on('registered', function registered() {
				console.log('001 message recieved');
			});
		}

		client.on('abort', function abort() {
			socket.emit('error', {
				type: 'connection',
			});
		});

		client.on('raw', function raw(message) {
			if (env === 'development') {
				console.log(message);
			}

			socket.emit('raw', [clientId, message]);
		});

		client.on('error', function error(message) {
			console.log(`Node-IRC Error: ${JSON.stringify(message)}`);
		});

		return client;
	}

	io.sockets.on('connection', function connection(socket) {
		console.log(`Client connected from: ${socket.handshake.address}`);

		const thisClient = {};
		let i;

		socket.on('connectToNetwork', function connectToNetwork(data) {
			if (typeof data === undefined) {
				socket.disconnect('unauthorized');
			} else {
				const connectionId = data[1];

				thisClient[connectionId] = createClient(socket, data[0], connectionId);
				const clientInstance = thisClient[connectionId];

				// Connect it now!
				clientInstance.connect();

				if (!clientInstance.conn._connecting || clientInstance.conn._hadError) {
					// It didn't connect?
				}

				socket.on('disconnect', function disconnect(reason) {
					console.log(`Client disconnected: ${reason}`);
					clientInstance.disconnect('Connection closed');

					delete thisClient[connectionId];
				});

				socket.on('send-raw', function sendraw(message) {
					clientInstance.send.apply(null, message);
				});

				i = allClients.push(socket);
			}
		});

		socket.on('disconnectFromNetwork', function disconnect(id) {
			// Needs error checking
			thisClient[id].disconnect();
			delete thisClient[id];
		});

		// Find the correct event for a socket disconnection
		socket.on('liveDisconnect', function liveDisconnect() {
			Object.keys(thisClient, function thisClientKey(key) {
				thisClient[key].disconnect();
			});
			allClients.splice(i, 1);
		});
	});
}

module.exports = maidIrc;


text: Repositorio prueba


text:
package unix

import (
	"syscall"
	"unsafe"
)

func setTimespec(sec, nsec int64) Timespec {
	return Timespec{Sec: sec, Nsec: nsec}
}

func setTimeval(sec, usec int64) Timeval {
	return Timeval{Sec: sec, Usec: usec}
}

func SetKevent(k *Kevent_t, fd, mode, flags int) {
	k.Ident = uint64(fd)
	k.Filter = int16(mode)
	k.Flags = uint16(flags)
}

func (iov *Iovec) SetLen(length int) {
	iov.Len = uint64(length)
}

func (msghdr *Msghdr) SetControllen(length int) {
	msghdr.Controllen = uint32(length)
}

func (cmsg *Cmsghdr) SetLen(length int) {
	cmsg.Len = uint32(length)
}

func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
	var writtenOut uint64 = 0
	_, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0, 0)

	written = int(writtenOut)

	if e1 != 0 {
		err = e1
	}
	return
}

func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)


text:
import argparse
import os
import json
import csv
import glob
import requests
from jdss import SummaryReport
import base64

def job(args):
    report = SummaryReport()
    section = report.add_section()
    tabs = section.add_tabs()
    for i in range(0, len(args.tab)):
        tab_contents = args.tab[i]
        name = 'tab{}'.format(i + 1) if len(args.names) <= i else args.names[i]
        tab = tabs.add_tab(name)
        for files in [glob.glob(f) for f in tab_contents]:
            for file in files:
                file_name = os.path.splitext(os.path.split(file)[-1])[0]
                file_ext = os.path.splitext(os.path.split(file)[-1])[1].lower()
                if file_ext == '.json':
                    with open(file, 'r') as json_file:
                        contents = json.loads(json_file.read())
                    table = tab.add_table()
                    header = table.add_row()
                    header.add_cell('Key')
                    header.add_cell('Value')
                    for key in sorted(contents.keys()):
                        row = table.add_row()
                        row.add_cell(key)
                        row.add_cell(contents[key])
                elif file_ext in ['.png', '.jpeg', '.jpg']:
                    with open(file, 'rb') as image:
                        image_data = base64.b64encode(image.read()).decode('utf-8').replace('\n', '')
                    tab.add_field(
                        file_name,
                        '<![CDATA[<img src="data:image/{};base64,{}"/>]]>'.format(file_ext[1:], image_data)
                    )
                elif file_ext == '.csv':
                    with open(file, 'r') as csvfile:
                        reader = csv.reader(csvfile)
                        table = tab.add_table()
                        for row in reader:
                            r = table.add_row()
                            for element in row:
                                r.add_cell(element)
    report.write(args.file, args.output)

def jobs(args):
    url = '{}lastBuild/buildNumber'.format(args.url)
    response = (
        requests.get(url)
        if args.user is None or args.password is None else
        requests.get(url, auth=(args.user, args.password))
    )
    if response.status_code != 200:
        raise Exception('Not ok response received for latest build number. Check the url and credentials')
    last_build_number = int(response.content.decode())

    builds = []
    build_number = last_build_number
    artifact_keys = set()
    while build_number > 0 and len(builds) <= args.history:
        try:
            artifact_values = {}
            url = '{}/{}/api/json'.format(args.url, build_number)
            summary_response = (
                requests.get(url)
                if args.user is None or args.password is None else
                requests.get(url, auth=(args.user, args.password))
            )

            if summary_response.status_code != 200:
                print('WARN: Summary was not available for build number {}'.format(build_number))
                continue
            try:
                summary = json.loads(summary_response.content.decode())
            except:
                print('WARN: Summary was not valid JSON for build number {}'.format(build_number))
                continue

            if summary['result'].upper() != 'SUCCESS':
                print('INFO: Skipping build {}, because it did not succeed'.format(build_number))
                continue

            if len(summary['actions']) > 0:
                action_index = 0
                action_found = False
                for action in summary['actions']:
                    if 'parameters' in action['_class'].lower():
                        action_found = True
                        break
                    action_index += 1
                if action_found and 'parameters' in summary['actions'][action_index]:
                    for parameter in args.parameters:
                        if parameter in [p['name'] for p in summary['actions'][action_index]['parameters']]:
                            artifact_keys.add(parameter)
                            artifact_values[parameter] = [p['value'] for p in summary['actions'][action_index]['parameters'] if p['name'] == parameter][0]

            for artifact in args.artifact:
                url = '{}/{}/artifact/{}'.format(args.url, build_number, artifact)
                artifact_response = (
                    requests.get(url)
                    if args.user is None or args.password is None else
                    requests.get(url, auth=(args.user, args.password))
                )

                if artifact_response.status_code != 200:
                    print('WARN: Artifact was not available for build number {}'.format(build_number))
                    continue

                try:
                    artifact_content = json.loads(artifact_response.content.decode())
                except:
                    print('WARN: Artifact was not valid JSON for build number {}'.format(build_number))
                    continue

                for key in artifact_content.keys():
                    if len(args.artifact) == 1:
                        artifact_values[key] = artifact_content[key]
                    else:
                        artifact_values['{}/{}'.format(os.path.splitext(artifact)[0], key)] = artifact_content[key]

            for key in artifact_values.keys():
                artifact_keys.add(key)

            builds.append({'build_number': build_number, 'artifact': artifact_values, 'description': summary['description']})

        finally:
            build_number -= 1

    report = SummaryReport()
    section = report.add_section()
    accordion = section.add_accordion(args.name)
    table = accordion.add_table()

    header = table.add_row()
    header.add_cell('build')
    sorted_keys = sorted(artifact_keys)
    for key in sorted_keys:
        header.add_cell(key)
    header.add_cell('description')

    for build in builds:
        row = table.add_row()
        row.add_cell(build['build_number'], '{}/{}'.format(args.url, build['build_number']))
        for key in sorted_keys:
            if key not in build['artifact']:
                row.add_cell('-')
            else:
                row.add_cell(build['artifact'][key])
        row.add_cell(build['description'])

    report.write(args.file, args.output)

def main():
    parser = argparse.ArgumentParser()
    sub_parsers = parser.add_subparsers()

    jobs_parser = sub_parsers.add_parser('jobs')
    jobs_parser.add_argument('--url', required=True, help='The url of the build job in Jenkins to summarise')
    jobs_parser.add_argument(
        '--artifact',
        nargs='*',
        required=True,
        help='The name, or names, of the artifact that will be used to populate the metadata about head job. This should be a JSON '
             'file containing a list of key value pairs. e.g. `--artifact metrics.json`, `--artifacts metrics-1.json metrics-2.json`'
    )
    jobs_parser.add_argument('--history', type=int, default=50, help='The number of historic builds to summarise')
    jobs_parser.add_argument('--name', default='History', help='The name to put on the accordion header')
    jobs_parser.add_argument('--file', default='summary.xml', help='The name of the output file')
    jobs_parser.add_argument('--parameters', default=[], nargs='*', help='If provided, this is the list of build parameter names that should be included from the build results')
    jobs_parser.add_argument('--user', default=None, help='The username to use when communicating with Jenkins, if basic authentication is enabled')
    jobs_parser.add_argument('--password', default=None,help='The password to use when communicating with Jenkins, if basic authentication is enabled')
    jobs_parser.add_argument('--output', required=True, help='The output directory into which the summary report XML file should be written')
    jobs_parser.set_defaults(func=jobs)

    job_parser = sub_parsers.add_parser('job')
    job_parser.add_argument(
        '--tab',
        action='append',
        default=[],
        nargs='*',
        help='This option can  be used multiple times to specify the content of an individual tab. Multiple values can '
             'be provided, each being a file path that is read. If the file contains XML or JSON, the values are parsed '
             'into a field per property. The assumption here is that the file will contain key value pairs - if the '
             'structure is more complicated, nested objects will be ignored. If the file paths provided are PNG or JPEG '
             'files then these will be included in the tab as images.'
    )
    job_parser.add_argument(
        '--names',
        default=[],
        nargs='*',
        help='A list of names to be used when labelling the tabs whose content is provided in `--tabs`. If no names are '
             'provided then the tabs will be labelled tab1, tab2, etc. If more names are provided than tabs then the '
             'extras will be ignored.'
    )
    job_parser.add_argument('--file', default='summary.xml', help='The name of the output file')
    job_parser.add_argument('--output', required=True, help='The output directory into which the summary report XML file should be written')
    job_parser.set_defaults(func=job)

    args = parser.parse_args()
    args.func(args)

if __name__ == '__main__':
    main()


text:
/*
* PROJECT:          Aura Operating System Development
* CONTENT:          Command Interpreter - Mkdir
* PROGRAMMER(S):    John Welsh <djlw78@gmail.com>
*/

using System;
using System.Collections.Generic;
using System.IO;

namespace Aura_OS.Interpreter.Commands.Filesystem
{
    class CommandMkdir : ICommand
    {
        /// <summary>
        /// Empty constructor.
        /// </summary>
        public CommandMkdir(string[] commandvalues) : base(commandvalues, CommandType.Filesystem)
        {
            Description = "to create a directory";
        }

        /// <summary>
        /// CommandMkdir
        /// </summary>
        public override ReturnInfo Execute()
        {
            PrintHelp();

            return new ReturnInfo(this, ReturnCode.OK);
        }

        /// <summary>
        /// CommandMkdir
        /// </summary>
        public override ReturnInfo Execute(List<string> arguments)
        {
            string dir = arguments[0];

            if (dir.Contains("."))
            {
                Kernel.console.WriteLine("You can't have a dot in your directory name.");
            }

            else
            {
                if (!Directory.Exists(Kernel.CurrentDirectory + dir))
                {
                    Directory.CreateDirectory(Kernel.CurrentDirectory + dir);
                }
                else if (Directory.Exists(Kernel.CurrentDirectory + dir))
                {
                    Char[] separators = new char[] { '(', ')' };
                    Char[] directories = new char[] { '/', '\\' };

                    //getting last directory.
                    string x1 = Kernel.CurrentDirectory + dir;
                    string[] x2 = x1.Split(directories);
                    string x3 = x2[x2.Length - 1];
                    int x4 = 0;

                //boucle
                boucle:
                    x4 = x4 + 1;
                    string DirectoryAlreadyExist = x3 + "(" + x4 + ")";

                    //if directory has already been recreated once or more
                    if ((DirectoryAlreadyExist.Contains("(")) && (DirectoryAlreadyExist.Contains(")")))
                    {
                        //get number
                        string[] endName = DirectoryAlreadyExist.Split(separators);
                        int num = int.Parse(endName[1]);

                        //add one to num
                        num = num + 1;

                        //set new directory name with the new number.
                        string newName = dir + "(" + num + ")";

                        if (Directory.Exists(Kernel.CurrentDirectory + newName))
                        {
                            goto boucle;
                        }

                        //create directory
                        Directory.CreateDirectory(Kernel.CurrentDirectory + newName);

                        //display text to inform the user that the directory has been created with an another name
                        Kernel.console.Foreground = ConsoleColor.Yellow;

                        Kernel.console.WriteLine("That folder existed already, directory \"" + newName + "\" has been created.");
                    }
                    else
                    {
                        //if not, we create directory with (1)
                        Directory.CreateDirectory(Kernel.CurrentDirectory + dir + "(1)");

                        //display text to inform the user that the directory has been created with an another name
                        Kernel.console.Foreground = ConsoleColor.Yellow;

                        Kernel.console.WriteLine("That folder existed already, directory \"" + dir + "(1)" + "\" has been created.");
                    }
                }
            }
            return new ReturnInfo(this, ReturnCode.OK);
        }

        /// <summary>
        /// Print /help information
        /// </summary>
        public override void PrintHelp()
        {
            Kernel.console.WriteLine("Usage:");
            Kernel.console.WriteLine(" - mkdir {directory}");
        }
    }
}


text:
package org.apache.nutch.crawl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeSet;
import java.util.logging.Logger;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.MapFile;
import org.apache.hadoop.io.Text;
import org.apache.nutch.util.NutchConfiguration;

import junit.framework.TestCase;

public class TestCrawlDbMerger extends TestCase {
  private static final Logger LOG = Logger.getLogger(CrawlDbMerger.class.getName());

  String url10 = "http://example.com/";
  String url11 = "http://example.com/foo";
  String url20 = "http://example.com/";
  String url21 = "http://example.com/bar";
  String[] urls_expected = new String[] {
          url10,
          url11,
          url21
  };

  TreeSet init1 = new TreeSet();
  TreeSet init2 = new TreeSet();
  HashMap expected = new HashMap();
  CrawlDatum cd1, cd2, cd3;
  Configuration conf;
  FileSystem fs;
  Path testDir;
  CrawlDbReader reader;

  public void setUp() throws Exception {
    init1.add(url10);
    init1.add(url11);
    init2.add(url20);
    init2.add(url21);
    long time = System.currentTimeMillis();
    cd1 = new CrawlDatum();
    cd1.setFetchInterval(1.0f);
    cd1.setFetchTime(time);
    cd1.getMetaData().put(new Text("name"), new Text("cd1"));
    cd1.getMetaData().put(new Text("cd1"), new Text("cd1"));
    cd2 = new CrawlDatum();
    cd2.setFetchInterval(1.0f);
    cd2.setFetchTime(time + 10000);
    cd2.getMetaData().put(new Text("name"), new Text("cd2"));
    cd3 = new CrawlDatum();
    cd3.setFetchInterval(1.0f);
    cd3.setFetchTime(time + 10000);
    cd3.getMetaData().putAll(cd1.getMetaData());
    cd3.getMetaData().putAll(cd2.getMetaData());
    expected.put(url10, cd3);
    expected.put(url11, cd1);
    expected.put(url21, cd2);
    conf = NutchConfiguration.create();
    fs = FileSystem.get(conf);
    testDir = new Path("test-crawldb-" +
            new java.util.Random().nextInt());
    fs.mkdirs(testDir);
  }

  public void tearDown() {
    try {
      if (fs.exists(testDir))
        fs.delete(testDir);
    } catch (Exception e) { }
    try {
      reader.close();
    } catch (Exception e) { }
  }

  public void testMerge() throws Exception {
    Path crawldb1 = new Path(testDir, "crawldb1");
    Path crawldb2 = new Path(testDir, "crawldb2");
    Path output = new Path(testDir, "output");
    createCrawlDb(conf, fs, crawldb1, init1, cd1);
    createCrawlDb(conf, fs, crawldb2, init2, cd2);
    CrawlDbMerger merger = new CrawlDbMerger(conf);
    LOG.fine("* merging crawldbs to " + output);
    merger.merge(output, new Path[]{crawldb1, crawldb2}, false, false);
    LOG.fine("* reading crawldb: " + output);
    reader = new CrawlDbReader();
    String crawlDb = output.toString();
    Iterator it = expected.keySet().iterator();
    while (it.hasNext()) {
      String url = (String)it.next();
      LOG.fine("url=" + url);
      CrawlDatum cd = (CrawlDatum)expected.get(url);
      CrawlDatum res = reader.get(crawlDb, url, conf);
      LOG.fine(" -> " + res);
      System.out.println("url=" + url);
      System.out.println(" cd " + cd);
      System.out.println(" res " + res);
      // may not be null
      assertNotNull(res);
      assertTrue(cd.equals(res));
    }
    reader.close();
    fs.delete(testDir);
  }

  private void createCrawlDb(Configuration config, FileSystem fs, Path crawldb, TreeSet init, CrawlDatum cd) throws Exception {
    LOG.fine("* creating crawldb: " + crawldb);
    Path dir = new Path(crawldb, CrawlDb.CURRENT_NAME);
    MapFile.Writer writer = new MapFile.Writer(config, fs, new Path(dir, "part-00000").toString(), Text.class, CrawlDatum.class);
    Iterator it = init.iterator();
    while (it.hasNext()) {
      String key = (String)it.next();
      writer.append(new Text(key), cd);
    }
    writer.close();
  }
}


text:
package it.unibz.krdb.obda.owlrefplatform.core.dagjgrapht;

import it.unibz.krdb.obda.ontology.BasicClassDescription;
import it.unibz.krdb.obda.ontology.Description;
import it.unibz.krdb.obda.ontology.PropertyExpression;

import java.util.List;

import org.jgrapht.DirectedGraph;
import org.jgrapht.Graphs;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.EdgeReversedGraph;
import org.jgrapht.graph.SimpleDirectedGraph;

/**
 * Used to represent a DAG and a named DAG.
 * Extend SimpleDirectedGraph from the JGrapht library
 * It can be constructed using the class DAGBuilder.
 *
 *
 */

public class NamedDAG  {

	private final SimpleDirectedGraph <PropertyExpression,DefaultEdge> propertyDAG;
	private final SimpleDirectedGraph <BasicClassDescription,DefaultEdge> classDAG;

	public NamedDAG(TBoxReasoner reasoner) {
		propertyDAG = getNamedDAG(reasoner.getProperties());
		classDAG = getNamedDAG(reasoner.getClasses());
	}

	@Override
	public String toString() {
		return propertyDAG.toString() + classDAG.toString();
	}

	@Deprecated // USED ONLY IN TESTS (3 calls)
	public SimpleDirectedGraph <PropertyExpression,DefaultEdge> getPropertyDag() {
		return propertyDAG;
	}
	@Deprecated // USED ONLY IN TESTS (3 calls)
	public SimpleDirectedGraph <BasicClassDescription,DefaultEdge> getClassDag() {
		return classDAG;
	}

	public List<PropertyExpression> getSuccessors(PropertyExpression desc) {
		return Graphs.successorListOf(propertyDAG, desc);
	}
	public List<BasicClassDescription> getSuccessors(BasicClassDescription desc) {
		return Graphs.successorListOf(classDAG, desc);
	}

	public List<PropertyExpression> getPredecessors(PropertyExpression desc) {
		return Graphs.predecessorListOf(propertyDAG, desc);
	}
	public List<BasicClassDescription> getPredecessors(BasicClassDescription desc) {
		return Graphs.predecessorListOf(classDAG, desc);
	}

	/**
	 * Constructor for the NamedDAGBuilder
	 * @param dag the DAG from which we want to maintain only the named descriptions
	 */

	private static <T> SimpleDirectedGraph <T,DefaultEdge> getNamedDAG(EquivalencesDAG<T> dag) {

		SimpleDirectedGraph<T,DefaultEdge>  namedDAG = new SimpleDirectedGraph <T,DefaultEdge> (DefaultEdge.class);

		for (Equivalences<T> v : dag)
			namedDAG.addVertex(v.getRepresentative());

		for (Equivalences<T> s : dag)
			for (Equivalences<T> t : dag.getDirectSuper(s))
				namedDAG.addEdge(s.getRepresentative(), t.getRepresentative());

		for (Equivalences<T> v : dag)
			if (!v.isIndexed()) {
				// eliminate node
				for (DefaultEdge incEdge : namedDAG.incomingEdgesOf(v.getRepresentative())) {
					T source = namedDAG.getEdgeSource(incEdge);

					for (DefaultEdge outEdge : namedDAG.outgoingEdgesOf(v.getRepresentative())) {
						T target = namedDAG.getEdgeTarget(outEdge);

						namedDAG.addEdge(source, target);
					}
				}
				namedDAG.removeVertex(v.getRepresentative());		// removes all adjacent edges as well
			}
		return namedDAG;
	}

	public DirectedGraph<Description, DefaultEdge> getReversedDag() {
		SimpleDirectedGraph <Description,DefaultEdge>  dag
			= new SimpleDirectedGraph <Description,DefaultEdge> (DefaultEdge.class);
		Graphs.addGraph(dag, propertyDAG);
		Graphs.addGraph(dag, classDAG);
		DirectedGraph<Description, DefaultEdge> reversed =
				new EdgeReversedGraph<Description, DefaultEdge>(dag); // WOULD IT NOT BE BETTER TO CACHE?
		return reversed;
	}

}


text:
/**
 * @file
 * temporal field interlace filter, ported from MPlayer/libmpcodecs
 */

#include "libavutil/opt.h"
#include "libavutil/imgutils.h"
#include "libavutil/avassert.h"
#include "avfilter.h"
#include "internal.h"

enum TInterlaceMode {
    MODE_MERGE = 0,
    MODE_DROP_EVEN,
    MODE_DROP_ODD,
    MODE_PAD,
    MODE_INTERLEAVE_TOP,
    MODE_INTERLEAVE_BOTTOM,
    MODE_INTERLACEX2,
    MODE_NB,
};

typedef struct {
    const AVClass *class;
    enum TInterlaceMode mode;   ///< interlace mode selected
    int flags;                  ///< flags affecting interlacing algorithm
    int frame;                  ///< number of the output frame
    int vsub;                   ///< chroma vertical subsampling
    AVFrame *cur;
    AVFrame *next;
    uint8_t *black_data[4];     ///< buffer used to fill padded lines
    int black_linesize[4];
} TInterlaceContext;

#define OFFSET(x) offsetof(TInterlaceContext, x)
#define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
#define TINTERLACE_FLAG_VLPF 01

static const AVOption tinterlace_options[] = {
    {"mode",              "select interlace mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=MODE_MERGE}, 0, MODE_NB-1, FLAGS, "mode"},
    {"merge",             "merge fields",                                 0, AV_OPT_TYPE_CONST, {.i64=MODE_MERGE},             INT_MIN, INT_MAX, FLAGS, "mode"},
    {"drop_even",         "drop even fields",                             0, AV_OPT_TYPE_CONST, {.i64=MODE_DROP_EVEN},         INT_MIN, INT_MAX, FLAGS, "mode"},
    {"drop_odd",          "drop odd fields",                              0, AV_OPT_TYPE_CONST, {.i64=MODE_DROP_ODD},          INT_MIN, INT_MAX, FLAGS, "mode"},
    {"pad",               "pad alternate lines with black",               0, AV_OPT_TYPE_CONST, {.i64=MODE_PAD},               INT_MIN, INT_MAX, FLAGS, "mode"},
    {"interleave_top",    "interleave top and bottom fields",             0, AV_OPT_TYPE_CONST, {.i64=MODE_INTERLEAVE_TOP},    INT_MIN, INT_MAX, FLAGS, "mode"},
    {"interleave_bottom", "interleave bottom and top fields",             0, AV_OPT_TYPE_CONST, {.i64=MODE_INTERLEAVE_BOTTOM}, INT_MIN, INT_MAX, FLAGS, "mode"},
    {"interlacex2",       "interlace fields from two consecutive frames", 0, AV_OPT_TYPE_CONST, {.i64=MODE_INTERLACEX2},       INT_MIN, INT_MAX, FLAGS, "mode"},

    {"flags",             "set flags", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, 0, INT_MAX, 0, "flags" },
    {"low_pass_filter",   "enable vertical low-pass filter",              0, AV_OPT_TYPE_CONST, {.i64 = TINTERLACE_FLAG_VLPF}, INT_MIN, INT_MAX, FLAGS, "flags" },
    {"vlpf",              "enable vertical low-pass filter",              0, AV_OPT_TYPE_CONST, {.i64 = TINTERLACE_FLAG_VLPF}, INT_MIN, INT_MAX, FLAGS, "flags" },

    {NULL}
};

AVFILTER_DEFINE_CLASS(tinterlace);

#define FULL_SCALE_YUVJ_FORMATS \
    AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ440P

static enum AVPixelFormat full_scale_yuvj_pix_fmts[] = {
    FULL_SCALE_YUVJ_FORMATS, AV_PIX_FMT_NONE
};

static int query_formats(AVFilterContext *ctx)
{
    static const enum AVPixelFormat pix_fmts[] = {
        AV_PIX_FMT_YUV420P,  AV_PIX_FMT_YUV422P,  AV_PIX_FMT_YUV444P,
        AV_PIX_FMT_YUV444P,  AV_PIX_FMT_YUV410P,  AV_PIX_FMT_YUVA420P,
        AV_PIX_FMT_GRAY8, FULL_SCALE_YUVJ_FORMATS,
        AV_PIX_FMT_NONE
    };

    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
    return 0;
}

static av_cold void uninit(AVFilterContext *ctx)
{
    TInterlaceContext *tinterlace = ctx->priv;

    av_frame_free(&tinterlace->cur );
    av_frame_free(&tinterlace->next);
    av_freep(&tinterlace->black_data[0]);
}

static int config_out_props(AVFilterLink *outlink)
{
    AVFilterContext *ctx = outlink->src;
    AVFilterLink *inlink = outlink->src->inputs[0];
    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(outlink->format);
    TInterlaceContext *tinterlace = ctx->priv;

    tinterlace->vsub = desc->log2_chroma_h;
    outlink->flags |= FF_LINK_FLAG_REQUEST_LOOP;
    outlink->w = inlink->w;
    outlink->h = tinterlace->mode == MODE_MERGE || tinterlace->mode == MODE_PAD ?
        inlink->h*2 : inlink->h;

    if (tinterlace->mode == MODE_PAD) {
        uint8_t black[4] = { 16, 128, 128, 16 };
        int i, ret;
        if (ff_fmt_is_in(outlink->format, full_scale_yuvj_pix_fmts))
            black[0] = black[3] = 0;
        ret = av_image_alloc(tinterlace->black_data, tinterlace->black_linesize,
                             outlink->w, outlink->h, outlink->format, 1);
        if (ret < 0)
            return ret;

        /* fill black picture with black */
        for (i = 0; i < 4 && tinterlace->black_data[i]; i++) {
            int h = i == 1 || i == 2 ? FF_CEIL_RSHIFT(outlink->h, desc->log2_chroma_h) : outlink->h;
            memset(tinterlace->black_data[i], black[i],
                   tinterlace->black_linesize[i] * h);
        }
    }
    if ((tinterlace->flags & TINTERLACE_FLAG_VLPF)
            && !(tinterlace->mode == MODE_INTERLEAVE_TOP
              || tinterlace->mode == MODE_INTERLEAVE_BOTTOM)) {
        av_log(ctx, AV_LOG_WARNING, "low_pass_filter flag ignored with mode %d\n",
                tinterlace->mode);
        tinterlace->flags &= ~TINTERLACE_FLAG_VLPF;
    }
    av_log(ctx, AV_LOG_VERBOSE, "mode:%d filter:%s h:%d -> h:%d\n",
           tinterlace->mode, (tinterlace->flags & TINTERLACE_FLAG_VLPF) ? "on" : "off",
           inlink->h, outlink->h);

    return 0;
}

#define FIELD_UPPER           0
#define FIELD_LOWER           1
#define FIELD_UPPER_AND_LOWER 2

/**
 * Copy picture field from src to dst.
 *
 * @param src_field copy from upper, lower field or both
 * @param interleave leave a padding line between each copied line
 * @param dst_field copy to upper or lower field,
 *        only meaningful when interleave is selected
 * @param flags context flags
 */
static inline
void copy_picture_field(uint8_t *dst[4], int dst_linesize[4],
                        const uint8_t *src[4], int src_linesize[4],
                        enum AVPixelFormat format, int w, int src_h,
                        int src_field, int interleave, int dst_field,
                        int flags)
{
    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);
    int plane, vsub = desc->log2_chroma_h;
    int k = src_field == FIELD_UPPER_AND_LOWER ? 1 : 2;
    int h, i;

    for (plane = 0; plane < desc->nb_components; plane++) {
        int lines = plane == 1 || plane == 2 ? FF_CEIL_RSHIFT(src_h, vsub) : src_h;
        int linesize = av_image_get_linesize(format, w, plane);
        uint8_t *dstp = dst[plane];
        const uint8_t *srcp = src[plane];

        if (linesize < 0)
            return;

        lines = (lines + (src_field == FIELD_UPPER)) / k;
        if (src_field == FIELD_LOWER)
            srcp += src_linesize[plane];
        if (interleave && dst_field == FIELD_LOWER)
            dstp += dst_linesize[plane];
        if (flags & TINTERLACE_FLAG_VLPF) {
            // Low-pass filtering is required when creating an interlaced destination from
            // a progressive source which contains high-frequency vertical detail.
            // Filtering will reduce interlace 'twitter' and Moire patterning.
            int srcp_linesize = src_linesize[plane] * k;
            int dstp_linesize = dst_linesize[plane] * (interleave ? 2 : 1);
            for (h = lines; h > 0; h--) {
                const uint8_t *srcp_above = srcp - src_linesize[plane];
                const uint8_t *srcp_below = srcp + src_linesize[plane];
                if (h == lines) srcp_above = srcp; // there is no line above
                if (h == 1) srcp_below = srcp;     // there is no line below
                for (i = 0; i < linesize; i++) {
                    // this calculation is an integer representation of
                    // '0.5 * current + 0.25 * above + 0.25 * below'
                    // '1 +' is for rounding. */
                    dstp[i] = (1 + srcp[i] + srcp[i] + srcp_above[i] + srcp_below[i]) >> 2;
                }
                dstp += dstp_linesize;
                srcp += srcp_linesize;
            }
        } else {
            av_image_copy_plane(dstp, dst_linesize[plane] * (interleave ? 2 : 1),
                            srcp, src_linesize[plane]*k, linesize, lines);
        }
    }
}

static int filter_frame(AVFilterLink *inlink, AVFrame *picref)
{
    AVFilterContext *ctx = inlink->dst;
    AVFilterLink *outlink = ctx->outputs[0];
    TInterlaceContext *tinterlace = ctx->priv;
    AVFrame *cur, *next, *out;
    int field, tff, ret;

    av_frame_free(&tinterlace->cur);
    tinterlace->cur  = tinterlace->next;
    tinterlace->next = picref;

    cur = tinterlace->cur;
    next = tinterlace->next;
    /* we need at least two frames */
    if (!tinterlace->cur)
        return 0;

    switch (tinterlace->mode) {
    case MODE_MERGE: /* move the odd frame into the upper field of the new image, even into
             * the lower field, generating a double-height video at half framerate */
        out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
        if (!out)
            return AVERROR(ENOMEM);
        av_frame_copy_props(out, cur);
        out->height = outlink->h;
        out->interlaced_frame = 1;
        out->top_field_first = 1;

        /* write odd frame lines into the upper field of the new frame */
        copy_picture_field(out->data, out->linesize,
                           (const uint8_t **)cur->data, cur->linesize,
                           inlink->format, inlink->w, inlink->h,
                           FIELD_UPPER_AND_LOWER, 1, FIELD_UPPER, tinterlace->flags);
        /* write even frame lines into the lower field of the new frame */
        copy_picture_field(out->data, out->linesize,
                           (const uint8_t **)next->data, next->linesize,
                           inlink->format, inlink->w, inlink->h,
                           FIELD_UPPER_AND_LOWER, 1, FIELD_LOWER, tinterlace->flags);
        av_frame_free(&tinterlace->next);
        break;

    case MODE_DROP_ODD:  /* only output even frames, odd  frames are dropped; height unchanged, half framerate */
    case MODE_DROP_EVEN: /* only output odd  frames, even frames are dropped; height unchanged, half framerate */
        out = av_frame_clone(tinterlace->mode == MODE_DROP_EVEN ? cur : next);
        av_frame_free(&tinterlace->next);
        break;

    case MODE_PAD: /* expand each frame to double height, but pad alternate
                    * lines with black; framerate unchanged */
        out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
        if (!out)
            return AVERROR(ENOMEM);
        av_frame_copy_props(out, cur);
        out->height = outlink->h;

        field = (1 + tinterlace->frame) & 1 ? FIELD_UPPER : FIELD_LOWER;
        /* copy upper and lower fields */
        copy_picture_field(out->data, out->linesize,
                           (const uint8_t **)cur->data, cur->linesize,
                           inlink->format, inlink->w, inlink->h,
                           FIELD_UPPER_AND_LOWER, 1, field, tinterlace->flags);
        /* pad with black the other field */
        copy_picture_field(out->data, out->linesize,
                           (const uint8_t **)tinterlace->black_data, tinterlace->black_linesize,
                           inlink->format, inlink->w, inlink->h,
                           FIELD_UPPER_AND_LOWER, 1, !field, tinterlace->flags);
        break;

        /* interleave upper/lower lines from odd frames with lower/upper lines from even frames,
         * halving the frame rate and preserving image height */
    case MODE_INTERLEAVE_TOP:    /* top    field first */
    case MODE_INTERLEAVE_BOTTOM: /* bottom field first */
        tff = tinterlace->mode == MODE_INTERLEAVE_TOP;
        out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
        if (!out)
            return AVERROR(ENOMEM);
        av_frame_copy_props(out, cur);
        out->interlaced_frame = 1;
        out->top_field_first = tff;

        /* copy upper/lower field from cur */
        copy_picture_field(out->data, out->linesize,
                           (const uint8_t **)cur->data, cur->linesize,
                           inlink->format, inlink->w, inlink->h,
                           tff ? FIELD_UPPER : FIELD_LOWER, 1, tff ? FIELD_UPPER : FIELD_LOWER,
                           tinterlace->flags);
        /* copy lower/upper field from next */
        copy_picture_field(out->data, out->linesize,
                           (const uint8_t **)next->data, next->linesize,
                           inlink->format, inlink->w, inlink->h,
                           tff ? FIELD_LOWER : FIELD_UPPER, 1, tff ? FIELD_LOWER : FIELD_UPPER,
                           tinterlace->flags);
        av_frame_free(&tinterlace->next);
        break;
    case MODE_INTERLACEX2: /* re-interlace preserving image height, double frame rate */
        /* output current frame first */
        out = av_frame_clone(cur);
        if (!out)
            return AVERROR(ENOMEM);
        out->interlaced_frame = 1;

        if ((ret = ff_filter_frame(outlink, out)) < 0)
            return ret;

        /* output mix of current and next frame */
        tff = next->top_field_first;
        out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
        if (!out)
            return AVERROR(ENOMEM);
        av_frame_copy_props(out, next);
        out->interlaced_frame = 1;

        /* write current frame second field lines into the second field of the new frame */
        copy_picture_field(out->data, out->linesize,
                           (const uint8_t **)cur->data, cur->linesize,
                           inlink->format, inlink->w, inlink->h,
                           tff ? FIELD_LOWER : FIELD_UPPER, 1, tff ? FIELD_LOWER : FIELD_UPPER,
                           tinterlace->flags);
        /* write next frame first field lines into the first field of the new frame */
        copy_picture_field(out->data, out->linesize,
                           (const uint8_t **)next->data, next->linesize,
                           inlink->format, inlink->w, inlink->h,
                           tff ? FIELD_UPPER : FIELD_LOWER, 1, tff ? FIELD_UPPER : FIELD_LOWER,
                           tinterlace->flags);
        break;
    default:
        av_assert0(0);
    }

    ret = ff_filter_frame(outlink, out);
    tinterlace->frame++;

    return ret;
}

static const AVFilterPad tinterlace_inputs[] = {
    {
        .name         = "default",
        .type         = AVMEDIA_TYPE_VIDEO,
        .filter_frame = filter_frame,
    },
    { NULL }
};

static const AVFilterPad tinterlace_outputs[] = {
    {
        .name          = "default",
        .type          = AVMEDIA_TYPE_VIDEO,
        .config_props  = config_out_props,
    },
    { NULL }
};

AVFilter avfilter_vf_tinterlace = {
    .name          = "tinterlace",
    .description   = NULL_IF_CONFIG_SMALL("Perform temporal field interlacing."),
    .priv_size     = sizeof(TInterlaceContext),
    .uninit        = uninit,
    .query_formats = query_formats,
    .inputs        = tinterlace_inputs,
    .outputs       = tinterlace_outputs,
    .priv_class    = &tinterlace_class,
};


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

import com.facebook.presto.Session;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.planner.PlanNodeIdAllocator;
import com.facebook.presto.sql.planner.Symbol;
import com.facebook.presto.sql.planner.SymbolAllocator;
import com.facebook.presto.sql.planner.plan.ApplyNode;
import com.facebook.presto.sql.planner.plan.PlanNode;
import com.facebook.presto.sql.planner.plan.SemiJoinNode;
import com.facebook.presto.sql.planner.plan.SimplePlanRewriter;
import com.facebook.presto.sql.tree.Expression;
import com.facebook.presto.sql.tree.InPredicate;

import java.util.Map;
import java.util.Optional;

import static com.facebook.presto.sql.planner.plan.SimplePlanRewriter.rewriteWith;
import static com.google.common.collect.Iterables.getOnlyElement;
import static java.util.Objects.requireNonNull;

/**
 * This optimizers looks for InPredicate expressions in ApplyNodes and replaces the nodes with SemiJoin nodes.
 *

 * Plan before optimizer:
 *

 * Filter(a IN b):
 *   Apply
 *     - correlation: []  // empty
 *     - input: some plan A producing symbol a
 *     - subquery: some plan B producing symbol b
 *

 *

 * Plan after optimizer:
 *

 * Filter(semijoinresult):
 *   SemiJoin
 *     - source: plan A
 *     - filteringSource: symbol a
 *     - sourceJoinSymbol: plan B
 *     - filteringSourceJoinSymbol: symbol b
 *     - semiJoinOutput: semijoinresult
 *

 */
public class TransformUncorrelatedInPredicateSubqueryToSemiJoin
        implements PlanOptimizer
{
    @Override
    public PlanNode optimize(PlanNode plan, Session session, Map<Symbol, Type> types, SymbolAllocator symbolAllocator, PlanNodeIdAllocator idAllocator)
    {
        return rewriteWith(new InPredicateRewriter(idAllocator), plan, null);
    }

    /**
     * Each ApplyNode which contains InPredicate is replaced by semi join node.
     */
    private static class InPredicateRewriter
            extends SimplePlanRewriter<Void>
    {
        private final PlanNodeIdAllocator idAllocator;

        public InPredicateRewriter(PlanNodeIdAllocator idAllocator)
        {
            this.idAllocator = requireNonNull(idAllocator, "idAllocator is null");
        }

        @Override
        public PlanNode visitApply(ApplyNode node, RewriteContext<Void> context)
        {
            if (!node.getCorrelation().isEmpty()) {
                return context.defaultRewrite(node);
            }

            if (node.getSubqueryAssignments().size() != 1) {
                return context.defaultRewrite(node);
            }

            Expression expression = getOnlyElement(node.getSubqueryAssignments().getExpressions());
            if (!(expression instanceof InPredicate)) {
                return context.defaultRewrite(node);
            }

            PlanNode input = context.rewrite(node.getInput());
            PlanNode subquery = context.rewrite(node.getSubquery());

            InPredicate inPredicate = (InPredicate) expression;
            Symbol semiJoinSymbol = getOnlyElement(node.getSubqueryAssignments().getSymbols());
            return new SemiJoinNode(idAllocator.getNextId(),
                    input,
                    subquery,
                    Symbol.from(inPredicate.getValue()),
                    Symbol.from(inPredicate.getValueList()),
                    semiJoinSymbol,
                    Optional.empty(),
                    Optional.empty(),
                    Optional.empty()
            );
        }
    }
}