text:
package org.eclipse.collections.impl.jmh

import org.junit.Assert

import scala.collection.IterableView
import scala.collection.mutable.HashSet
import scala.collection.parallel.immutable.ParMap
import scala.collection.parallel.mutable.ParHashSet

object GroupBySetScalaTest
{
    private val SIZE = 1000000
    private val integers = new HashSet[Int]() ++ (0 to SIZE - 1)

    def groupBy_2_keys_serial_eager_scala(): Map[Boolean, HashSet[Int]] =
    {
        val multimap: Map[Boolean, HashSet[Int]] = this.integers.groupBy((each: Int) => each % 2 == 0)
        Assert.assertEquals(2, multimap.size)
        multimap
    }

    def test_groupBy_2_keys_serial_eager_scala(): Unit =
    {
        val multimap: Map[Boolean, HashSet[Int]] = groupBy_2_keys_serial_eager_scala()
        val odds: HashSet[Int] = multimap(false)
        val evens: HashSet[Int] = multimap(true)
        Assert.assertEquals(0.to(999999, 2).toSet, evens)
        Assert.assertEquals(1.to(999999, 2).toSet, odds)
    }

    def groupBy_100_keys_serial_eager_scala(): Map[Int, HashSet[Int]] =
    {
        val multimap: Map[Int, HashSet[Int]] = this.integers.groupBy((each: Int) => each % 100)
        Assert.assertEquals(100, multimap.size)
        multimap
    }

    def test_groupBy_100_keys_serial_eager_scala(): Unit =
    {
        val multimap: Map[Int, HashSet[Int]] = groupBy_100_keys_serial_eager_scala()
        for (i <- 0 to 99)
        {
            val integers: HashSet[Int] = multimap(i)
            Assert.assertEquals(i.to(999999, 100).toSet, integers)
        }
    }

    def groupBy_10000_keys_serial_eager_scala(): Map[Int, HashSet[Int]] =
    {
        val multimap: Map[Int, HashSet[Int]] = this.integers.groupBy((each: Int) => each % 10000)
        Assert.assertEquals(10000, multimap.size)
        multimap
    }

    def test_groupBy_10000_keys_serial_eager_scala(): Unit =
    {
        val multimap: Map[Int, HashSet[Int]] = groupBy_10000_keys_serial_eager_scala()
        for (i <- 0 to 9999)
        {
            val integers: HashSet[Int] = multimap(i)
            Assert.assertEquals(i.to(999999, 10000).toSet, integers)
        }
    }

    def groupBy_unordered_lists_2_keys_serial_lazy_scala(): Map[Boolean, IterableView[Int, HashSet[Int]]] =
    {
        val multimap: Map[Boolean, IterableView[Int, HashSet[Int]]] = this.integers.view.groupBy((each: Int) => each % 2 == 0)
        Assert.assertEquals(2, multimap.size)
        multimap
    }

    def test_groupBy_unordered_lists_2_keys_serial_lazy_scala(): Unit =
    {
        val multimap: Map[Boolean, IterableView[Int, HashSet[Int]]] = groupBy_unordered_lists_2_keys_serial_lazy_scala()
        val evens: IterableView[Int, HashSet[Int]] = multimap(true)
        val odds: IterableView[Int, HashSet[Int]] = multimap(false)
        Assert.assertEquals(0.to(999999, 2).toSet, evens.toSet)
        Assert.assertEquals(1.to(999999, 2).toSet, odds.toSet)
    }

    def groupBy_unordered_lists_100_keys_serial_lazy_scala(): Map[Int, IterableView[Int, HashSet[Int]]] =
    {
        val multimap: Map[Int, IterableView[Int, HashSet[Int]]] = this.integers.view.groupBy((each: Int) => each % 100)
        Assert.assertEquals(100, multimap.size)
        multimap
    }

    def test_groupBy_unordered_lists_100_keys_serial_lazy_scala(): Unit =
    {
        val multimap: Map[Int, IterableView[Int, HashSet[Int]]] = groupBy_unordered_lists_100_keys_serial_lazy_scala()
        for (i <- 0 to 99)
        {
            val integers: IterableView[Int, HashSet[Int]] = multimap(i)
            Assert.assertEquals(i.to(999999, 100).toSet, integers.toSet)
        }
    }

    def groupBy_unordered_lists_10000_keys_serial_lazy_scala(): Map[Int, IterableView[Int, HashSet[Int]]] =
    {
        val multimap: Map[Int, IterableView[Int, HashSet[Int]]] = this.integers.view.groupBy((each: Int) => each % 10000)
        Assert.assertEquals(10000, multimap.size)
        multimap
    }

    def test_groupBy_unordered_lists_10000_keys_serial_lazy_scala(): Unit =
    {
        val multimap: Map[Int, IterableView[Int, HashSet[Int]]] = groupBy_unordered_lists_10000_keys_serial_lazy_scala()
        for (i <- 0 to 9999)
        {
            val integers: IterableView[Int, HashSet[Int]] = multimap(i)
            Assert.assertEquals(i.to(999999, 10000).toSet, integers.toSet)
        }
    }

    def groupBy_2_keys_parallel_lazy_scala(): ParMap[Boolean, ParHashSet[Int]] =
    {
        val multimap: ParMap[Boolean, ParHashSet[Int]] = this.integers.par.groupBy((each: Int) => each % 2 == 0)
        Assert.assertEquals(2, multimap.size)
        multimap
    }

    def test_groupBy_2_keys_parallel_lazy_scala(): Unit =
    {
        val multimap: ParMap[Boolean, ParHashSet[Int]] = groupBy_2_keys_parallel_lazy_scala()
        val evens: ParHashSet[Int] = multimap(true)
        val odds: ParHashSet[Int] = multimap(false)
        Assert.assertEquals(0.to(999999, 2).toSet, evens)
        Assert.assertEquals(1.to(999999, 2).toSet, odds)
    }

    def groupBy_100_keys_parallel_lazy_scala(): ParMap[Int, ParHashSet[Int]] =
    {
        val multimap: ParMap[Int, ParHashSet[Int]] = this.integers.par.groupBy((each: Int) => each % 100)
        Assert.assertEquals(100, multimap.size)
        multimap
    }

    def test_groupBy_100_keys_parallel_lazy_scala(): Unit =
    {
        val multimap: ParMap[Int, ParHashSet[Int]] = groupBy_100_keys_parallel_lazy_scala()
        for (i <- 0 to 99)
        {
            val integers: ParHashSet[Int] = multimap(i)
            Assert.assertEquals(i.to(999999, 100).toSet, integers)
        }
    }

    def groupBy_10000_keys_parallel_lazy_scala(): ParMap[Int, ParHashSet[Int]] =
    {
        val multimap: ParMap[Int, ParHashSet[Int]] = this.integers.par.groupBy((each: Int) => each % 10000)
        Assert.assertEquals(10000, multimap.size)
        multimap
    }

    def test_groupBy_10000_keys_parallel_lazy_scala(): Unit =
    {
        val multimap: ParMap[Int, ParHashSet[Int]] = groupBy_10000_keys_parallel_lazy_scala()
        for (i <- 0 to 9999)
        {
            val integers: ParHashSet[Int] = multimap(i)
            Assert.assertEquals(i.to(999999, 10000).toSet, integers)
        }
    }
}


text:
require File.expand_path('../application', __FILE__)

# Initialize the rails application
Zenkai::Application.initialize!

redpajama_set_name: RedPajamaGithub


text:
package ru.kpfu.itis.group11501.shatin.politics_web_project.servlets;

import ru.kpfu.itis.group11501.shatin.politics_web_project.helpers.Helper;
import ru.kpfu.itis.group11501.shatin.politics_web_project.models.*;
import ru.kpfu.itis.group11501.shatin.politics_web_project.services.*;
import ru.kpfu.itis.group11501.shatin.politics_web_project.services.impls.ElectionServiceImpl;
import ru.kpfu.itis.group11501.shatin.politics_web_project.services.impls.NewsServiceImpl;
import ru.kpfu.itis.group11501.shatin.politics_web_project.services.impls.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.OffsetDateTime;
import java.util.HashMap;

/**
 * @author Oleg Shatin
 *         11-501
 */
@WebServlet(name = "NewsServlet")
public class NewsServlet extends HttpServlet {

    private NewsService newsService;
    private UserService userService;
    private ElectionService electionService;

    @Override
    public void init() throws ServletException {
        super.init();
        this.newsService = new NewsServiceImpl();
        this.userService = new UserServiceImpl();
        this.electionService = new ElectionServiceImpl();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = userService.authorize(request.getSession().getAttribute("user"));
        if (user != null && (user.getRole() == Role.ADMIN || user.getRole() == Role.USER)) {
            Long parentCommentId = null;
            if (request.getParameter("parent_comment_id") != null) {
                try {
                    parentCommentId = Long.parseLong(request.getParameter("parent_comment_id"));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    response.sendRedirect("/404");
                }
            }
            Comment newComment = new Comment(parentCommentId,
                    Long.parseLong(request.getParameter("a")), user.getId(),
                    request.getParameter("comment_text"),
                    OffsetDateTime.now(user.getTimezoneOffset()));
            newComment = newsService.addComment(newComment);
            if (newComment != null) {
                response.sendRedirect("/news" + "?a=" + request.getParameter("a"));
            } else {
                response.sendRedirect("/news" + "?a=" + request.getParameter("a") + "&error=smth_wrong");
            }
        } else {

            response.sendRedirect("/news" + "?a=" + request.getParameter("a") + "&error=access_denied");

        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //get user from session or create Guest user
        User user = userService.authorize(request.getSession().getAttribute("user"));
        HashMap<String, Object> root = new HashMap<>();
        root.put("user_role", user.getRole());
        root.put("error", request.getParameter("error"));
        root.put("alert", request.getParameter("alert"));
        //// TODO: 10.11.2016 add clocks info
        //if required all news send news list, if required article - send article
        if (request.getParameter("a") == null) {
            String search = request.getParameter("search");
            root.put("search", search);
            root.put("articles", newsService.getArticlesForUser(user, search, request.getParameter("headlines_only") != null));
            Election election = electionService.getCurrentElectionForUser(user);
            root.put("user_cannot_vote", (user.getRole() != Role.USER || election == null || electionService.userVotedOnElection(user, election)));
            Helper.render(request, response, "news.ftl", root);
        } else {
            long articleNum = 0;
            try {
                articleNum = Long.parseLong(request.getParameter("a"));
            } catch (NumberFormatException e) {
                response.sendRedirect("/404");
            }
            Article article = newsService.getArticle(articleNum, user);
            root.put("article", article);
            root.put("comments", newsService.getCommentsOfArticleForUser(article, user));
            Helper.render(request, response, "article.ftl", root);
        }
    }
}


text:
import { Component, OnInit, OnDestroy, ViewContainerRef } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { ChatService } from './chat.service';
import { ToastsManager } from 'ng2-toastr';

interface IMsg {
  name: string;
  logo: string;
  msg: string;
}

@Component({
  selector: 'chat',
  templateUrl: './chat.component.html',
  styleUrls: ['./chat.component.scss'],
  providers: [ChatService]
})

export class ChatComponent implements OnInit, OnDestroy {
  public messages: object[] = [];
  public message: string;
  private connection: any;

  constructor(
    private chatService: ChatService,
    public toastr: ToastsManager,
    public vRef: ViewContainerRef,
    private titleService: Title
    ) {
      this.titleService.setTitle('Chat - HoneyMorning');
    }

  public sendMessage() {
    // 如果未登录,不允许发送信息
    const cookie = document.cookie;
    if (!cookie || !/isLogin=true/.test(cookie)) {
      this.toastr.warning('Please login first.', 'Warning');
      return;
    }

    const user = JSON.parse(localStorage.getItem('user'));

    this.toastr.info('Sending message...', 'Progress');
    this.chatService.sendMessage({
      name: user.name,
      logo: user.logo,
      msg: this.message
    });
    this.message = '';
  }

  public onEnter(value: string) {
    this.message = value;
    this.sendMessage();
  }

  public ngOnInit() {
    this.connection = this.chatService.getMessage().subscribe((msg: IMsg) => {
      this.toastr.warning('New Message', 'TIP');
      msg.logo = msg.logo || 'src/assets/images/icon.png';
      this.messages.push(msg);
    });
  }

  public ngOnDestroy() {
    this.connection.unsubscribe();
  }
}


text:
"""check method hidding ancestor attribute
"""
from __future__ import print_function

class Abcd(object):
    """dummy"""
    def __init__(self):
        self.abcd = 1

class Cdef(Abcd):
    """dummy"""
    def abcd(self): # [method-hidden]
        """test
        """
        print(self)

class CustomProperty:
    """dummy"""
    def __init__(self, _):
        pass

    def __get__(self, obj, __):
        if not obj:
            return self
        return 5

    def __set__(self, _, __):
        pass

class Ddef:
    """dummy"""
    def __init__(self):
        self.five = "five"

    @CustomProperty
    def five(self):
        """Always 5."""
        return self

def my_decorator(*args, **kwargs):
    return CustomProperty(*args, **kwargs)

class Foo:
    def __init__(self):
        self._bar = 42
        self._baz = 84

    @my_decorator
    def method(self):  # E0202
        return self._baz

    @method.setter
    def method(self, value):
        self._baz = value

    def do_something_with_baz(self, value):
        self.method = value


text:
package metadslx.compiler;

public class SymbolTypeAnnotation {
	private String name;
	private boolean hasName;
	private Class<?> symbolType;

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
		this.hasName = true;
	}

	public boolean hasName() {
		return hasName;
	}

	public void setHasName(boolean hasName) {
		this.hasName = hasName;
	}

	public Class<?> getSymbolType() {
		return symbolType;
	}

	public void setSymbolType(Class<?> symbolType) {
		this.symbolType = symbolType;
	}
}


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>6 | Gregor von Laszewski</title>
    <link>/publication-type/6/</link>
      <atom:link href="/publication-type/6/index.xml" rel="self" type="application/rss+xml" />
    <description>6</description>
    <generator>Source Themes Academic (https://sourcethemes.com/academic/)</generator><language>en-us</language><lastBuildDate>Wed, 01 Jan 2014 00:00:00 +0000</lastBuildDate>
    <image>
      <url>/images/icon_hufdd866d90d76849587aac6fbf27da1ac_464_512x512_fill_lanczos_center_3.png</url>
      <title>6</title>
      <link>/publication-type/6/</link>
    </image>

    <item>
      <title>The FutureGrid Testbed for Big Data</title>
      <link>/publication/las-2014-bigdata/</link>
      <pubDate>Wed, 01 Jan 2014 00:00:00 +0000</pubDate>
      <guid>/publication/las-2014-bigdata/</guid>
      <description></description>
    </item>

    <item>
      <title>Contemporary High Performance Computing</title>
      <link>/publication/las-2013-fg-bookchapter/</link>
      <pubDate>Tue, 01 Jan 2013 00:00:00 +0000</pubDate>
      <guid>/publication/las-2013-fg-bookchapter/</guid>
      <description></description>
    </item>

    <item>
      <title>Providing a Green Framework for Cloud Based Data Centers</title>
      <link>/publication/las-2011-greenchapter/</link>
      <pubDate>Sat, 01 Jan 2011 00:00:00 +0000</pubDate>
      <guid>/publication/las-2011-greenchapter/</guid>
      <description></description>
    </item>

    <item>
      <title>Towards on Demand IT Service Deployment</title>
      <link>/publication/las-2011-ondemand/</link>
      <pubDate>Sat, 01 Jan 2011 00:00:00 +0000</pubDate>
      <guid>/publication/las-2011-ondemand/</guid>
      <description></description>
    </item>

    <item>
      <title>Cyberaide Virtual Applicance: On-Demand Deploying Middleware for Cyberinfrastructure</title>
      <link>/publication/las-2009-cloudcomp/</link>
      <pubDate>Fri, 01 Oct 2010 00:00:00 +0000</pubDate>
      <guid>/publication/las-2009-cloudcomp/</guid>
      <description></description>
    </item>

    <item>
      <title>Grid Workflow with the Java CoG Kit</title>
      <link>/publication/las-2006-workflow-book/</link>
      <pubDate>Mon, 01 Jan 2007 00:00:00 +0000</pubDate>
      <guid>/publication/las-2006-workflow-book/</guid>
      <description></description>
    </item>

    <item>
      <title>Java CoG Kit Workflow</title>
      <link>/publication/las-2007-workflow/</link>
      <pubDate>Mon, 01 Jan 2007 00:00:00 +0000</pubDate>
      <guid>/publication/las-2007-workflow/</guid>
      <description></description>
    </item>

    <item>
      <title>Work coordination for Grid computing</title>
      <link>/publication/las-2006-workcoordination/</link>
      <pubDate>Sun, 01 Jan 2006 00:00:00 +0000</pubDate>
      <guid>/publication/las-2006-workcoordination/</guid>
      <description></description>
    </item>

    <item>
      <title>Quality-of-Service Based Grid Communities</title>
      <link>/publication/las-2005-qos-book/</link>
      <pubDate>Sat, 01 Jan 2005 00:00:00 +0000</pubDate>
      <guid>/publication/las-2005-qos-book/</guid>
      <description></description>
    </item>

    <item>
      <title>Gestalt of the Grid</title>
      <link>/publication/las-2004-gestalt/</link>
      <pubDate>Thu, 01 Jan 2004 00:00:00 +0000</pubDate>
      <guid>/publication/las-2004-gestalt/</guid>
      <description></description>
    </item>

    <item>
      <title>Grid Middleware</title>
      <link>/publication/las-2004-grid-midleware/</link>
      <pubDate>Thu, 01 Jan 2004 00:00:00 +0000</pubDate>
      <guid>/publication/las-2004-grid-midleware/</guid>
      <description></description>
    </item>

    <item>
      <title>High-Level Grid Execution Patterns</title>
      <link>/publication/las-2004-grid-pattern/</link>
      <pubDate>Thu, 01 Jan 2004 00:00:00 +0000</pubDate>
      <guid>/publication/las-2004-grid-pattern/</guid>
      <description></description>
    </item>

    <item>
      <title>Middleware for Communications</title>
      <link>/publication/las-2004-middleware/</link>
      <pubDate>Thu, 01 Jan 2004 00:00:00 +0000</pubDate>
      <guid>/publication/las-2004-middleware/</guid>
      <description></description>
    </item>

    <item>
      <title>Commodity Grid Kits - Middleware for Building Grid Computing Environments</title>
      <link>/publication/las-2003-gridcomputing/</link>
      <pubDate>Wed, 01 Jan 2003 00:00:00 +0000</pubDate>
      <guid>/publication/las-2003-gridcomputing/</guid>
      <description></description>
    </item>

    <item>
      <title>Sourcebook of Parallel Computing</title>
      <link>/publication/las-2003-cmt-book/</link>
      <pubDate>Wed, 01 Jan 2003 00:00:00 +0000</pubDate>
      <guid>/publication/las-2003-cmt-book/</guid>
      <description></description>
    </item>

  </channel>
</rss>


text:
<?php
/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class Controller extends CController
{

	public function init() {
   		 $this->attachBehavior('bootstrap', new BController($this));
	}

	/**
	 * @var string the default layout for the controller view. Defaults to '//layouts/column1',
	 * meaning using a single column layout. See 'protected/views/layouts/column1.php'.
	 */
	public $layout='//layouts/column1';
	/**
	 * @var array context menu items. This property will be assigned to {@link CMenu::items}.
	 */
	public $menu=array();
	/**
	 * @var array the breadcrumbs of the current page. The value of this property will
	 * be assigned to {@link CBreadcrumbs::links}. Please refer to {@link CBreadcrumbs::links}
	 * for more details on how to specify this property.
	 */
	public $breadcrumbs=array();

	public $searchFilters=array();

	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	public function accessRules()
	{
		return array(

			array('allow',
				'actions'=>array('login','captcha','forgot'),
				'users'=>array('*'),
			),

			array('allow',
				'actions'=>array('admin','delete'),
				'users'=>array('Alvaro Ruiz'),
			),

			array('deny',
				'actions'=>array('admin','delete'),
				'users'=>array('*'),
			),

			//  If no actions are specified, rule applies to all actions.
			array('allow',
				'users'=>array('@'),
			),

			array('deny',
				'users'=>array('*'),
			),
		);
	}

}


text:
/*
 * BP-NmapDB.h -- Headers and structures relating to the extraction of the nmap
 * data from a mysql database.  The database includes numerous data items that are
 * redundant between structures.  They are preserved to keep convention with the db.
 *
 *
 *  Created on: Mar 14, 2010
 *      Author: Jason Medeiros
 */

#ifndef BPNMAPDB_H_
#define BPNMAPDB_H_

// port structure to use (names are taken from database fields)
typedef struct _BP_NMAPDB_PORTSTATS {
	char d[64];          // time
	char t[64];          // date
	size_t hostid;       // host id in db
	char target_ip[64];  // target ip (ascii)
	unsigned short port; // target port
	char protocol[16];   // protocol (tcp/udp/etc)
	char service[1024];  // nmap service info
	char state[16];      // (open/closed/filtered/etc)
	char fullversion[16];// full version info
	size_t scannerid;    // scanner id
	size_t runid;        // runid
	size_t rec_id;       // rec id
} BP_NMAPDB_PORTSTATS, *P_BP_NMAPDB_PORTSTATS;

// hosts structure
typedef struct _BP_NMAPDB_HOSTSTATS {
	size_t hostid;
	char ip[64];
	char user[1024];
	size_t userid;
	char d[64];
	char t[64];
	size_t open_ports;
	size_t ports_scanned;
	size_t runid;
	size_t scanner_id;
	size_t rec_id;
} BP_NMAPDB_HOSTSTATS, *P_BP_NMAPDB_HOSTSTATS;

// target structure
typedef struct _BP_NMAPDB_TARGETS {
	char host[1024];
	char d[64];
	char t[64];
	char ip[64];
	size_t ipnum;
	char mac[64];
	char macvendor[64];
	size_t flag;
	size_t hostid;
	char description[1024];
	char os_guessed[1024];
	char os_known[1024];
	char fingerprint[1024];
	size_t rec_id;
} BP_NMAPDB_TARGETS, *P_NMAPDB_TARGETS;

// scanner (user) table
typedef struct _BP_NMAPDB_SCANNERS {
	char scanner[1024]; // username
	char scanner_ip[64]; // ip scanner used
	char description[1024]; // description
	char d[64];
	char t[64];
	size_t flag;
	size_t scanner_id;
	size_t rec_id;
} BP_NMAPDB_SCANNERS, *P_BP_NMAPDB_SCANNERS;

// runlist table
typedef struct _BP_NMAPDB_RUNLIST {
	char d[64];
	char t[64];
	size_t run_type;
	char user[1024];
	size_t userid;
	char host[1024];
	char host_ip[64];
	size_t numscanned;
	size_t numup;
	size_t runid;
	size_t rec_id;
} BP_NMAPDB_RUNLIST, *P_BP_NMAPDB_RUNLIST;

// this enumerator defines the type of result in a BP_NMAPDB_RESULTS structure.
enum BP_NMAPDB_RESULT_TYPE {
	BP_NMAPDB_RESULT_RUNLIST,
	BP_NMAPDB_RESULT_SCANNERS,
	BP_NMAPDB_RESULT_TARGETS,
	BP_NMAPDB_RESULT_HOSTSTATS,
	BP_NMAPDB_RESULT_PORTSTATS
};

// generic result set container for nmap db
typedef struct _BP_NMAPDB_RESULTS {

	// number of records returned from the database
	size_t record_count;

	// opaque datatype holding one of a variety of different data structure types (normally arrays of database related
	// structures)
	void *opaque_data;

	// result type (defined above in enum)
	BP_NMAPDB_RESULT_TYPE type;

	// query used to generate results
	char *query;

} BP_NMAPDB_RESULTS, *P_BP_NMAPDB_RESULTS;

// full search results structures (populated in block class only)
typedef struct _BP_NMAPDB_SEARCH_RESULTS {

	// search results for runlist
	P_BP_NMAPDB_RESULTS runlist;

	// search result for scanners
	P_BP_NMAPDB_RESULTS scanners;

	// search results for targets
	P_BP_NMAPDB_RESULTS targets;

	// search results for hoststats
	P_BP_NMAPDB_RESULTS hoststats;

	// search results for portstats
	P_BP_NMAPDB_RESULTS portstats;

} BP_NMAPDB_SEARCH_RESULTS, *P_BP_NMAPDB_SEARCH_RESULTS;

/*
 * Using Search Functions:
 * ----------------------------------------------------
 * Each search function has a min, and max parameter.  Searching is done by
 * building a SQL query that basically matches all min/max items set in the
 * structures provided.  Min uses "<" operator, and Max uses ">" operator.
 * The like parameter matches using the "LIKE" keyword, and the equal parameter
 * matches with the "=" operator.  NULL parameters are not processed.  Like parameters
 * only work on character entries.
 */

// search the portstats database table
P_BP_NMAPDB_RESULTS BP_NDBSearchPortStats(P_BP_MYSQL_SESSION mysql_db, P_BP_NMAPDB_PORTSTATS min, P_BP_NMAPDB_PORTSTATS max, P_BP_NMAPDB_PORTSTATS like, P_BP_NMAPDB_PORTSTATS equal, size_t limitBottom, size_t limitTop);

// search the hoststats database table
P_BP_NMAPDB_RESULTS BP_NDBSearchHostStats(P_BP_MYSQL_SESSION mysql_db, P_BP_NMAPDB_HOSTSTATS min, P_BP_NMAPDB_HOSTSTATS max, P_BP_NMAPDB_HOSTSTATS like, P_BP_NMAPDB_HOSTSTATS equal, size_t limitBottom, size_t limitTop);

// search the targets database table
P_BP_NMAPDB_RESULTS BP_NDBSearchTargets(P_BP_MYSQL_SESSION mysql_db, P_NMAPDB_TARGETS min, P_NMAPDB_TARGETS max, P_NMAPDB_TARGETS like, P_NMAPDB_TARGETS equal, size_t limitBottom, size_t limitTop);

// search the scanners database table
P_BP_NMAPDB_RESULTS BP_NDBSearchScanners(P_BP_MYSQL_SESSION mysql_db, P_BP_NMAPDB_SCANNERS min, P_BP_NMAPDB_SCANNERS max, P_BP_NMAPDB_SCANNERS like, P_BP_NMAPDB_SCANNERS equal, size_t limitBottom, size_t limitTop);

// search the run list database table
P_BP_NMAPDB_RESULTS BP_NDBSearchRunlist(P_BP_MYSQL_SESSION mysql_db, P_BP_NMAPDB_RUNLIST min, P_BP_NMAPDB_RUNLIST max, P_BP_NMAPDB_RUNLIST like, P_BP_NMAPDB_RUNLIST equal, size_t limitBottom, size_t limitTop);

// ---------- Visualization Functions ----------------------------

// This function autodetects a result type and prints out the result.
int BP_NDBVisualizeResults(P_BP_NMAPDB_RESULTS result, size_t displayQuery);

// Visualizer for P_BP_NMAPDB_PORTSTATS structure
int BP_NDBVisualzePortStats(P_BP_NMAPDB_PORTSTATS data);

// Visualizer for P_BP_NMAPDB_HOSTSTATS structure
int BP_NDBVisualizeHostStats(P_BP_NMAPDB_HOSTSTATS data);

// Visualizer for P_NMAPDB_TARGETS structure
int BP_NDBVisualizeTargets(P_NMAPDB_TARGETS data);

// Visualizer for P_BP_NMAPDB_SCANNERS structure
int BP_NDBVisualizeScanners(P_BP_NMAPDB_SCANNERS data);

// Visualizer for P_BP_NMAPDB_RUNLIST structure
int BP_NDBVisualizeRunlist(P_BP_NMAPDB_RUNLIST data);

#endif /* BPNMAPDB_H_ */


text:
using Selfnet;
using Selfwin.Core;
using Selfwin.Items;

namespace Selfwin.Selfoss
{
    public class SelfwinApp : Core.SelfwinApp
    {
        public override IItemViewModel CreateItemVm(SelfWinSettings settings, Item item)
        {
            return new ItemViewModel(settings, item);
        }
    }
}


text:
import sys
import traceback

__author__ = 'dusanklinec'

def error_message(e, message=None, cause=None):
    """
    Formats exception message + cause
    :param e:
    :param message:
    :param cause:
    :return: formatted message, includes cause if any is set
    """
    if message is None and cause is None:
        return None
    elif message is None:
        return '%s, caused by %r' % (e.__class__, cause)
    elif cause is None:
        return message
    else:
        return '%s, caused by %r' % (message, cause)

class Error(Exception):
    """Generic EB client error."""
    def __init__(self, message=None, cause=None):
        super(Error, self).__init__(error_message(self, message, cause))
        self.cause = cause
        self.base_message = message

        self.exc_type, self.exc_value, self.exc_traceback = None, None, None
        self.traceback_formatted = None
        self.traceback = None

        self.load(cause, do_message=False)

    def load(self, cause=None, do_message=True):
        """
        Loads exception data from the current exception frame - should be called inside the except block
        :return:
        """
        if cause is not None:
            self.cause = cause
            if do_message:
                self.message = error_message(self, self.base_message, cause)

        self.exc_type, self.exc_value, self.exc_traceback = sys.exc_info()
        self.traceback_formatted = traceback.format_exc()
        self.traceback = traceback.extract_tb(self.exc_traceback)

class InvalidResponse(Error):
    """Invalid server response"""
    def __init__(self, message=None, cause=None):
        super(InvalidResponse, self).__init__(message=message, cause=cause)

class InvalidStatus(Error):
    """Invalid server response"""
    def __init__(self, message=None, cause=None):
        super(InvalidStatus, self).__init__(message=message, cause=cause)

class InvalidState(Error):
    """Invalid internal state"""
    def __init__(self, message=None, cause=None):
        super(InvalidState, self).__init__(message=message, cause=cause)

class RequestFailed(Error):
    """API request failed"""
    def __init__(self, message=None, cause=None):
        super(RequestFailed, self).__init__(message=message, cause=cause)

class EnvError(Error):
    """Problem with the environment running the script"""
    def __init__(self, message=None, cause=None):
        super(EnvError, self).__init__(message=message, cause=cause)

class NoSuchEndpoint(Error):
    """Endpoint could not be loaded from the configuration"""
    def __init__(self, message=None, cause=None):
        super(NoSuchEndpoint, self).__init__(message=message, cause=cause)

class SubprocessError(Error):
    """Error when executing a subprocess"""
    def __init__(self, message=None, cause=None):
        super(SubprocessError, self).__init__(message=message, cause=cause)

class SetupError(Error):
    """Generic error with the system setup"""
    def __init__(self, message=None, cause=None):
        super(SetupError, self).__init__(message=message, cause=cause)

class AccessForbiddenError(Error):
    """Access to the resource was forbidden"""
    def __init__(self, message=None, cause=None):
        super(AccessForbiddenError, self).__init__(message=message, cause=cause)


text:
ViewerJS combines a number of excellent open source tools that are built on HTML and javascript. ViewerJS was funded by [NLnet foundation](https://nlnet.nl) and developed by [KO GmbH](http://kogmbh.com).

The heavy lifting in ViewerJS is done by these awesome projects:

### WebODF

WebODF is a JavaScript library created by [KO GmbH](http://kogmbh.com). It was started by Jos van den Oever at KO and is now developed by a growing team including external collaborators. It makes it easy to add Open Document Format (ODF) support to your website and to your mobile or desktop applications. It uses HTML and CSS to display ODF documents.

### PDF.js

PDF.js is a library created by Andreas Gal and others at Mozilla Labs. It is an HTML5 technology experiment that explores building a faithful and efficient Portable Document Format (PDF) renderer without native code assistance.

### Examples and more

You can find additional information, some usage guides, and live examples at [the project homepage](http://viewerjs.org).

### Building

ViewerJS uses [`cmake`](http://cmake.org/). Just follow these steps:

```bash
git clone git@github.com:kogmbh/ViewerJS.git
mkdir build
cd build
cmake ../ViewerJS
make
```

You will find the following two products in the build directory if everything goes well:
- `viewerjs-{x.y.z}.zip`
- `viewerjs-wordpress-{x.y.z}.zip`

... where `{x.y.z}` denotes the version.

### License

ViewerJS is a Free Software project. All code is available under the AGPL.

If you are interested in using ViewerJS in your commercial product
(and do not want to disclose your sources / obey AGPL),
contact [KO GmbH](http://kogmbh.com) for a commercial license.


text:
layout: default
titel: Angebote
kennung: projectrequirements
---

In this section, you will find possible guidelines for the project, which could help the students to
improve the project.

# Project Plan

A rough project plan / course plan would be useful to determine when which parts of the project should be finished. With this specification, you can prevent the stagnation at a task or see the fulfilled tasks, which are already due. Also, this serves as a reference for the students so they do not put too much time into a themed area. The students could thereby assess their ability to test expenses.

# Items
Teachers could already develop rough tasks / items during the elaboration of the task, which the
students would have to divide again into sub-tasks. A major task at the beginning of the project could
be that the students could put together requirements for the system. This could be used to develop
use cases or user stories. These must then be implemented, for example, by the developers. By the
number of items to be done, the students would have a feeling for the effort that would still be
needed.

## Scrum-Board
The scrum-board is the tool that represents how far an item has been edited. This is mainly for the overview of the individual tasks and the progress. In general, the scrum-board is divided into several columns:

### Todos / Stories
Here are the items listed as stories, which must be implemented by the developers. This can be done
from the backlog or you can simply create new tasks. Often it is to create a story task, from which in
turn more can arise.

### Progress
Here are the tasks listed that should be currently handled by the project members.

### Testing Review
In this section, completed tasks are checked by other project members and, if necessary, tested for
acceptance criteria

### Done
This is where the tasks are performed when they are completely revised and meet all acceptance
criteria.

A scrum board could be created digitally, but also analog. There is a lot of free tools available online for this board, which also work very well. The illustration is only an example of a scrum board. It can be seen that the items have different colors to distinguish the type of the item. Another methodology in Scrum would be to place a sticker or point on an item after the last day, which was in the same state the previous day. This means that if Item 1 remains in the "Progress" area for three days, it will receive three stickers. This allows you to see how long an item is already in the

## Tools
With project work hardly any tools are needed. The problem is to make the right choice. Tools should
make working on a project more efficient. Since there were participants from different locations in
our project, one should absolutely use tools that enable constant communication to be maintained. If
possible via instant messaging or in the best case via voice or video conferencing. The next section
will deal with this topic.

#### Further reading
[Atlasian - How to build a kick-ass agile team](https://www.atlassian.com/agile/teams)

[Agile42 - Scrum Roles](http://www.agile42.com/en/agile-info-center/scrum-roles/)

[Scrum.de - Scrum Definition](https://www.scrum.de/scrum-definitionen/)


text:
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
    using Microsoft.Rest.Azure;
    using Models;

    /// <summary>
    /// BackupOperationResultsOperations operations.
    /// </summary>
    public partial interface IBackupOperationResultsOperations
    {
        /// <summary>
        /// Provides the status of the delete operations such as deleting
        /// backed up item. Once the operation has started, the status code
        /// in the response would be Accepted. It will continue to be in this
        /// state till it reaches completion. On successful completion, the
        /// status code will be OK. This method expects OperationID as an
        /// argument. OperationID is part of the Location header of the
        /// operation response.
        /// </summary>
        /// <param name='vaultName'>
        /// The name of the recovery services vault.
        /// </param>
        /// <param name='resourceGroupName'>
        /// The name of the resource group where the recovery services vault
        /// is present.
        /// </param>
        /// <param name='operationId'>
        /// OperationID which represents the operation.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string operationId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
    }
}


text:
#include <iostream>

#include "ECS.h"

ECS_TYPE_IMPLEMENTATION;

using namespace ECS;

struct Position
{
	ECS_DECLARE_TYPE;

	Position(float x, float y) : x(x), y(y) {}
	Position() {}

	float x;
	float y;
};

ECS_DEFINE_TYPE(Position);

struct Rotation
{
	ECS_DECLARE_TYPE;

	Rotation(float angle) : angle(angle) {}
	Rotation() {}

	float angle;
};

ECS_DEFINE_TYPE(Rotation);

struct SomeComponent
{
	ECS_DECLARE_TYPE;

	SomeComponent() {}
};

ECS_DEFINE_TYPE(SomeComponent);

struct SomeEvent
{
	ECS_DECLARE_TYPE;

	int num;
};

ECS_DEFINE_TYPE(SomeEvent);

class TestSystem : public EntitySystem,
	public EventSubscriber<Events::OnEntityCreated>,
	public EventSubscriber<Events::OnEntityDestroyed>,
	public EventSubscriber<Events::OnComponentRemoved<Position>>,
	public EventSubscriber<Events::OnComponentRemoved<Rotation>>,
	public EventSubscriber<SomeEvent>
{
public:
	virtual ~TestSystem() {}

	virtual void configure(class World* world) override
	{
		world->subscribe<Events::OnEntityCreated>(this);
		world->subscribe<Events::OnEntityDestroyed>(this);
		world->subscribe<Events::OnComponentRemoved<Position>>(this);
		world->subscribe<Events::OnComponentRemoved<Rotation>>(this);
		world->subscribe<SomeEvent>(this);
	}

	virtual void unconfigure(class World* world) override
	{
		world->unsubscribeAll(this);
	}

	virtual void tick(class World* world, float deltaTime) override
	{
		world->each<Position, Rotation>([&](Entity* ent, ComponentHandle<Position> pos, ComponentHandle<Rotation> rot) -> void {
			pos->x += deltaTime;
			pos->y += deltaTime;
			rot->angle += deltaTime * 2;
		});
	}

	virtual void receive(class World* world, const Events::OnEntityCreated& event) override
	{
		std::cout << "An entity was created!" << std::endl;
	}

	virtual void receive(class World* world, const Events::OnEntityDestroyed& event) override
	{
		std::cout << "An entity was destroyed!" << std::endl;
	}

	virtual void receive(class World* world, const Events::OnComponentRemoved<Position>& event) override
	{
		std::cout << "A position component was removed!" << std::endl;
	}

	virtual void receive(class World* world, const Events::OnComponentRemoved<Rotation>& event) override
	{
		std::cout << "A rotation component was removed!" << std::endl;
	}

	virtual void receive(class World* world, const SomeEvent& event) override
	{
		std::cout << "I received SomeEvent with value " << event.num << "!" << std::endl;

		// Let's delete an entity while iterating because why not?
		world->all([&](Entity* ent) {
			if (ent->getEntityId() + 1 == event.num)
				world->destroy(world->getById(event.num));

			if (ent->getEntityId() == event.num)
				std::cout << "Woah, we shouldn't get here!" << std::endl;
		});
	}
};

int main(int argc, char** argv)
{
	std::cout << "EntityComponentSystem Test" << std::endl
		<< "==========================" << std::endl;

	World* world = World::createWorld();

	EntitySystem* testSystem = world->registerSystem(new TestSystem());

	Entity* ent = world->create();
	auto pos = ent->assign<Position>(0.f, 0.f);
	auto rot = ent->assign<Rotation>(0.f);

	std::cout << "Initial values: position(" << pos->x << ", " << pos->y << "), rotation(" << rot->angle << ")" << std::endl;

	world->tick(10.f);

	std::cout << "After tick(10): position(" << pos->x << ", " << pos->y << "), rotation(" << rot->angle << ")" << std::endl;

	world->disableSystem(testSystem);

	world->tick(10.f);

	std::cout << "After tick(10) and DisableSystem(testSystem): position(" << pos->x << ", " << pos->y << "), rotation(" << rot->angle << ")" << std::endl;

	world->enableSystem(testSystem);

	world->tick(10.f);

	std::cout << "After tick(10) and EnableSystem(testSystem): position(" << pos->x << ", " << pos->y << "), rotation(" << rot->angle << ")" << std::endl;

	ent->remove<Position>();
	ent->remove<Rotation>();

	std::cout << "Creating more entities..." << std::endl;

	for (int i = 0; i < 10; ++i)
	{
		ent = world->create();
		ent->assign<SomeComponent>();
	}

	int count = 0;
	std::cout << "Counting entities with SomeComponent..." << std::endl;
	// range based for loop
	for (auto ent : world->each<SomeComponent>())
	{
		++count;
		std::cout << "Found entity #" << ent->getEntityId() << std::endl;
	}
	std::cout << count << " entities have SomeComponent!" << std::endl;

	// Emitting events
	world->emit<SomeEvent>({ 4 });

	std::cout << "We have " << world->getCount() << " entities right now." << std::endl;
	world->cleanup();
	std::cout << "After a cleanup, we have " << world->getCount() << " entities." << std::endl;

	std::cout << "Destroying the world..." << std::endl;

	world->destroyWorld();

	std::cout << "Press any key to exit..." << std::endl;
	std::getchar();

	return 0;
}


text:
<?php

namespace Kunstmaan\FormBundle\Helper;

use ArrayObject;
use Doctrine\ORM\EntityManager;
use Kunstmaan\FormBundle\Entity\FormAdaptorInterface;
use Kunstmaan\FormBundle\Entity\FormSubmission;
use Kunstmaan\FormBundle\Entity\FormSubmissionField;
use Kunstmaan\FormBundle\Event\FormEvents;
use Kunstmaan\FormBundle\Event\SubmissionEvent;
use Kunstmaan\NodeBundle\Entity\Node;
use Kunstmaan\NodeBundle\Helper\RenderContext;
use Kunstmaan\PagePartBundle\Entity\PagePartRef;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RouterInterface;

/**
 * The form handler handles everything from creating the form to handling the submitted form
 */
class FormHandler implements FormHandlerInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function handleForm(FormPageInterface $page, Request $request, RenderContext $context)
    {
        /* @var EntityManager $em */
        $em = $this->container->get('doctrine.orm.entity_manager');
        /* @var FormBuilderInterface $formBuilder */
        $formBuilder = $this->container->get('form.factory')->createBuilder(FormType::class);
        /* @var RouterInterface $router */
        $router = $this->container->get('router');
        /* @var ArrayObject $fields */
        $fields = new \ArrayObject();
        $pageParts = $em->getRepository(PagePartRef::class)->getPageParts($page, $page->getFormElementsContext());
        foreach ($pageParts as $sequence => $pagePart) {
            if ($pagePart instanceof FormAdaptorInterface) {
                $pagePart->adaptForm($formBuilder, $fields, $sequence);
            }
        }

        $form = $formBuilder->getForm();
        if ($request->getMethod() == 'POST') {
            $form->handleRequest($request);
            if ($form->isSubmitted() && $form->isValid()) {
                $formSubmission = new FormSubmission();
                $formSubmission->setIpAddress($request->getClientIp());
                $formSubmission->setNode($em->getRepository(Node::class)->getNodeFor($page));
                $formSubmission->setLang($request->getLocale());
                $em->persist($formSubmission);

                /* @var FormSubmissionField $field */
                foreach ($fields as $field) {
                    $field->setSubmission($formSubmission);
                    $field->onValidPost($form, $formBuilder, $request, $this->container);
                    $em->persist($field);
                }

                $em->flush();
                $em->refresh($formSubmission);

                $event = new SubmissionEvent($formSubmission, $page);
                $this->container->get('event_dispatcher')->dispatch($event, FormEvents::ADD_SUBMISSION);

                return new RedirectResponse($page->generateThankYouUrl($router, $context));
            }
        }
        $context['frontendform'] = $form->createView();
        $context['frontendformobject'] = $form;

        return null;
    }
}


text:
using FluentAssertions;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Thinktecture.IdentityServer.Core.Validation;
using Xunit;

namespace Thinktecture.IdentityServer.Tests.Validation
{
    public class BearerTokenUsageValidation
    {
        const string Category = "BearerTokenUsageValidator Tests";

        [Fact]
        [Trait("Category", Category)]
        public async Task No_Header_no_Body_Get()
        {
            var request = new HttpRequestMessage();
            request.Method = HttpMethod.Get;

            var validator = new BearerTokenUsageValidator();
            var result = await validator.ValidateAsync(request);

            result.TokenFound.Should().BeFalse();
        }

        [Fact]
        [Trait("Category", Category)]
        public async Task No_Header_no_Body_Post()
        {
            var request = new HttpRequestMessage();
            request.Method = HttpMethod.Post;
            request.Content = new FormUrlEncodedContent(new Dictionary<string, string>());

            var validator = new BearerTokenUsageValidator();
            var result = await validator.ValidateAsync(request);

            result.TokenFound.Should().BeFalse();
        }

        [Fact]
        [Trait("Category", Category)]
        public async Task Non_Bearer_Scheme_Header()
        {
            var request = new HttpRequestMessage();
            request.Method = HttpMethod.Get;
            request.Headers.Add("Authorization", "Foo Bar");

            var validator = new BearerTokenUsageValidator();
            var result = await validator.ValidateAsync(request);

            result.TokenFound.Should().BeFalse();
        }

        [Fact]
        [Trait("Category", Category)]
        public async Task Empty_Bearer_Scheme_Header()
        {
            var request = new HttpRequestMessage();
            request.Method = HttpMethod.Get;
            request.Headers.Add("Authorization", "Bearer");

            var validator = new BearerTokenUsageValidator();
            var result = await validator.ValidateAsync(request);

            result.TokenFound.Should().BeFalse();
        }

        [Fact]
        [Trait("Category", Category)]
        public async Task Whitespaces_Bearer_Scheme_Header()
        {
            var request = new HttpRequestMessage();
            request.Method = HttpMethod.Get;
            request.Headers.Add("Authorization", "Bearer           ");

            var validator = new BearerTokenUsageValidator();
            var result = await validator.ValidateAsync(request);

            result.TokenFound.Should().BeFalse();
        }

        [Fact]
        [Trait("Category", Category)]
        public async Task Valid_Bearer_Scheme_Header()
        {
            var request = new HttpRequestMessage();
            request.Method = HttpMethod.Get;
            request.Headers.Add("Authorization", "Bearer token");

            var validator = new BearerTokenUsageValidator();
            var result = await validator.ValidateAsync(request);

            result.TokenFound.Should().BeTrue();
            result.Token.Should().Be("token");
            result.UsageType.Should().Be(BearerTokenUsageType.AuthorizationHeader);
        }

        [Fact]
        [Trait("Category", Category)]
        public async Task Valid_Body_Post()
        {
            var request = new HttpRequestMessage();
            request.Method = HttpMethod.Post;
            request.Content = new FormUrlEncodedContent(new Dictionary<string, string>
                {
                    { "access_token", "token" }
                });

            var validator = new BearerTokenUsageValidator();
            var result = await validator.ValidateAsync(request);

            result.TokenFound.Should().BeTrue();
            result.Token.Should().Be("token");
            result.UsageType.Should().Be(BearerTokenUsageType.PostBody);
        }

        [Fact]
        [Trait("Category", Category)]
        public async Task Body_Post_empty_Token()
        {
            var request = new HttpRequestMessage();
            request.Method = HttpMethod.Post;
            request.Content = new FormUrlEncodedContent(new Dictionary<string, string>
                {
                    { "access_token", "" }
                });

            var validator = new BearerTokenUsageValidator();
            var result = await validator.ValidateAsync(request);

            result.TokenFound.Should().BeFalse();
        }

        [Fact]
        [Trait("Category", Category)]
        public async Task Body_Post_Whitespace_Token()
        {
            var request = new HttpRequestMessage();
            request.Method = HttpMethod.Post;
            request.Content = new FormUrlEncodedContent(new Dictionary<string, string>
                {
                    { "access_token", "    " }
                });

            var validator = new BearerTokenUsageValidator();
            var result = await validator.ValidateAsync(request);

            result.TokenFound.Should().BeFalse();
        }

        [Fact]
        [Trait("Category", Category)]
        public async Task Body_Post_no_Token()
        {
            var request = new HttpRequestMessage();
            request.Method = HttpMethod.Post;
            request.Content = new FormUrlEncodedContent(new Dictionary<string, string>
                {
                    { "foo", "bar" }
                });

            var validator = new BearerTokenUsageValidator();
            var result = await validator.ValidateAsync(request);

            result.TokenFound.Should().BeFalse();
        }
    }
}


text:
using System.Linq;
using AllReady.Controllers;
using AllReady.Features.Organizations;
using AllReady.ViewModels;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Moq;
using System.Threading.Tasks;
using Xunit;
using AllReady.UnitTest.Extensions;
using AllReady.ViewModels.Organization;

namespace AllReady.UnitTest.Controllers
{
    public class OrganizationControllerTests
    {
        #region ShowOrganization Action Tests

        [Fact]
        public void IndexReturnsAView()
        {
            var controller = new OrganizationController(Mock.Of<IMediator>());
            var result = controller.Index();

            Assert.IsType<ViewResult>(result);
        }

        [Fact]
        public void IndexSendsOrganizationsQuery()
        {
            var mockedMediator = new Mock<IMediator>();
            var controller = new OrganizationController(mockedMediator.Object);
            controller.Index();

            mockedMediator.Verify(x => x.Send(It.IsAny<OrganizationsQuery>()), Times.Once());
        }

        [Fact]
        public void IndexHasRouteAttributeWithCorrectRoute()
        {
            var sut = new OrganizationController(null);
            var routeAttribute = sut.GetAttributesOn(x => x.Index()).OfType<RouteAttribute>().SingleOrDefault();
            Assert.NotNull(routeAttribute);
            Assert.Equal(routeAttribute.Template, "Organizations/");
        }

        [Fact]
        public void ShowOrganizationHasRouteAttributeWithCorrectRoute()
        {
            var sut = new OrganizationController(null);
            var routeAttribute = (RouteAttribute)sut.GetAttributesOn(x => x.ShowOrganization(It.IsAny<int>())).SingleOrDefault(x => x.GetType() == typeof(RouteAttribute));
            Assert.NotNull(routeAttribute);
            Assert.Equal(routeAttribute.Template, "Organization/{id}/");
        }

        [Fact]
        public async Task ShowOrganization_ReturnsCorrectView()
        {
            OrganizationController controller;
            MockMediatorOrganizationDetailsQuery(out controller);

            var result = await controller.ShowOrganization(1);

            Assert.NotNull(result);
            Assert.IsType<ViewResult>(result);

            var finalResult = result as ViewResult;

            Assert.Equal("Organization", finalResult.ViewName);
        }

        [Fact]
        public async Task ShowOrganization_ReturnsNotFoundForNullOrganization()
        {
            OrganizationController controller;
            MockMediatorOrganizationDetailsQueryNullResult(out controller);

            var result = await controller.ShowOrganization(1) as NotFoundResult;

            Assert.NotNull(result);
        }

        [Fact]
        public async Task ShowOrganization_ReturnsBadRequestForZeroId()
        {
            OrganizationController controller;
            MockMediatorOrganizationDetailsQuery(out controller);

            var result = await controller.ShowOrganization(0) as BadRequestResult;

            Assert.NotNull(result);
        }

        #endregion

        #region PrivacyPolicy Action Tests

        [Fact]
        public async Task PrivacyPolicy_ReturnsCorrectViewWhenOrgHasAPolicyDefined()
        {
            var modelWithPolicy = new OrganizationPrivacyPolicyViewModel { OrganizationName = "Org 2", Content = "A privacy policy" };

            OrganizationController controller;
            MockMediatorOrganizationPrivacyPolicyQuery(out controller, modelWithPolicy);

            var result = await controller.OrganizationPrivacyPolicy(2) as ViewResult;

            Assert.NotNull(result);
            Assert.Equal("OrgPrivacyPolicy", result.ViewName);
        }

        [Fact]
        public async Task PrivacyPolicy_ReturnsRedirectToActionWhenOrgHasNoPolicyDefined()
        {
            OrganizationController controller;
            MockMediatorOrganizationPrivacyPolicyQuery(out controller);

            var result = await controller.OrganizationPrivacyPolicy(2) as RedirectToActionResult;

            Assert.NotNull(result);
        }

        [Fact]
        public async Task PrivacyPolicy_ReturnsRedirectToActionForNullOrganization()
        {
            OrganizationController controller;
            MockMediatorOrganizationPrivacyPolicyQueryNullResult(out controller);

            var result = await controller.OrganizationPrivacyPolicy(1) as RedirectToActionResult;

            Assert.NotNull(result);
            Assert.Equal("ShowOrganization", result.ActionName);
        }

        [Fact]
        public async Task PrivacyPolicy_ReturnsBadRequestForZeroId()
        {
            OrganizationController controller;
            MockMediatorOrganizationPrivacyPolicyQuery(out controller);

            var result = await controller.OrganizationPrivacyPolicy(0) as BadRequestResult;

            Assert.NotNull(result);
        }

        #endregion

        #region Helper Methods

        private static void MockMediatorOrganizationDetailsQuery(out OrganizationController controller, OrganizationViewModel model = null)
        {
            if (model == null)
                model = new OrganizationViewModel { Id = 1, Name = "Org 1" };

            var mockMediator = new Mock<IMediator>();
            mockMediator.Setup(mock => mock.SendAsync(It.IsAny<OrganizationDetailsQueryAsync>())).Returns(() => Task.FromResult(model)).Verifiable();
            controller = new OrganizationController(mockMediator.Object);
        }

        private static void MockMediatorOrganizationDetailsQueryNullResult(out OrganizationController controller)
        {
            var mockMediator = new Mock<IMediator>();
            mockMediator.Setup(mock => mock.SendAsync(It.IsAny<OrganizationDetailsQueryAsync>())).Returns(() => Task.FromResult((OrganizationViewModel)null)).Verifiable();
            controller = new OrganizationController(mockMediator.Object);
        }

        private static void MockMediatorOrganizationPrivacyPolicyQuery(out OrganizationController controller, OrganizationPrivacyPolicyViewModel model = null)
        {
            if (model == null) model = new OrganizationPrivacyPolicyViewModel { OrganizationName = "Org 1", Content = null };

            var mockMediator = new Mock<IMediator>();
            mockMediator.Setup(mock => mock.SendAsync(It.IsAny<OrganziationPrivacyPolicyQueryAsync>())).Returns(() => Task.FromResult(model)).Verifiable();
            controller = new OrganizationController(mockMediator.Object);
        }

        private static void MockMediatorOrganizationPrivacyPolicyQueryNullResult(out OrganizationController controller)
        {
            var mockMediator = new Mock<IMediator>();
            mockMediator.Setup(mock => mock.SendAsync(It.IsAny<OrganziationPrivacyPolicyQueryAsync>())).Returns(() => Task.FromResult((OrganizationPrivacyPolicyViewModel)null)).Verifiable();
            controller = new OrganizationController(mockMediator.Object);
        }

        #endregion
    }
}


text:
package com.example.yifengliu.transitionfeature;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.transition.Explode;
import android.transition.Fade;
import android.transition.Slide;
import android.transition.TransitionManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

public class MainActivity extends ActionBarActivity implements View.OnClickListener {

    private ViewGroup mRootView;
    private View mRedBox, mGreenBox, mBlueBox, mBlackBox;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRootView = (ViewGroup) findViewById(R.id.layout_root_view);
        mRootView.setOnClickListener(this);
        mRedBox = findViewById(R.id.red_box);
        mGreenBox = findViewById(R.id.green_box);
        mBlueBox = findViewById(R.id.blue_box);
        mBlackBox = findViewById(R.id.black_box);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        TransitionManager.beginDelayedTransition(mRootView, new Explode());
        toggleVisibility(mRedBox, mGreenBox, mBlueBox, mBlackBox);
    }

    private static void toggleVisibility(View... views) {
        for (View view : views) {
            boolean isVisible = view.getVisibility() == View.VISIBLE;
            view.setVisibility(isVisible ? View.INVISIBLE : View.VISIBLE);
        }
    }
}


text:
<?php
//retrieve our data from POST
$username = $_POST['username'];
$password1 = $_POST['password1'];
$password2 = $_POST['password2'];
$email = $_POST['email'];

if($password1 != $password2)
    header('Location: registration.html');

if(strlen($username) > 30)
    header('Location: registration.html');

$hash = hash('sha256', $password1);

function createSalt()
{
    $text = md5(uniqid(rand(), true));
    return substr($text, 0, 3);
}

$salt = createSalt();
$password = hash('sha256', $salt . $hash);

$conn = mysql_connect('localhost', 'root', 'meigic1212');
mysql_select_db('login', $conn);

//sanitize username
$username = mysql_real_escape_string($username);

$query = "INSERT INTO member ( username, password, email, salt )
        VALUES ( '$username', '$password', '$email', '$salt' );";
mysql_query($query);

mysql_close();

header('Location: login.php');
?>


text:
Djanoa
======

Client PHP pour la plateforme [Djanoa](http://www.djanoa.com).

Installation
------------
Pour l'installer il faut télécharger le projet et le décompresser dans votre projet.

Utilisation
-----------
Il faut d'abord créer un compte sur [le site de djanoa](http://www.djanoa.com).

Ensuite vous faites les configurations
```php
require 'djanoa_php/src/djanoa.class.php';

$client = new Djanoa(VOTRE_NUMERO_COURT, CODE_DE_VOTRE_COMPTE, MOT_DE_PASSE);
```

ensuite pour envoyer un SMS il suffit de faire :

```php
$client->send_sms('221777777777', 'juste pour tester mon client PHP');
```

Gestion des erreurs
-------------------

Si vous voulez allez plus loin vous pouvez récupérer la réponse et voir s'il n'y a pas d'erreur.

Le code suivant permet d'envoyer un SMS et, s'il y'a une erreur, affiche le code de l'erreur, le message d'erreur ainsi que l'adresse IP de l'envoyeur.
```php
$reponse = $sms->send_sms('221777777777', 'juste pour tester mon client PHP');

if $reponse->sent() {
  echo "le sms est envoyé";
} else {
  echo $reponse->getError()->getCode();
  echo $reponse->getError()->getMessage();
  echo $reponse->getError()->getIp();
}
```

Copyright
---------
Copyright 2013 Cheikh Sidya CAMARA. Voir la [LICENSE](https://github.com/scicasoft/djanoa_php/blob/master/LICENSE.md) pour plus de détails.


text:
extern int ddLogLevel;

@interface ChangesListener ()
@property (nonatomic) NSMutableSet* delegates;
@property (nonatomic) ChangesOutputStream* stream;
@property (nonatomic) MKNetworkOperation* operation;
@property (nonatomic) NSNumber* seq;
@end

@implementation ChangesListener

-(id)initWithDatabase:(Database*)database filter:(Filter*)filter {
    self = [super init];
    if (self) {
        _database = database;
        _filter = filter;
        _delegates = [NSMutableSet set];
        _stream = [[ChangesOutputStream alloc] initWithDelegate:self];
        _seq = @0;
    }
    return self;
}

-(void)addDelegate:(NSObject<ChangesDelegate>*)delegate {
    if (![self.delegates containsObject:delegate]) {
        [self.delegates addObject:delegate];
    }

    if (self.delegates.count == 1) {
        [self getSeqAndStart];
    }
}

-(void)removeDelegate:(NSObject<ChangesDelegate>*)delegate {
    if ([self.delegates containsObject:delegate]) {
        [self.delegates removeObject:delegate];
    }

    if (self.delegates.count == 0) {
        [self stop];
    }
}

-(void)getSeqAndStart {
    DDLogVerbose(@"[ChangesListener] Loading current update_seq and start listening for changes. Filter:%@", self.filter);
    [self.database
     getPath:@""
     params:nil
     progressBlock:nil
     finishedBlock:^(MKNetworkOperation* completedOperation) {
         NSDictionary* response = [completedOperation responseJSON];
         self.seq = [response getNumberWithPath:@"update_seq"];
         DDLogVerbose(@"[ChangesListener] Done loading current update_seq:%@. Starting listening for changes. Filter:%@", self.seq, self.filter);
         [self start];
     }
     errorBlock:^(NSError* error) {
         DDLogError(@"[ChangesListener] Error:%@ loading current update_seq and start listening for changes. Filter:%@", error.localizedDescription, self.filter);
         if (self.database.globalErrorBlock) {
             dispatch_async(dispatch_get_main_queue(), ^{
                 self.database.globalErrorBlock(error);
             });
         }
     }
     jsonParams:NO];
}

-(void)start {
    if (self.delegates.count == 0) return;
    DDLogVerbose(@"[ChangesListener] Start listening for changes. Filter:%@", self.filter);

    NSMutableDictionary* params = [@{@"feed":@"continuous",@"heartbeat":@10000,@"since":self.seq} mutableCopy];
    if (self.filter != nil) {
        [params addEntriesFromDictionary:self.filter.options];
        [params setObject:[NSString stringWithFormat:@"%@/%@",[self.filter.design.identifier substringFromIndex:8],self.filter.name] forKey:@"filter"];
    }

    self.operation = [self.database operationWithPath:@"_changes" params:params httpMethod:@"GET" jsonParams:YES];
    [self.operation addHeaders:@{@"Accept":@"application/json"}]; //Fixes NSUrlConnection bug as couchdb returns with mimetype application/json
    [self.operation addDownloadStream:self.stream];

    ChangesListener* weakSelf = self;
    [self.operation addCompletionHandler:^(MKNetworkOperation* completedOperation) {
        if (weakSelf.database.globalErrorBlock) {
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.database.globalErrorBlock([NSError errorWithDomain:@"ChangesStreamError" code:0 userInfo:@{NSLocalizedDescriptionKey:@"Changes stream completed."}]);
            });
        }
    } errorHandler:^(MKNetworkOperation* completedOperation, NSError* error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf performSelector:@selector(start) withObject:nil afterDelay:0.1];
            if (weakSelf.database.globalErrorBlock) {
                weakSelf.database.globalErrorBlock(error);
            }
        });
    }];

    [self.operation start];
}

-(void)stop {
    DDLogVerbose(@"[ChangesListener] Stop listening for changes. Filter:%@", self.filter);

    [self.operation cancel];
}

-(void)newChange:(NSDictionary*)changeDict {
    self.seq = [changeDict getNumberWithPath:@"seq"];
    Change* change = [[Change alloc] initWithData:changeDict];

    DDLogVerbose(@"[ChangesListener] New change:%@. Filter:%@", change, self.filter);

    for (NSObject<ChangesDelegate>* delegate in self.delegates) {
        [delegate newChange:change];
    }
}

@end


text:
package org.springframework.cloud.gcp.stream.binder.pubsub.properties;

/**
 * Properties common to consumers and producers.
 *
 * @author Mike Eltsufin
 * @since 1.1
 */
public class PubSubCommonProperties {

	private boolean autoCreateResources = true;

	public boolean isAutoCreateResources() {
		return this.autoCreateResources;
	}

	public void setAutoCreateResources(boolean autoCreateResources) {
		this.autoCreateResources = autoCreateResources;
	}
}


text:
package com.google.gerrit.pgm.init;

import static com.google.gerrit.pgm.init.api.InitUtil.username;

import com.google.common.primitives.Ints;
import com.google.gerrit.pgm.init.api.InitUtil;
import com.google.gerrit.pgm.init.api.Section;

public class HANAInitializer implements DatabaseConfigInitializer {

  @Override
  public void initConfig(Section databaseSection) {
    final String defInstanceNumber = "00";
    databaseSection.string("Server hostname", "hostname", "localhost");
    databaseSection.string("Instance number", "instance", defInstanceNumber,
        false);
    String instance = databaseSection.get("instance");
    Integer instanceNumber = Ints.tryParse(instance);
    if (instanceNumber == null || instanceNumber < 0 || instanceNumber > 99) {
      instanceIsInvalid();
    }
    databaseSection.string("Database username", "username", username());
    databaseSection.password("username", "password");
  }

  private void instanceIsInvalid() {
    throw InitUtil.die("database.instance must be in the range of 00 to 99");
  }
}


text:
local nginx_signals = require "kong.cmd.utils.nginx_signals"
local conf_loader = require "kong.conf_loader"
local pl_path = require "pl.path"
local log = require "kong.cmd.utils.log"

local function execute(args, opts)
  opts = opts or {}

  log.disable()
  -- only to retrieve the default prefix or use given one
  local default_conf = assert(conf_loader(nil, {
    prefix = args.prefix
  }))
  log.enable()
  assert(pl_path.exists(default_conf.prefix),
         "no such prefix: " .. default_conf.prefix)

  if opts.quiet then
    log.disable()
  end

  -- load <PREFIX>/kong.conf containing running node's config
  local conf = assert(conf_loader(default_conf.kong_env))
  assert(nginx_signals.stop(conf))

  if opts.quiet then
    log.enable()
  end

  log("Kong stopped")
end

local lapp = [[
Usage: kong stop [OPTIONS]

Stop a running Kong node (Nginx and other configured services) in given
prefix directory.

This command sends a SIGTERM signal to Nginx.

Options:
 -p,--prefix      (optional string) prefix Kong is running at
]]

return {
  lapp = lapp,
  execute = execute
}


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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.metastore.v1alpha.model;

/**
 * Request message for DataprocMetastore.ExportMetadata.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Dataproc Metastore API. For a detailed explanation
 * see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class ExportMetadataRequest extends com.google.api.client.json.GenericJson {

  /**
   * Optional. The type of the database dump. If unspecified, defaults to MYSQL.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String databaseDumpType;

  /**
   * A Cloud Storage URI of a folder, in the format gs:. A sub-folder containing exported files will
   * be created below it.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String destinationGcsFolder;

  /**
   * Optional. A request ID. Specify a unique request ID to allow the server to ignore the request
   * if it has completed. The server will ignore subsequent requests that provide a duplicate
   * request ID for at least 60 minutes after the first request.For example, if an initial request
   * times out, followed by another request with the same request ID, the server ignores the second
   * request to prevent the creation of duplicate commitments.The request ID must be a valid UUID
   * (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format). A zero UUID
   * (00000000-0000-0000-0000-000000000000) is not supported.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String requestId;

  /**
   * Optional. The type of the database dump. If unspecified, defaults to MYSQL.
   * @return value or {@code null} for none
   */
  public java.lang.String getDatabaseDumpType() {
    return databaseDumpType;
  }

  /**
   * Optional. The type of the database dump. If unspecified, defaults to MYSQL.
   * @param databaseDumpType databaseDumpType or {@code null} for none
   */
  public ExportMetadataRequest setDatabaseDumpType(java.lang.String databaseDumpType) {
    this.databaseDumpType = databaseDumpType;
    return this;
  }

  /**
   * A Cloud Storage URI of a folder, in the format gs:. A sub-folder containing exported files will
   * be created below it.
   * @return value or {@code null} for none
   */
  public java.lang.String getDestinationGcsFolder() {
    return destinationGcsFolder;
  }

  /**
   * A Cloud Storage URI of a folder, in the format gs:. A sub-folder containing exported files will
   * be created below it.
   * @param destinationGcsFolder destinationGcsFolder or {@code null} for none
   */
  public ExportMetadataRequest setDestinationGcsFolder(java.lang.String destinationGcsFolder) {
    this.destinationGcsFolder = destinationGcsFolder;
    return this;
  }

  /**
   * Optional. A request ID. Specify a unique request ID to allow the server to ignore the request
   * if it has completed. The server will ignore subsequent requests that provide a duplicate
   * request ID for at least 60 minutes after the first request.For example, if an initial request
   * times out, followed by another request with the same request ID, the server ignores the second
   * request to prevent the creation of duplicate commitments.The request ID must be a valid UUID
   * (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format). A zero UUID
   * (00000000-0000-0000-0000-000000000000) is not supported.
   * @return value or {@code null} for none
   */
  public java.lang.String getRequestId() {
    return requestId;
  }

  /**
   * Optional. A request ID. Specify a unique request ID to allow the server to ignore the request
   * if it has completed. The server will ignore subsequent requests that provide a duplicate
   * request ID for at least 60 minutes after the first request.For example, if an initial request
   * times out, followed by another request with the same request ID, the server ignores the second
   * request to prevent the creation of duplicate commitments.The request ID must be a valid UUID
   * (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format). A zero UUID
   * (00000000-0000-0000-0000-000000000000) is not supported.
   * @param requestId requestId or {@code null} for none
   */
  public ExportMetadataRequest setRequestId(java.lang.String requestId) {
    this.requestId = requestId;
    return this;
  }

  @Override
  public ExportMetadataRequest set(String fieldName, Object value) {
    return (ExportMetadataRequest) super.set(fieldName, value);
  }

  @Override
  public ExportMetadataRequest clone() {
    return (ExportMetadataRequest) super.clone();
  }

}


text:
If you would like to contribute to the development of OpenStack,
you must follow the steps in this page:

   http://docs.openstack.org/infra/manual/developers.html

Once those steps have been completed, changes to OpenStack
should be submitted for review via the Gerrit tool, following
the workflow documented at:

   http://docs.openstack.org/infra/manual/developers.html#development-workflow

Pull requests submitted through GitHub will be ignored.

Bugs should be filed on Launchpad, not GitHub:

   https://bugs.launchpad.net/networking-cisco

Tox environments provided in networking-cisco:

* py27, py34 - Unit tests run against Mitaka neutron, on different python2.7 and python3.4
* newton - Unit tests run against Newton neutron with python2.7
* master - Unit tests run against master neutron with python2.7
* coverage - provides a report on the test coverage
* compare-coverage - compares coverage reports from before and after the current changes
* pep8 - Checks code against the pep8 and OpenStack hacking rules


text:
using System;
using System.Collections.Generic;
using MiscUtil.Extensions;
namespace MiscUtil.Linq.Extensions
{
    public static partial class DataProducerExt
    {
        /// <summary>
        /// Groups the elements of a sequence according to a specified key selector function
        /// and creates a result value from each group and its key.
        /// </summary>
        /// <typeparam name="TKey">The return-type of the transform used to group the sequence</typeparam>
        /// <typeparam name="TSource">The values to be yielded by the original data-source</typeparam>
        /// <param name="keySelector">A function to extract the key for each element in hte original sequence.</param>
        /// <param name="source">The data-source to be grouped</param>
        /// <remarks>This will force each unique grouping key to
        /// be buffered, but not the data itself</remarks>
        public static IDataProducer<IProducerGrouping<TKey, TSource>> GroupBy<TSource, TKey>
            (this IDataProducer<TSource> source,
             Func<TSource, TKey> keySelector)
        {
            return source.GroupBy(keySelector,
                                  elt => elt,
                                  (key, elements) => (IProducerGrouping<TKey, TSource>)new ProducerGrouping<TKey, TSource>(key, elements),
                                  EqualityComparer<TKey>.Default);
        }
        /// <summary>
        /// Groups the elements of a sequence according to a specified key selector function
        /// and creates a result value from each group and its key.
        /// </summary>
        /// <typeparam name="TKey">The return-type of the transform used to group the sequence</typeparam>
        /// <typeparam name="TSource">The values to be yielded by the original data-source</typeparam>
        /// <param name="comparer">Used to compare grouping keys</param>
        /// <param name="keySelector">A function to extract the key for each element in hte original sequence.</param>
        /// <param name="source">The data-source to be grouped</param>
        /// <remarks>This will force each unique grouping key to
        /// be buffered, but not the data itself</remarks>
        public static IDataProducer<IProducerGrouping<TKey, TSource>> GroupBy<TSource, TKey>
            (this IDataProducer<TSource> source,
             Func<TSource, TKey> keySelector,
             IEqualityComparer<TKey> comparer)
        {
            return source.GroupBy(keySelector,
                                  elt => elt,
                                  (key, elements) => (IProducerGrouping<TKey, TSource>)new ProducerGrouping<TKey, TSource>(key, elements),
                                  comparer);
        }
        /// <summary>
        /// Groups the elements of a sequence according to a specified key selector function
        /// and creates a result value from each group and its key. The elements of each
        /// group are projected by using a specified function.
        /// </summary>
        /// <typeparam name="TElement">The return-type of the transform used to process the
        /// values within each grouping.</typeparam>
        /// <typeparam name="TKey">The return-type of the transform used to group the sequence</typeparam>
        /// <typeparam name="TSource">The values to be yielded by the original data-source</typeparam>
        /// <param name="elementSelector">A function to map each source element to an element in the appropriate group</param>
        /// <param name="keySelector">A function to extract the key for each element in hte original sequence.</param>
        /// <param name="source">The data-source to be grouped</param>
        /// <remarks>This will force each unique grouping key to
        /// be buffered, but not the data itself</remarks>
        public static IDataProducer<IProducerGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>
            (this IDataProducer<TSource> source,
             Func<TSource, TKey> keySelector,
             Func<TSource, TElement> elementSelector)
        {
            return source.GroupBy(keySelector,
                                  elementSelector,
                                  (key, elements) => (IProducerGrouping<TKey, TElement>)new ProducerGrouping<TKey, TElement>(key, elements),
                                  EqualityComparer<TKey>.Default);
        }
        /// <summary>
        /// Groups the elements of a sequence according to a specified key selector function
        /// and creates a result value from each group and its key.
        /// </summary>
        /// <typeparam name="TKey">The return-type of the transform used to group the sequence</typeparam>
        /// <typeparam name="TResult">The final values to be yielded after processing</typeparam>
        /// <typeparam name="TSource">The values to be yielded by the original data-source</typeparam>
        /// <param name="keySelector">A function to extract the key for each element in hte original sequence.</param>
        /// <param name="resultSelector">A function to create a result value from each group.</param>
        /// <param name="source">The data-source to be grouped</param>
        /// <remarks>This will force each unique grouping key to
        /// be buffered, but not the data itself</remarks>
        public static IDataProducer<TResult> GroupBy<TSource, TKey, TResult>
            (this IDataProducer<TSource> source,
             Func<TSource, TKey> keySelector,
             Func<TKey, IDataProducer<TSource>, TResult> resultSelector)
        {
            return source.GroupBy(keySelector,
                                  elt => elt,
                                  resultSelector,
                                  EqualityComparer<TKey>.Default);
        }
        /// <summary>
        /// Groups the elements of a sequence according to a specified key selector function
        /// and creates a result value from each group and its key. The elements of each
        /// group are projected by using a specified function.
        /// </summary>
        /// <typeparam name="TElement">The return-type of the transform used to process the
        /// values within each grouping.</typeparam>
        /// <typeparam name="TKey">The return-type of the transform used to group the sequence</typeparam>
        /// <typeparam name="TSource">The values to be yielded by the original data-source</typeparam>
        /// <param name="comparer">Used to compare grouping keys</param>
        /// <param name="elementSelector">A function to map each source element to an element in the appropriate group</param>
        /// <param name="keySelector">A function to extract the key for each element in hte original sequence.</param>
        /// <param name="source">The data-source to be grouped</param>
        /// <remarks>This will force each unique grouping key to
        /// be buffered, but not the data itself</remarks>
        public static IDataProducer<IProducerGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>
            (this IDataProducer<TSource> source,
             Func<TSource, TKey> keySelector,
             Func<TSource, TElement> elementSelector,
             IEqualityComparer<TKey> comparer)
        {
            return source.GroupBy(keySelector,
                                  elementSelector,
                                  (key, elements) => (IProducerGrouping<TKey, TElement>)new ProducerGrouping<TKey, TElement>(key, elements),
                                  comparer);
        }
        /// <summary>
        /// Groups the elements of a sequence according to a specified key selector function
        /// and creates a result value from each group and its key. The elements of each
        /// group are projected by using a specified function.
        /// </summary>
        /// <typeparam name="TElement">The return-type of the transform used to process the
        /// values within each grouping.</typeparam>
        /// <typeparam name="TKey">The return-type of the transform used to group the sequence</typeparam>
        /// <typeparam name="TResult">The final values to be yielded after processing</typeparam>
        /// <typeparam name="TSource">The values to be yielded by the original data-source</typeparam>
        /// <param name="elementSelector">A function to map each source element to an element in the appropriate group</param>
        /// <param name="keySelector">A function to extract the key for each element in hte original sequence.</param>
        /// <param name="resultSelector">A function to create a result value from each group.</param>
        /// <param name="source">The data-source to be grouped</param>
        /// <remarks>This will force each unique grouping key to
        /// be buffered, but not the data itself</remarks>
        public static IDataProducer<TResult> GroupBy<TSource, TKey, TElement, TResult>
            (this IDataProducer<TSource> source,
             Func<TSource, TKey> keySelector,
             Func<TSource, TElement> elementSelector,
             Func<TKey, IDataProducer<TElement>, TResult> resultSelector)
        {
            return source.GroupBy(keySelector, elementSelector, resultSelector, EqualityComparer<TKey>.Default);
        }
        /// <summary>
        /// Groups the elements of a sequence according to a specified key selector function
        /// and creates a result value from each group and its key.
        /// </summary>
        /// <typeparam name="TKey">The return-type of the transform used to group the sequence</typeparam>
        /// <typeparam name="TResult">The final values to be yielded after processing</typeparam>
        /// <typeparam name="TSource">The values to be yielded by the original data-source</typeparam>
        /// <param name="comparer">Used to compare grouping keys</param>
        /// <param name="keySelector">A function to extract the key for each element in hte original sequence.</param>
        /// <param name="resultSelector">A function to create a result value from each group.</param>
        /// <param name="source">The data-source to be grouped</param>
        /// <remarks>This will force each unique grouping key to
        /// be buffered, but not the data itself</remarks>
        public static IDataProducer<TResult> GroupBy<TSource, TKey, TResult>
            (this IDataProducer<TSource> source,
             Func<TSource, TKey> keySelector,
             Func<TKey, IDataProducer<TSource>, TResult> resultSelector,
             IEqualityComparer<TKey> comparer)
        {
            return source.GroupBy(keySelector,
                                  elt => elt,
                                  resultSelector,
                                  comparer);
        }
        /// <summary>
        /// Groups the elements of a sequence according to a specified key selector function
        /// and creates a result value from each group and its key. The elements of each
        /// group are projected by using a specified function.
        /// </summary>
        /// <typeparam name="TElement">The return-type of the transform used to process the
        /// values within each grouping.</typeparam>
        /// <typeparam name="TKey">The return-type of the transform used to group the sequence</typeparam>
        /// <typeparam name="TResult">The final values to be yielded after processing</typeparam>
        /// <typeparam name="TSource">The values to be yielded by the original data-source</typeparam>
        /// <param name="comparer">Used to compare grouping keys</param>
        /// <param name="elementSelector">A function to map each source element to an element in the appropriate group</param>
        /// <param name="keySelector">A function to extract the key for each element in hte original sequence.</param>
        /// <param name="resultSelector">A function to create a result value from each group.</param>
        /// <param name="source">The data-source to be grouped</param>
        /// <remarks>This will force each unique grouping key to
        /// be buffered, but not the data itself</remarks>
        public static IDataProducer<TResult> GroupBy<TSource, TKey, TElement, TResult>
            (this IDataProducer<TSource> source,
             Func<TSource, TKey> keySelector,
             Func<TSource, TElement> elementSelector,
             Func<TKey, IDataProducer<TElement>, TResult> resultSelector,
             IEqualityComparer<TKey> comparer)
        {
            source.ThrowIfNull("source");
            keySelector.ThrowIfNull("keySelector");
            elementSelector.ThrowIfNull("elementSelector");
            resultSelector.ThrowIfNull("resultSelector");
            comparer.ThrowIfNull("comparer");

            DataProducer<TResult> ret = new DataProducer<TResult>();

            Dictionary<TKey, DataProducer<TElement>> dictionary = new Dictionary<TKey, DataProducer<TElement>>(comparer);

            source.DataProduced += value =>
            {
                TKey key = keySelector(value);

                DataProducer<TElement> subProducer;

                if (!dictionary.TryGetValue(key, out subProducer))
                {
                    subProducer = new DataProducer<TElement>();
                    dictionary[key] = subProducer;
                    ret.Produce(resultSelector(key, subProducer));
                }
                subProducer.Produce(elementSelector(value));
            };

            source.EndOfData += () =>
            {
                foreach (DataProducer<TElement> value in dictionary.Values)
                {
                    value.End();
                }
                ret.End();
            };

            return ret;
        }
    }
}


text:
package com.anrisoftware.globalpom.core.durationformat;

import com.google.inject.AbstractModule;
import com.google.inject.assistedinject.FactoryModuleBuilder;

/**
 * Installs the duration format factory.
 *
 * @see DurationFormat
 * @see DurationFormatFactory
 *
 * @author Erwin Mueller, erwin.mueller@deventm.org
 * @since 1.9
 */
public class DurationFormatModule extends AbstractModule {

	@Override
	protected void configure() {
		install(new FactoryModuleBuilder().implement(DurationFormat.class,
				DurationFormat.class).build(DurationFormatFactory.class));
	}

}


text:
"""
Post-Sync RH
Map custom attributes/tags to Groups in CB
"""
import pyVmomi
from accounts.models import Group, GroupType
from common.methods import set_progress
from infrastructure.models import Server
from jobs.models import Job
from resourcehandlers.vmware import pyvmomi_wrapper
from resourcehandlers.vmware.pyvmomi_wrapper import get_connection

vm_custattr = '{{ vcenter_custom_attribute }}'

def run(job, logger=None, server=None, **kwargs):
    jp = job.job_parameters.cast()
    servers = Server.objects.filter(resource_handler__in=jp.resource_handlers.all())
    servers = servers.exclude(status="HISTORICAL")
    for server in servers:
        rh = server.resource_handler.cast()
        rh.get_api_wrapper()
        si = get_connection(rh.ip, rh.port, rh.serviceaccount, rh.servicepasswd, ssl_verification=False)
        vm = pyvmomi_wrapper.get_vm_by_name(si, server.get_vm_name())
        f = si.content.customFieldsManager.field
        for k, v in [(x.name, v.value) for x in f for v in vm.customValue if x.key == v.key]:
            if k == vm_custattr:
                try:
                    server.group = Group.objects.get(name=v)
                    server.save()
                except:
                    group_type, _ = GroupType.objects.get_or_create(group_type='Organization')
                    parent_group = None
                    group = Group.objects.create(name=v, type=group_type, parent=parent_group)
                    server.group = Group.objects.get(name=v)
                    server.save()
            else:
                group = Group.objects.get(name='Unassigned')
                server.group = group
                server.save()
    return "", "", ""