text:
stamplay-ebayclassifieds
===================

**This project is built on the [Stamplay](https://stamplay.com) platform with [Ionic Framework](http://ionicframework.com/) to show you how to build a post-and-search application, like [eBay Classifieds](https://itunes.apple.com/en/app/ebay-classifieds/id363971383?mt=8).**

*eBay is 20! During the last two decades hundreds of millions of people around the world have used the service to buy and sell items. Now its Classifieds mobile app is bringing free local listings to your pocket.*

In this project we'll show you how to use Stamplay with the amazing Ionic Framework to create a fully fledged native mobile app. We wanted to deliver something that can be reused in many ways so we decided to build an eBay Classifieds clone to let users search, post, and sell their items.

The app will have the following functionality:

* guest users can search, filter (Category and City) and view posted items
* guest users can post items to sell
* guest users need to confirm a valid email address before posting an item
* guest and logged in users can contact the owners of an item
* logged in users can track their listings
* guest and logged in users can contact the app administrator
* guest users need to signup with email and password to access all features

![picture alt](https://blog.stamplay.com/wp-content/uploads/2014/10/1200x687xeBay-Classifieds-Stamplay-clone.jpg.pagespeed.ic.MbBI4wa_eo.webp "The finished product – your own classifieds app!")

###[Click here to read the full tutorial](https://blog.stamplay.com/build-ios-and-android-post-and-search-app-like-ebay-classified-with-ionic-framework-and-angularjs/)###


text:
var log = require('./log');

var commands = function(afterEval,request,response,result,responseHead,handleRequest,flushFunction,flushResponse){
	this.afterEval = afterEval;
	this.request = request;
	this.response = response;
	this.result = result;
	this.responseHead = responseHead;
	this.handleRequest = handleRequest;
	this.flushFunction = flushFunction;
	this.flushResponse = flushResponse;
};

commands.prototype.write = function(text){
	this.afterEval.push(text);
};

commands.prototype.writeEscapedText = function(text){
	this.afterEval.push(unescape(text));
};

commands.prototype.forward = function(resource){
	this.flushFunction = this.handleRequest(this.request,this.response,this.resource,this.result.sessionId);
	this.flushResponse = false;
};

commands.prototype.sendRedirect = function(url){
	this.responseHead.status = 301;
	this.responseHead.headers["location"] = url;
};

exports.getCommands = function(afterEval,request,response,result,responseHead,handleRequest,flushFunction,flushResponse){
	return new commands(afterEval,request,response,result,responseHead,handleRequest,flushFunction,flushResponse);
};

redpajama_set_name: RedPajamaGithub


text:
package collins.graphs

import models.{PageParams, SortDirection}
import collins.solr.{CollinsQueryParser, AssetSearchQuery, AssetDocType}

import play.api.Logger
import com.google.common.cache.CacheLoader

case class MetricsQuery(query: String, metrics: Set[String])
case class MetricsCacheLoader() extends CacheLoader[MetricsQuery, Set[String]] {

  private[this] val logger = Logger("collins.graphs.MetricsCacheLoader")

  override def load(metricsQuery: MetricsQuery): Set[String] = {
    val MetricsQuery(query, metrics) = metricsQuery
    val hasMatch = try {
      solrQueryMatches(query)
    } catch {
      case e =>
        logger.error("Error querying solr for %s".format(query), e)
        false
    }
    if (hasMatch) {
      metrics
    } else {
      Set()
    }
  }

  protected def solrQueryMatches(query: String): Boolean = {
    CollinsQueryParser(List(AssetDocType))
      .parseQuery(query)
      .right
      .flatMap(_.typeCheck)
      .fold[Boolean](
        err => {
          logger.warn("Error in type check: %s".format(err))
          false
        },
        expr => {
          val cq = AssetSearchQuery(expr, PageParams(0, 1, SortDirection.SortAsc, "TAG"))
          cq.getPage().fold(
            err => {
              logger.warn("Error executing CQL query: %s".format(err))
              false
            },
            page => if (page.size > 0) {
              logger.debug("Query (%s) had results".format(query))
              true
            } else {
              logger.debug("Query (%s) had no results".format(query))
              false
            }
          )
        }
      )
  }

}


text:
"""
Build state operations

Copyright (c) 2012-2013 Heikki Nousiainen, F-Secure
See LICENSE for details
"""

import json

class Client(object):
    """ client class for buid state operations """
    def __init__(self, parent):
        self.parent = parent

    def put(self, job_id, build_id, state):
        """ update state """
        try:
            response = self.parent.rest.do_build_request('PUT',
                                                         job_id,
                                                         build_id,
                                                         'state',
                                                         data=json.dumps(state))
        except:
            self.parent.log.exception('Failed to update build state %s/%s', job_id, build_id)
            return None

        if response.status != 200:
            self.parent.log.error('Updating build state %s/%s failed with HTTP code %d', job_id, build_id, response.status)
            return None

        try:
            return json.loads(response.read())
        except (TypeError, ValueError):
            self.parent.log.exception('Failed to decode reply to update build state')
            return None

    def get(self, job_id, build_id):
        """ get state """
        try:
            response = self.parent.rest.do_build_request('GET',
                                                         job_id,
                                                         build_id,
                                                         'state')
        except:
            self.parent.log.exception('Failed to get build state for %s', job_id)
            return None

        if response.status != 200:
            self.parent.log.error('Get build state %s failed with HTTP code %d', job_id, response.status)
            return None

        try:
            return json.loads(response.read())
        except (TypeError, ValueError):
            self.parent.log.exception('Failed to decode reply to get build state')
            return None


text:
package net.sourceforge.myvd.test.util;

import java.io.*;
import java.util.HashMap;

import com.novell.ldap.LDAPConnection;
import com.novell.ldap.LDAPException;
import com.novell.ldap.LDAPLocalException;
import com.novell.ldap.LDAPMessage;
import com.novell.ldap.LDAPSearchResult;
import com.novell.ldap.LDAPSearchResults;
import com.novell.ldap.util.LDIFReader;

public class StartOpenLDAP {

	static HashMap<Integer,StartOpenLDAP> servers = new HashMap<Integer,StartOpenLDAP>();

	Process process;
	int port;

	private String adminDN;

	private String adminPass;

	private String fullPath;

	public void reloadAllData() throws Exception {

		LDAPConnection con = new LDAPConnection();
		con.connect("127.0.0.1", this.port);
		con.bind(this.adminDN, this.adminPass);
		LDIFReader reader = new LDIFReader(new FileInputStream(fullPath + "/data.ldif"));

		LDAPMessage msg = reader.readMessage();
		this.deleteNode(((LDAPSearchResult) msg).getEntry().getDN(), con,true);
		con.disconnect();

		this.loadLDIF(fullPath,adminDN,adminPass,port,true);
	}

	void deleteNode(String dn,LDAPConnection con,boolean childrenOnly) throws Exception {
		LDAPSearchResults children = con.search(dn, 1, "(objectClass=*)", new String[]{"1.1"}, false);
		while (children.hasMore()) {
			deleteNode(children.next().getDN(),con,false);
		}
		System.err.println("Deleting " + dn);

		if (!childrenOnly) {
			con.delete(dn);
		}

	}

	public void stopServer() {
		if (this.process != null) {
			this.process.destroy();
		}

		for (int i=0,m=100;i<m;i++) {
			try {
				LDAPConnection con = new LDAPConnection();
				con.connect("127.0.0.1",port);
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {

				}
			} catch (LDAPException e) {
				servers.remove(port);
				break;
			}
		}
	}

	private void clearData(String path) {
		String dataPath = path + "/data";
		File dir = new File(dataPath);
		if (dir.exists()) {
			File[] files = dir.listFiles();

			if (files != null) {
				for (int i=0,m=files.length;i<m;i++) {
					files[i].delete();
				}
			}
		} else {
			dir.mkdir();
		}

	}

	private void loadLDIF(String path,String adminDN,String adminPass,int port, boolean skipFirst) throws LDAPException, FileNotFoundException, IOException {
		try {
			this.port = port;
			LDAPConnection con = new LDAPConnection();
			con.connect("localhost",port);
			con.bind(3,adminDN,adminPass.getBytes());

			//System.out.println(path + "/data.ldif");

			LDIFReader reader = new LDIFReader(new FileInputStream(path + "/data.ldif"));

			LDAPMessage msg;

			if (skipFirst) {
				reader.readMessage();
			}

			while ((msg = reader.readMessage()) != null) {
				System.err.println("Msg : " + msg);
				con.add(((LDAPSearchResult) msg).getEntry());
			}

			con.disconnect();
		} catch (LDAPLocalException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (LDAPException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public boolean startServer(String fullPath,int port,String adminDN,String adminPass) throws IOException,Exception {
		return this.startServer(fullPath, port, adminDN, adminPass,0);
	}

	public boolean startServer(String fullPath,int port,String adminDN,String adminPass,int sslPort) throws IOException,Exception {

		this.adminDN = adminDN;
		this.adminPass = adminPass;
		this.fullPath = fullPath;

		LDAPConnection con = new LDAPConnection();
		try {
			con.connect("127.0.0.1",port);
			con.disconnect();

			for (int i=0;i<10;i++) {
				Thread.sleep(5000);

				try {
					con.connect("127.0.0.1",port);
					con.disconnect();
				} catch (Exception e) {
					throw e;
				}
			}

			if (! servers.containsKey(port)) {
				throw new Exception("Server on port " + port + "not stopped");
			} else {
				servers.get(port).stopServer();
			}
		} catch (LDAPException e) {

		} catch (Exception e) {
			throw e;
		}

		clearData(fullPath);
		this.createTestConf(fullPath);
		String exec = System.getenv("SLAPD_PATH") + "/slapd -d 1 -h 'ldap://:" + port + "/" + (sslPort > 0 ? " ldaps://:" + sslPort + "/" : "") + "' -f " + fullPath + "/slapd-gen.conf";
		String[] execa = new String[] {System.getenv("SLAPD_PATH") + "/slapd","-d","1","-h","ldap://:" + port + "/" + (sslPort > 0 ? " ldaps://:" + sslPort + "/" : ""),"-f",fullPath + "/slapd-gen.conf"};

		System.out.println(exec);
		process = Runtime.getRuntime().exec(execa);

		boolean debug = Boolean.valueOf(System.getenv("DEBUG_SERVER"));

		StreamReader reader = new StreamReader(process.getInputStream(), debug);
		StreamReader errReader = new StreamReader(process.getErrorStream(), debug);

		reader.start();
		errReader.start();

		for (int i=0,m=10;i<m;i++) {
			con = new LDAPConnection();
			try {
				//System.out.println("Try : " + i);
				con.connect("127.0.0.1",port);

				con.disconnect();

				if (sslPort > 0) {
					con.connect("127.0.0.1", sslPort);
					con.disconnect();
				}

				this.loadLDIF(fullPath,adminDN,adminPass,port,false);
				servers.put(port, this);
				return true;
			} catch (LDAPException e) {
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e1) {
					//do nothing
				}
			}
		}

		return false;
	}

	private void createTestConf(String fullPath) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(fullPath + "/slapd.conf")));

		StringBuffer buf = new StringBuffer();

		String line;

		while ((line = in.readLine()) != null) {
			buf.append(line).append('\n');
		}

		String tmpDir = System.getenv("TMP_DIR");
		if (tmpDir != null && ! tmpDir.isEmpty()) {
			this.clearData(tmpDir);
		}

		String tmp = buf.toString().replaceAll("[%]PROJ_DIR[%]", System.getenv("PROJ_DIR"));
		tmp = tmp.replaceAll("[%]SCHEMA_DIR[%]", System.getenv("SCHEMA_DIR"));
		tmp = tmp.replaceAll("[%]TMP_DIR[%]", System.getenv("TMP_DIR"));

		PrintWriter out = new PrintWriter(new FileWriter(fullPath + "/slapd-gen.conf"));
		out.println("# GENERATED FILE - DO NOT EDIT");
		out.print(tmp);
		out.close();

	}

	public static final void main(String[] args) throws Exception {
		StartOpenLDAP start = new StartOpenLDAP();
		boolean isStarted = start.startServer(System.getenv("PROJ_DIR") + "/test/startopenldap",10983,"cn=admin,dc=domain,dc=com","manager");

		if (isStarted) {
			//System.out.println("Server started on 10983....");
			BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
			in.readLine();
			start.stopServer();
		}
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `Stream` trait in crate `std`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, Stream">

    <title>std::old_io::Stream - Rust</title>

    <link rel="stylesheet" type="text/css" href="../../main.css">

    <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">

std::<wbr>old_io

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Trait std::<wbr>old_io::<wbr>Stream<wbr>Unstable
            [-] [+]
        [src]

pub trait Stream: Reader + Writer { }

A Stream is a readable and a writable object. Data written is typically
received by the object which reads receive data from.

Implementors

impl<T: Reader + Writer> Stream for T

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).


text:
var contentWidth = 1248;
var maxContentWidth = 1248;
var minMarginSize = 100;

//Display Box Variables
//Smallest display box is 15% of the content width
var displayBoxWidth = 1248 * 0.15;
var boxGridWidth = 0;
var displayMarginSize = 1248 * 0.02;

//An array that holds references to displayBox objects in the order they appear on screen
var boxGrid = new Array();

//The absolute minimum size for the small display box.  After this, the boxes will stop resizing and re-arrange.
//The boxes are initially 8 across.  At 1000, the boxes will shift to 6 across.  At 800, the site will shift into mobile mode and severely reduce margin size
var minDisplayBoxWidth = 150;

//Window width and height
var wWidth = 0;
var wHeight = 0;

//Dark or Light text to be used
colorMode = 1;

sidebarToggle = 0;

//Before anything else happens, initialize display box image background sizes
$(document).ready(function () {
    $(".displayBoxBackContent").each(function () {
        $(this).attr("w", 0);
        $(this).attr("h", 0);
    });
});

//Once all page content has loaded
$(window).on("load", function () {
    //Make all resize calculations
    resize();

    //After resize and all elements are done moving around, make the page visible
    $("html").css("visibility", "visible");
    //Loop through all elements that animate in and check if they are on the page
    $('.animIn').each(function () {
        checkAnimation($(this));
    });

    //Position the header hover line
    headerLineReset();

    /*
     * EVENT BINDING
     */
    //Bind mouse events to display box buttons
    $(".dBoxButtonText").mouseenter(function () {
        //On mouse enter, call the button enter function
        buttonEnter($(this).parent());
    }).mouseleave(function () {
        //On mouse leave, call the button leave function
        buttonLeave($(this).parent());
    }).mouseup(function () {
        //On a click, set the display box to active
        setDBActive($(this).parent());
    });

    //Bind mouse events to display boxes
    $(".displayBox").mouseleave(function () {
        //When the mouse leaves an active display box, make it inactive
        if ($(this).hasClass("active")) {
            setDBInactive($(this));
        }
        //When the mouse leaves a display box without a description, set it's link to inactive
        var bWrap = $(this).children(".dBoxButtonWrapper");
        if (bWrap.hasClass("linkActive")) {
            bWrap.removeClass("linkActive");
            $(this).children(".dBoxLink").children(".linkSpan").css({ "visibility": "hidden" });
            buttonLeave($(this).children(".dBoxButtonWrapper"));
        }
    }).mouseup(function () {
        //Make display boxes work like buttons on mobile
        if (window.mobilecheck()) {
            setDBActive($(this).children(".dBoxButtonWrapper"));
            if ($(this).children(".dBoxButtonWrapper").hasClass("linkActive")) {
                $(this).children(".dBoxLink").children(".linkSpan").css({ "visibility": "visible" });
            }
        }
    });

    //Social Media display boxes
    $(".socialMedia").mouseenter(function () {
        $(this).children(".dBoxLink").children(".socialLink").css({ "visibility": "visible" });
        //Zoom the background
        var boxW = parseInt($(this).width()) + 40;
        var boxH = parseInt($(this).height()) + 40;
        utils.fitContent($(this).children(".displayBoxBackground").children(".displayBoxBackContent"), boxW, boxH);
    }).mouseleave(function () {
        $(this).children(".dBoxLink").children(".socialLink").css({ "visibility": "hidden" });
        //Reset the background
        var boxW = parseInt($(this).width());
        var boxH = parseInt($(this).height());
        utils.fitContent($(this).children(".displayBoxBackground").children(".displayBoxBackContent"), boxW, boxH);
    });

    //Header links
    $(".headerLinkCell").mouseenter(function () {
        headerLineTo($(this));
    }).mouseleave(function () {
        headerLineReset();
    });

    //When the hamburger button is clicked
    $("#mobileHeaderButton").mouseup(function () {
        headerActivateSidebar();
    });
    $("#mobileSidebar").mouseleave(function () {
        headerActivateSidebar();
    });

    //Content Item Highlight animations
    $(".cIHItem").mouseenter(function () {
        cIHItemEnter($(this));
    }).mouseleave(function () {
        cIHItemLeave($(this));
    });

    //Set the copyright text
    var curDate = new Date()
    $('.copyright').replaceWith('
Copyright © ' + curDate.getFullYear() + ' Daniel Timko
');
});

window.onresize = function () {
    if (window.mobilecheck() == false) {
        resize();
    }
};

$(window).scroll(function () {
    $('.animIn').each(function () {
        checkAnimation($(this));
    });
    //Scroll the header when the scroll distance reaches 30.  The header is transparent
    headerScroll(30, 0);
});

/**
 * Check if an animIn object should animate
 */
function checkAnimation(elem) {
    //If the element has already animated, do nothing
    if (elem.hasClass('start')) {
        return;
    }
    //If the element is in the view, begin css animation
    if (isElementInView(elem)) {
        elem.addClass('start');
    }
}
/**
 * Check if a DOM element is visible
 */
function isElementInView(elem) {
    //Get the scroll position of the page
    var scrollElem = ((navigator.userAgent.toLocaleLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
    var viewTop = $(scrollElem).scrollTop();
    var viewBottom = viewTop + wHeight;

    //Get the position of the element on the page
    var elemTop = Math.round(elem.offset().top);
    var elemBottom = elemTop + elem.height();

    return ((elemTop < viewBottom) && (elemBottom > viewTop));
}

/**
 * The function called on window resize.  It makes sure that everything works properly with the new dynamic window sizing
 */
function resize() {
    //Get the window size
    wWidth = $(window).width();
    wHeight = $(window).height();

    //Find a proper size for the margins
    //If the min margin size plus the max content width is still smaller than the window width
    if (2 * minMarginSize + maxContentWidth < wWidth) {
        //Make the margins equal, and set the content width to it's max
        var marginSize = 0.5 * (wWidth - maxContentWidth);
        contentWidth = maxContentWidth;
        $('.mainContent').css("margin-left", marginSize).css("margin-right", marginSize);
        $('.mainContent').css("width", maxContentWidth);

    //Else, the default-sized content box won't fit in the window.  Resize it.
    } else {
        $('.mainContent').css("margin-left", minMarginSize).css("margin-right", minMarginSize);
        //Get the width of the middle box
        contentWidth = wWidth - 2 * minMarginSize;
        $('.mainContent').css("width", contentWidth);
    }

    //Position the header
    $("#header").css("width", wWidth);
    headerResize();
    headerLineReset();
    headerScroll(40, 0);

    //Resize content elements
    cElemResize();

    //Resize and align the display boxes
    alignBoxes();

	//Fix display box inner proportions
    $(".displayBoxBackContent").each(function () {
        //Get the box width and height
        var boxW = $(this).parent().parent().width();
        var boxH = $(this).parent().parent().height();

        utils.fitContent($(this), boxW, boxH);
    });

    //Re-format box descriptions
    $(".dBoxDescription").each(function () {
        //Position the display box description
        var boxH = $(this).parent().height();
        //Set the top position of the description to off-screen
        $(this).css("top", boxH);
    });

    /*
        Position the buttons properly
    */
    buttonResize(colorMode);
}

/**
 * Set a display box to active, animate the description
 */
function setDBActive(button) {
    button.addClass("active");
    var activeDisplayBox = button.parent();
    var activeDBDesc = activeDisplayBox.children(".dBoxDescription");
    activeDisplayBox.addClass("active");

    //If the display box has a description
    if (activeDBDesc.length > 0) {
        //Set the link to visible
        activeDisplayBox.children(".dBoxLink").children(".linkSpan").css({ "visibility": "visible" });

        //Active positioning
        var topDescMargin = parseInt(activeDisplayBox.height()) * 0.45;
        var topButtonMargin = (topDescMargin / 4) - (button.height() / 2);

        button.stop().animate({ "top": topButtonMargin }, 300);
        //Animate button children elements so the button becomes a title
        var leftLine = button.children(".dBoxButtonWLine5").children(".dBBHWLineLL");
        var rightLine = button.children(".dBoxButtonWLine3").children(".dBBHWLineRR");
        var text = button.children(".dBoxButtonText").children("span");
        var bottomLLine = button.children(".dBoxButtonWLine4").children(".dBBHWLineBL");
        var bottomRLine = button.children(".dBoxButtonWLine4").children(".dBBHWLineBR");
        //Set the opacity of all white line backgrounds to zero:
        button.children(".dBoxButtonWLine1").css("background-color", "rgba(255, 255, 255, 0)");
        button.children(".dBoxButtonWLine2").css("background-color", "rgba(255, 255, 255, 0)");
        button.children(".dBoxButtonWLine3").css("background-color", "rgba(255, 255, 255, 0)");
        button.children(".dBoxButtonWLine4").css("background-color", "rgba(255, 255, 255, 0)");
        button.children(".dBoxButtonWLine5").css("background-color", "rgba(255, 255, 255, 0)");
        //Animate the actual opacity of the top red line to zero
        button.children(".dBoxButtonRLine").stop().animate({ "opacity": 0 }, 300);
        //Animate the side red lines down
        leftLine.stop().animate({ "top": leftLine.height() }, 300);
        rightLine.stop().animate({ "top": rightLine.height() }, 300);

        //Animate the text down by a small margin
        text.stop().animate({ "top": text.parent().height() - (text.height() + 5) }, 300);

        //Animate the bottom red lines to fit as a text underline
        bottomLLine.stop().animate({ "left": text.css("left") });
        bottomRLine.stop().animate({ "left": parseInt(bottomRLine.parent().width()) / 2 - parseInt(text.css("left")) });

        activeDBDesc.stop().animate({ "top": topDescMargin }, 300);

        //Zoom in with 20 pixel margins
        var activeDBBack = activeDisplayBox.children(".displayBoxBackground");
        var boxW = activeDisplayBox.width() + 40;
        var boxH = activeDisplayBox.height() + 40;
        utils.fitContent(activeDBBack.children(".displayBoxBackContent"), boxW, boxH);

        //Else, there is no description
    } else {
        button.removeClass("active");
        //Set the button to active link.  This is only for mobile purposes.  Link forewarding is handled mostly by mouse move events.
        buttonEnter(button);
    }
}

/**
 * Set a display box to inactive and reset it's CSS
 */
function setDBInactive(curDisplayBox) {
    curDisplayBox.removeClass("active");

    var curButton = curDisplayBox.children(".dBoxButtonWrapper");
    curButton.removeClass("active");

    var activeDBDesc = curDisplayBox.children(".dBoxDescription");

    //If there is a description
    if (activeDBDesc.length > 0) {
        //Set the link to invisible
        curDisplayBox.children(".dBoxLink").children(".linkSpan").css({ "visibility": "hidden" });

        var topButtonMargin = (parseInt(curDisplayBox.height()) - parseInt(curButton.height())) / 2;
        curButton.stop().animate({ "top": topButtonMargin }, 300);

        //Reset the title to become a button again
        var leftLine = curButton.children(".dBoxButtonWLine5").children(".dBBHWLineLL");
        var rightLine = curButton.children(".dBoxButtonWLine3").children(".dBBHWLineRR");
        var text = curButton.children(".dBoxButtonText").children("span");
        var bottomLLine = curButton.children(".dBoxButtonWLine4").children(".dBBHWLineBL");
        var bottomRLine = curButton.children(".dBoxButtonWLine4").children(".dBBHWLineBR");
        //Animate the bottom red lines to fit as a text underline
        bottomLLine.stop().animate({ "left": 0 }, 150);
        bottomRLine.stop().animate({ "left": parseInt(bottomRLine.parent().width()) / 2 }, 150);
        //Animate the side red lines up
        leftLine.stop().animate({ "top": 0 }, 150);
        rightLine.stop().animate({ "top": 0 }, 150);
        //Animate the opacity of the red line back to 100%
        setTimeout(function () {
            curButton.children(".dBoxButtonRLine").stop().animate({ "opacity": 100 }, 150);
        }, 150);
        //Set the text back to its original location
        text.stop().animate({ "top": parseInt(text.parent().height()) / 2 - parseInt(text.css("font-size")) / 1.5 }, 300);
        setTimeout(function () {
            //Fix the white line border opacity
            curButton.children(".dBoxButtonWLine1").css("background-color", "#fcfcfc");
            curButton.children(".dBoxButtonWLine2").css("background-color", "#fcfcfc");
            curButton.children(".dBoxButtonWLine3").css("background-color", "#fcfcfc");
            curButton.children(".dBoxButtonWLine4").css("background-color", "#fcfcfc");
            curButton.children(".dBoxButtonWLine5").css("background-color", "#fcfcfc");

            buttonLeave(curDisplayBox.children(".dBoxButtonWrapper"));
        }, 200);

        activeDBDesc.stop().animate({ "top": parseInt(curDisplayBox.height()) }, 300);

        //Zoom to normal
        var activeDBBack = curDisplayBox.children(".displayBoxBackground");
        var boxW = curDisplayBox.width();
        var boxH = curDisplayBox.height();
        utils.fitContent(activeDBBack.children(".displayBoxBackContent"), boxW, boxH);
    }
}

/**
 * Get a 2d region of a parent 2d array
 */
function GetRegion(x, y, areaWidth, areaHeight) {
    if (y+areaHeight > boxGrid.length || x+areaWidth > boxGrid[0].length) {
        return null;
    }
    var newGrid = new Array(areaHeight);
    for (var o=0; o<newGrid.length; o++) {
        newGrid[o] = new Array(areaWidth);
    }

    for (var h = 0; h < newGrid.length; h++) {
        for (var w = 0; w < newGrid[h].length; w++) {
            newGrid[h][w] = boxGrid[y+h][x+w];
        }
    }
    return newGrid;
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<example>
    <description>
        <![CDATA[This is a more advanced example that shows how you can combine paging and Template.]]>
    </description>
</example>


text:
using System;
using System.Text;

using GostCryptography.Properties;

namespace GostCryptography.Asn1.Ber
{
	[Serializable]
	class Asn1UtcTime : Asn1Time
	{
		public static readonly Asn1Tag Tag = new Asn1Tag(0, 0, UtcTimeTypeCode);

		public Asn1UtcTime()
			: base(UtcTimeTypeCode, false)
		{
		}

		public Asn1UtcTime(bool useDerRules)
			: base(UtcTimeTypeCode, useDerRules)
		{
		}

		public Asn1UtcTime(string data)
			: base(data, UtcTimeTypeCode, false)
		{
		}

		public Asn1UtcTime(string data, bool useDerRules)
			: base(data, UtcTimeTypeCode, useDerRules)
		{
		}

		public override string Fraction
		{
			get
			{
				return "";
			}
			set
			{
				SecFraction = "";

				throw ExceptionUtility.CryptographicException(Resources.Asn1FractionNotSupportedForUtcTime);
			}
		}

		public override int Year
		{
			get
			{
				if (!Parsed)
				{
					ParseString(Value);
				}

				return YearValue;
			}
			set
			{
				if (value < 0)
				{
					throw ExceptionUtility.CryptographicException(Resources.Asn1InvalidYearValue, YearValue);
				}

				if (value < 100)
				{
					if (value >= 50)
					{
						Year = value + 0x76c;
					}
					else
					{
						Year = value + 0x7d0;
					}
				}

				Year = value;
			}
		}

		public override void Clear()
		{
			Clear();
			HourValue = MinuteValue = -1;
			UtcFlag = true;
		}

		public override int CompareTo(object obj)
		{
			return base.CompareTo(obj);
		}

		protected override bool CompileString()
		{
			Value = "";

			if (((YearValue < 0) || (DayValue <= 0)) || (((MonthValue <= 0) || (HourValue < 0)) || (MinuteValue < 0)))
			{
				return false;
			}

			if (StringBuffer == null)
			{
				StringBuffer = new StringBuilder();
			}
			else
			{
				StringBuffer.Length = 0;
			}

			if ((DerRules || UtcFlag) && ((DiffHourValue != 0) || (DiffMinValue != 0)))
			{
				var time = GetTime();
				time.AddMinutes(-DiffMinValue);
				time.AddHours(-DiffHourValue);

				PutInteger(2, time.Year);
				PutInteger(2, time.Month);
				PutInteger(2, time.Day);
				PutInteger(2, time.Hour);
				PutInteger(2, time.Minute);
			}
			else
			{
				PutInteger(2, YearValue);
				PutInteger(2, MonthValue);
				PutInteger(2, DayValue);
				PutInteger(2, HourValue);
				PutInteger(2, MinuteValue);
			}

			PutInteger(2, SecondValue);

			if (DerRules || UtcFlag)
			{
				StringBuffer.Append('Z');
			}
			else if ((DiffHourValue != 0) || (DiffMinValue != 0))
			{
				StringBuffer.Append((DiffHourValue > 0) ? '+' : '-');
				PutInteger(2, Math.Abs(DiffHourValue));
				PutInteger(2, Math.Abs(DiffMinValue));
			}

			Value = StringBuffer.ToString();

			return true;
		}

		public override void Decode(Asn1BerDecodeBuffer buffer, bool explicitTagging, int implicitLength)
		{
			Decode(buffer, explicitTagging, implicitLength, Tag);
		}

		public override int Encode(Asn1BerEncodeBuffer buffer, bool explicitTagging)
		{
			return Encode(buffer, explicitTagging, Tag);
		}

		public override void Encode(Asn1BerOutputStream outs, bool explicitTagging)
		{
			Encode(outs, explicitTagging, Tag);
		}

		protected override void Init()
		{
			Init();
			HourValue = MinuteValue = -1;
			UtcFlag = true;
		}

		public override void ParseString(string data)
		{
			if (data == null)
			{
				throw ExceptionUtility.ArgumentNull("data");
			}

			Clear();

			var off = new IntHolder(0);

			try
			{
				YearValue = ParseInt(data, off, 2);
				MonthValue = ParseInt(data, off, 2);
				DayValue = ParseInt(data, off, 2);

				if (YearValue < 0)
				{
					throw ExceptionUtility.CryptographicException(Resources.Asn1InvalidYearValue, YearValue);
				}

				if (YearValue < 100)
				{
					if (YearValue > 70)
					{
						YearValue += 0x76c;
					}
					else
					{
						YearValue += 0x7d0;
					}
				}

				if ((MonthValue < 1) || (MonthValue > 12))
				{
					throw ExceptionUtility.CryptographicException(Resources.Asn1InvalidMonthValue, MonthValue);
				}

				var num = DaysInMonth[MonthValue];

				if (((MonthValue == 2) && ((YearValue % 4) == 0)) && (((YearValue % 100) != 0) || ((YearValue % 400) == 0)))
				{
					num++;
				}

				if ((DayValue < 1) || (DayValue > num))
				{
					throw ExceptionUtility.CryptographicException(Resources.Asn1InvalidDayValue, DayValue);
				}

				var num2 = 0;

				if (!char.IsDigit(CharAt(data, off.Value)))
				{
					throw ExceptionUtility.CryptographicException(Resources.Asn1HoursExpected);
				}

				HourValue = ParseInt(data, off, 2);
				num2++;

				if (!char.IsDigit(CharAt(data, off.Value)))
				{
					throw ExceptionUtility.CryptographicException(Resources.Asn1MinutesExpected);
				}

				MinuteValue = ParseInt(data, off, 2);
				num2++;

				if (char.IsDigit(CharAt(data, off.Value)))
				{
					SecondValue = ParseInt(data, off, 2);
					num2++;
				}

				if ((num2 >= 2) && ((HourValue < 0) || (HourValue > UtcTimeTypeCode)))
				{
					throw ExceptionUtility.CryptographicException(Resources.Asn1InvalidHourValue, HourValue);
				}

				if ((num2 >= 2) && ((MinuteValue < 0) || (MinuteValue > 0x3b)))
				{
					throw ExceptionUtility.CryptographicException(Resources.Asn1InvalidMinuteValue, MinuteValue);
				}

				if ((num2 == 3) && ((SecondValue < 0) || (SecondValue > 0x3b)))
				{
					throw ExceptionUtility.CryptographicException(Resources.Asn1InvalidSecondValue, SecondValue);
				}

				CharAt(data, off.Value);

				if (CharAt(data, off.Value) == 'Z')
				{
					off.Value++;
					UtcFlag = true;

					if (off.Value != data.Length)
					{
						throw ExceptionUtility.CryptographicException(Resources.Asn1UnexpectedValuesAtEndOfString);
					}
				}
				else
				{
					if (DerRules)
					{
						throw ExceptionUtility.CryptographicException(Resources.Asn1UnexpectedZoneOffset);
					}

					UtcFlag = false;
					var ch = CharAt(data, off.Value);

					switch (ch)
					{
						case '-':
						case '+':
							off.Value++;

							if (!char.IsDigit(CharAt(data, off.Value)))
							{
								throw ExceptionUtility.CryptographicException(Resources.Asn1InvalidDiffHour);
							}

							DiffHourValue = ParseInt(data, off, 2);

							if (!char.IsDigit(CharAt(data, off.Value)))
							{
								throw ExceptionUtility.CryptographicException(Resources.Asn1InvalidDiffMinute);
							}

							DiffMinValue = ParseInt(data, off, 2);

							if ((DiffHourValue < 0) || (DiffHourValue > 12))
							{
								throw ExceptionUtility.CryptographicException(Resources.Asn1InvalidDiffHourValue, DiffHourValue);
							}

							if ((DiffMinValue < 0) || (DiffMinValue > 0x3b))
							{
								throw ExceptionUtility.CryptographicException(Resources.Asn1InvalidDiffMinuteValue, DiffMinValue);
							}

							if (ch == '-')
							{
								DiffHourValue = -DiffHourValue;
								DiffMinValue = -DiffMinValue;
							}
							break;
					}
				}

				Parsed = true;

				if (data != Value)
				{
					CompileString();
				}
			}
			catch (IndexOutOfRangeException)
			{
				throw ExceptionUtility.CryptographicException(Resources.Asn1InvalidDateFormat);
			}
			catch (FormatException)
			{
				throw ExceptionUtility.CryptographicException(Resources.Asn1InvalidNumberFormat);
			}
			catch (ArgumentException)
			{
				throw ExceptionUtility.CryptographicException(Resources.Asn1InvalidDateFormat);
			}
		}

		public override void SetTime(DateTime time)
		{
			Clear();
			YearValue = time.Year;
			MonthValue = time.Month;
			DayValue = time.Day;
			HourValue = time.Hour;
			MinuteValue = time.Minute;
			SecondValue = time.Second;
			SecFraction = "";
			DiffHourValue = DiffMinValue = 0;
			UtcFlag = true;
			CompileString();
		}
	}
}


text:
class WhoAction < SimpleAction

  def run
    user_nicks = Session.users.map do |user|
      user.nick + "\n"
    end
    Bot.say_as_private(Command.sender, user_nicks.join)
  end
end


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

package org.camunda.bpm.dmn.engine.impl.delegate;

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

import org.camunda.bpm.dmn.engine.DmnDecision;
import org.camunda.bpm.dmn.engine.delegate.DmnDecisionTableEvaluationEvent;
import org.camunda.bpm.dmn.engine.delegate.DmnEvaluatedDecisionRule;
import org.camunda.bpm.dmn.engine.delegate.DmnEvaluatedInput;
import org.camunda.bpm.engine.variable.value.TypedValue;

public class DmnDecisionTableEvaluationEventImpl implements DmnDecisionTableEvaluationEvent {

  protected DmnDecision decisionTable;
  protected List<DmnEvaluatedInput> inputs = new ArrayList<DmnEvaluatedInput>();
  protected List<DmnEvaluatedDecisionRule> matchingRules = new ArrayList<DmnEvaluatedDecisionRule>();
  protected String collectResultName;
  protected TypedValue collectResultValue;
  protected long executedDecisionElements;

  public DmnDecision getDecisionTable() {
    return decisionTable;
  }

  public void setDecisionTable(DmnDecision decisionTable) {
    this.decisionTable = decisionTable;
  }

  public List<DmnEvaluatedInput> getInputs() {
    return inputs;
  }

  public void setInputs(List<DmnEvaluatedInput> inputs) {
    this.inputs = inputs;
  }

  public List<DmnEvaluatedDecisionRule> getMatchingRules() {
    return matchingRules;
  }

  public void setMatchingRules(List<DmnEvaluatedDecisionRule> matchingRules) {
    this.matchingRules = matchingRules;
  }

  public String getCollectResultName() {
    return collectResultName;
  }

  public void setCollectResultName(String collectResultName) {
    this.collectResultName = collectResultName;
  }

  public TypedValue getCollectResultValue() {
    return collectResultValue;
  }

  public void setCollectResultValue(TypedValue collectResultValue) {
    this.collectResultValue = collectResultValue;
  }

  public long getExecutedDecisionElements() {
    return executedDecisionElements;
  }

  public void setExecutedDecisionElements(long executedDecisionElements) {
    this.executedDecisionElements = executedDecisionElements;
  }

  @Override
  public String toString() {
    return "DmnDecisionTableEvaluationEventImpl{" +
      "decisionTable=" + decisionTable +
      ", inputs=" + inputs +
      ", matchingRules=" + matchingRules +
      ", collectResultName='" + collectResultName + '\'' +
      ", collectResultValue=" + collectResultValue +
      ", executedDecisionElements=" + executedDecisionElements +
      '}';
  }

}


text:
<?php

namespace app\modules\user\models\frontend\form;

use app\modules\user\models\User;
use app\modules\user\Module;
use yii\base\InvalidParamException;
use yii\base\Model;
use Yii;

/**
 * Password reset form
 */
class PasswordResetForm extends Model
{
    public $password;

    /**
     * @var User
     */
    private $_user;

    /**
     * Creates a form model given a token.
     *
     * @param  string $token
     * @param  integer $timeout
     * @param  array $config name-value pairs that will be used to initialize the object properties
     * @throws \yii\base\InvalidParamException if token is empty or not valid
     */
    public function __construct($token, $timeout, $config = [])
    {
        if (empty($token) || !is_string($token)) {
            throw new InvalidParamException('Password reset token cannot be blank.');
        }
        $this->_user = User::findByPasswordResetToken($token, $timeout);
        if (!$this->_user) {
            throw new InvalidParamException('Wrong password reset token.');
        }
        parent::__construct($config);
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['password', 'required'],
            ['password', 'string', 'min' => 6],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'password' => Module::t('module', 'USER_NEW_PASSWORD'),
        ];
    }

    /**
     * Resets password.
     *
     * @return boolean if password was reset.
     */
    public function resetPassword()
    {
        $user = $this->_user;
        $user->setPassword($this->password);
        $user->removePasswordResetToken();

        return $user->save();
    }
}


text:
.root {
  display: flex;
  justify-content: space-between;
}

.compared_models_manager {
}

.dashboard_settings_container {
  display: flex;
}

.action_wrapper {
}

.action_container {
  display: grid;
  grid-template-columns: 45px 40px;
  margin-right: 10px;
  margin-bottom: 3px;
}

.dashboard_actione_label {
  font-size: 12px;
  color: var(--text-color3);
  margin-top: 10px;
}

.dashboard_action_link {
}

.experiment_runs_table_config_wrapper {
  display: flex;
  align-self: center;
  margin-right: 10px;
}


text:
import React, { HTMLProps } from 'react';
import { css, cx } from '@emotion/css';
import { GrafanaTheme } from '../../../data';
import { stylesFactory, useTheme } from '../../themes';

enum Orientation {
  Horizontal,
  Vertical,
}
type Spacing = 'none' | 'xs' | 'sm' | 'md' | 'lg';
type Justify = 'flex-start' | 'flex-end' | 'space-between' | 'center';
type Align = 'normal' | 'flex-start' | 'flex-end' | 'center';

export interface LayoutProps extends Omit<HTMLProps<HTMLDivElement>, 'align' | 'children' | 'wrap'> {
  children: React.ReactNode[] | React.ReactNode;
  orientation?: Orientation;
  spacing?: Spacing;
  justify?: Justify;
  align?: Align;
  width?: string;
  wrap?: boolean;
}

export interface ContainerProps {
  padding?: Spacing;
  margin?: Spacing;
  grow?: number;
  shrink?: number;
}

export const Layout: React.FC<LayoutProps> = ({
  children,
  orientation = Orientation.Horizontal,
  spacing = 'sm',
  justify = 'flex-start',
  align = 'normal',
  wrap = false,
  width = '100%',
  height = '100%',
  ...rest
}) => {
  const theme = useTheme();
  const styles = getStyles(theme, orientation, spacing, justify, align, wrap);
  return (

      {React.Children.toArray(children)
        .filter(Boolean)
        .map((child, index) => {
          return (

              {child}

          );
        })}

  );
};

export const HorizontalGroup: React.FC<Omit<LayoutProps, 'orientation'>> = ({
  children,
  spacing,
  justify,
  align = 'center',
  wrap,
  width,
  height,
}) => (
  <Layout
    spacing={spacing}
    justify={justify}
    orientation={Orientation.Horizontal}
    align={align}
    width={width}
    height={height}
    wrap={wrap}
  >
    {children}
  </Layout>
);
export const VerticalGroup: React.FC<Omit<LayoutProps, 'orientation' | 'wrap'>> = ({
  children,
  spacing,
  justify,
  align,
  width,
  height,
}) => (
  <Layout
    spacing={spacing}
    justify={justify}
    orientation={Orientation.Vertical}
    align={align}
    width={width}
    height={height}
  >
    {children}
  </Layout>
);

export const Container: React.FC<ContainerProps> = ({ children, padding, margin, grow, shrink }) => {
  const theme = useTheme();
  const styles = getContainerStyles(theme, padding, margin);
  return (

      {children}

  );
};

const getStyles = stylesFactory(
  (theme: GrafanaTheme, orientation: Orientation, spacing: Spacing, justify: Justify, align, wrap) => {
    const finalSpacing = spacing !== 'none' ? theme.spacing[spacing] : 0;
    // compensate for last row margin when wrapped, horizontal layout
    const marginCompensation =
      (orientation === Orientation.Horizontal && !wrap) || orientation === Orientation.Vertical
        ? 0
        : `-${finalSpacing}`;

    const label = orientation === Orientation.Vertical ? 'vertical-group' : 'horizontal-group';

    return {
      layout: css`
        label: ${label};
        display: flex;
        flex-direction: ${orientation === Orientation.Vertical ? 'column' : 'row'};
        flex-wrap: ${wrap ? 'wrap' : 'nowrap'};
        justify-content: ${justify};
        align-items: ${align};
        height: 100%;
        max-width: 100%;
        // compensate for last row margin when wrapped, horizontal layout
        margin-bottom: ${marginCompensation};
      `,
      childWrapper: css`
        label: layoutChildrenWrapper;
        margin-bottom: ${orientation === Orientation.Horizontal && !wrap ? 0 : finalSpacing};
        margin-right: ${orientation === Orientation.Horizontal ? finalSpacing : 0};
        display: flex;
        align-items: ${align};

        &:last-child {
          margin-bottom: ${orientation === Orientation.Vertical && 0};
          margin-right: ${orientation === Orientation.Horizontal && 0};
        }
      `,
    };
  }
);

const getContainerStyles = stylesFactory((theme: GrafanaTheme, padding?: Spacing, margin?: Spacing) => {
  const paddingSize = (padding && padding !== 'none' && theme.spacing[padding]) || 0;
  const marginSize = (margin && margin !== 'none' && theme.spacing[margin]) || 0;
  return {
    wrapper: css`
      label: container;
      margin: ${marginSize};
      padding: ${paddingSize};
    `,
  };
});


text:
require 'delegate'

class Roda
  class Component
    class DOM
      attr_accessor :dom, :raw_html

      def initialize html
        @raw_html = html

        if server?
          @dom = raw_html.is_a?(String) ? Component::HTML(raw_html.dup): raw_html
        else
          @dom = raw_html.is_a?(String) ? Element[raw_html.dup] : raw_html
        end

        # super @dom
      end

      def find string, &block
        if client?
          node = DOM.new dom.find(string)
        elsif server?
          if block_given?
            node = DOM.new dom.css(string)
          else
            node = DOM.new dom.at(string)
          end
        end

        if block_given?
          node.each_with_index do |n, i|
            block.call DOM.new(n), i
          end
        end

        node
      end

      if RUBY_ENGINE == 'ruby'
        def data key = false, value = false
          d = Hash[node.xpath("@*[starts-with(name(), 'data-')]").map{|a| [a.name, a.value]}]

          if !key
            d
          elsif key && !value
            d[key]
          else
            node["data-#{key}"] = value
          end
        end

        def val value
          node.content = value
        end

        def add_class classes
          classes = (classes || '').split ' ' unless classes.is_a? Array
          new_classes =  ((node.attr('class') || '').split(' ') << classes).uniq.join(' ')
          node['class'] = new_classes
        end

        def remove_class classes
          classes = (classes || '').split ' ' unless classes.is_a? Array
          (node.attr('class') || '').split(' ').reject { |n| n =~ /active|asc|desc/i }.join(' ')
        end

        def attr key, value = false
          if value
            value = value.join ' ' if value.is_a? Array
            node[key] = value
          else
            super key
          end
        end
      end

      def html= content
        if server?
          node.inner_html = content
        else
          content = content.dom if content.is_a? Roda::Component::DOM
          node.html content
        end

        node
      end

      if RUBY_ENGINE == 'opal'
        # make it supply the jquery element so it will use that as it doesn't
        # know how to handle the DOM element.
        %w(append prepend replace_with after).each do |meth|
          define_method meth do |obj|
            obj = obj.dom if obj.is_a? Roda::Component::DOM
            super obj
          end
        end
      end

      def html content = false
        if !content
          if server?
            node.inner_html
          else
            node ? node.html : dom.html
          end
        else
          self.html = content
        end
      end

      def node
        @node || dom
      end

      # This allows you to use all the nokogiri or opal jquery methods if a
      # global one isn't set
      def method_missing method, *args, &block
        # respond_to?(symbol, include_all=false)
        if dom.respond_to? method, true
          dom.send method, *args, &block
        else
          super
        end
      end

      private

      def server? &block
        RUBY_ENGINE == 'ruby'
      end
      alias :server :server?

      def client?
        RUBY_ENGINE == 'opal'
      end
      alias :client :client?
    end
  end
end


text:
import argparse
import pandas as pd
import numpy as np

import os
import glob

import wikipediaapi

import pickle

LANG = {
        'italy': 'it',
        'germany': 'de',
        'belgium': 'nl',
        'netherlands': 'nl'
    }

INFLUENZA = {
        'it': 'Influenza',
        'de': 'Influenza',
        'nl': 'Griep'
    }

def save_obj(obj, name ):
    with open(name + '.pkl', 'wb') as f:
        pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)

def load_obj(name):
    with open(name, 'rb') as f:
        return pickle.load(f)

def get_wikipedia_page_language(wiki_page, language="en", start_lang="it"):

    wiki_wiki = wikipediaapi.Wikipedia(start_lang)
    page = wiki_wiki.page(wiki_page)

    if language in page.langlinks:
        langlinks = page.langlinks[language]
        return langlinks.title
    else:
        return "NE"

def get_distance_from_influenza(wiki_page, wiki_graph):
    if wiki_page in wiki_graph:
        return wiki_graph[wiki_page]
    else:
        return "> 3"

def inspect_wikipedia_tree(language="it", depth=2):

    wiki_wiki = wikipediaapi.Wikipedia(language)

    visited_pages = [(INFLUENZA[language], 1)]
    discovered_pages = {INFLUENZA[language]: 1}

    while(len(visited_pages) != 0):

        tmp_page, counter = visited_pages.pop()

        if counter >= depth:
            continue

        if ":" in tmp_page:
            continue

        tmp_links = wiki_wiki.page(tmp_page).links

        for l in tmp_links.keys():
            if not l in discovered_pages:
                if counter < depth:
                    discovered_pages[l] = counter
                    visited_pages.append((l, counter+1))
            else:
                counter_already = discovered_pages[l]
                if counter_already > counter:
                    discovered_pages[l] = counter
                    visited_pages.append([l, counter])

        print(len(discovered_pages), len(visited_pages))

    save_obj(discovered_pages, "{}-{}-influenza".format(language, depth))
    return discovered_pages

def get_results_filename(basepath, country):
    files = [f for f in glob.glob(basepath + "/*_information_{}.csv".format(country), recursive=True)]
    season_years = os.path.basename(files[0]).split("_")[0]
    return season_years

def get_keywords_prefix(model):
    """
    Return the correct keyword's file prefix given the model
    :param model: name of the model
    :return: keyword's file prefix
    """
    if model == "cyclerank" or model == "cyclerank_pageviews":
        return "keywords_cyclerank"
    elif model == "pagerank" or model == "pagerank_pageviews":
        return "keywords_pagerank"
    else:
        return "keywords"

def convert_naming(model):
    if model == "cyclerank":
        return ("a", "b", "c")
    elif model == "cyclerank_pageviews":
        return ("d", "e", "f")
    elif model == "pagerank":
        return ("g", "h", "i")
    elif model == "pagerank_pageviews":
        return ("l", "m", "n")
    elif model == "pageviews":
        return ("o", "p", "q")
    else:
        return ("r", "s", "t")

def get_intersection_dataframe(original_data, percentage=False):

    # Compute the intersection between all of them
    intersection_df = []
    for first in original_data:
        partial_value = [convert_naming(first)]
        for second in original_data:
            intersection_value = set.intersection(set(original_data[first].page_name),
                                                  set(original_data[second].page_name))
            if percentage:
                partial_value.append((len(intersection_value)/len(original_data[first])))
            else:
                partial_value.append(len(intersection_value))
        intersection_df.append(partial_value)

    # Convert the intersection into a dataframe
    intersection_columns = ["index"] + [convert_naming(x) for x in list(original_data.keys())]
    intersection_df = pd.DataFrame(intersection_df, columns=intersection_columns)
    intersection_df = intersection_df.set_index("index")
    return intersection_df

def get_min_max_mean_feature_selected(df, start_year=2015, end_year=2019):
    min = np.inf
    max = 0
    mean = 0
    seasons = df.season.unique()
    correct_seasons = 0
    for s in seasons:
        start_end = s.split("-")
        if int(start_end[0]) >= start_year and int(start_end[1]) <= end_year:
            correct_seasons += 1
            features_slice = df[df.season == s]
            features_selected = len(features_slice)

            if features_selected > max:
                max = features_selected
            if features_selected < min:
                min = features_selected

            mean += features_selected

    return min, max, mean/correct_seasons

def get_feature_dictionary(df, start_year=2015, end_year=2019):
    """
    Group all the features into a dictionary. Namely, we generate for each
    feature a list of values which indicates their weight in each of the models
    under scrutiny
    :param df: the feature dataframe
    :param start_year: start year to consider
    :param end_year: end year to consider
    :return: a dictionary
    """

    feature_dictionary = {}
    seasons = df.season.unique()
    for s in seasons:
        start_end = s.split("-")
        if int(start_end[0]) >= start_year and int(start_end[1]) <= end_year:
            features_slice = df[df.season == s]
            for index, row in features_slice.iterrows():
                if row["page_name"] in feature_dictionary:
                    feature_dictionary[row["page_name"]].append(row["value"])
                else:
                    feature_dictionary[row["page_name"]] = [row["value"]]
    return feature_dictionary

def get_important_pages(important_pages, top=10, influenza_seasons=4):
    """
    Get the most important feature selected by the model.

    :param important_pages: a dictionary with, for each of the features,
    a list of their weights in each of the models.
    :param top: how many feature we want to return.
    :return: the top feature
    """
    imp_pages_avg = dict((k, sum(v) / float(influenza_seasons)) for k, v in important_pages.items())
    _terms_avg_top = sorted(sorted(imp_pages_avg.items(),
                                   key=lambda value: value[0]),
                            key=lambda value: value[1],
                            reverse=False
                            )
    return _terms_avg_top[0:top]

def generate_features(year_a, year_b, number_a, number_b):
    if not year_a.empty:
        if (number_a != 2007):
            first_part= year_a.copy()[41:52]
        else:
            first_part= year_a.copy()[48:52]
    else:
        first_part = pd.DataFrame()
    if not year_b.empty and number_b != 2007:
        second_part= year_b.copy()[0:15]
    else:
        second_part = pd.DataFrame()

    return first_part.append(second_part)

def generate(stop_year, exclude, path_features="./../data/wikipedia_italy/new_data"):
    """
    Generate a dataframe with as columns the Wikipedia's pages and as rows
    the number of pageviews for each week and for each page. The dataframe
    contains all the influenza season without the one specified by stop_year.

    :param stop_year: The influenza seasosn which will not be inserted into
    the final dataframe.
    :param path_features: the path to the directory containing all the files
    with the data.
    :return: a dataframe containing all influenza season, which can be used to
    train the model.
    """

    # The stop year must not be in the exclude list
    assert (stop_year not in exclude)

    # Generate an empty dataframe
    dataset = pd.DataFrame()

    # Get all features files and sort the list
    file_list = os.listdir(path_features)
    file_list.sort()

    for i in range(0, len(file_list)-1):
        # If the file's year is equal than stop_year then do anything
        if int(file_list[i].replace(".csv", "")) != stop_year-1:
            tmp_a = pd.read_csv(os.path.join(path_features, file_list[i]), encoding = 'utf8', delimiter=',')
        else:
            tmp_a = pd.DataFrame()

        if int(file_list[i+1].replace(".csv", "")) != stop_year:
            tmp_b = pd.read_csv(os.path.join(path_features, file_list[i+1]), encoding = 'utf8', delimiter=',')
        else:
            tmp_b = pd.DataFrame()

        # Do not add years which are in the exclude list
        if int(file_list[i+1].replace(".csv", "")) in exclude:
            continue

        # If the dataset is empty the generate a new dataframe.
        # Append a new dataframe if the dataset is not empty.
        if dataset.empty:
            dataset = generate_features(tmp_a, tmp_b, int(file_list[i].replace(".csv", "")), int(file_list[i+1].replace(".csv", "")))
        else:
            dataset = dataset.append(generate_features(tmp_a, tmp_b, int(file_list[i].replace(".csv", "")), int(file_list[i+1].replace(".csv", ""))))

    return dataset

def standardize_data(train, test):
    """
    Standardize between [-1, 1] the train and test set by applying this
    formula for each feature:

    x_new = (x-dataset_mean)/(dataset_max - dataset_min)

    :param train: the training dataset (represented with a Pandas dataframe).
    :param test: the testing dataset (represented with a Pandas dataframe).
    :return: the train and test dataset standardized
    """
    dmean = train.mean(axis=0)
    dstd = train.std(axis=0)
    ddenom = dstd

    dataset_imp = (train - dmean) / ddenom
    data_imp = (test - dmean) / ddenom

    dataset_imp.fillna(method="pad", inplace=True)
    data_imp.fillna(method="pad", inplace=True)

    data_imp.replace([np.inf, -np.inf], np.nan, inplace=True)
    dataset_imp.replace([np.inf, -np.inf], np.nan, inplace=True)

    dataset_imp.fillna(method="pad", inplace=True)
    data_imp.fillna(method="pad", inplace=True)

    dataset_imp[np.isnan(dataset_imp)] = 0.0
    data_imp[np.isnan(data_imp)] = 0.0

    return (dataset_imp, data_imp)

if __name__ == "__main__":

    # Parse the arguments
    parser = argparse.ArgumentParser()
    parser.add_argument("models", metavar="N", nargs="+", type=str, help="Models we want to check")
    parser.add_argument("--country", type=str, default="italy", help="Country name")
    parser.add_argument("--basedir", type=str, default="../complete_results")
    parser.add_argument("--future", default=True, action="store_false")
    parser.add_argument("--start-year", default=2015, type=int)
    parser.add_argument("--end-year", default=2019, type=int)
    parser.add_argument("--save", default=False, action="store_true")
    args = parser.parse_args()

    # Set some variables
    country = args.country
    base_dir = args.basedir
    future = "future" if args.future else "no-future"
    start_year = int(args.start_year)
    end_year = int(args.end_year)

    # Generate wikipedia graph
    depth = 3
    graph_name = "./{}-{}-influenza.pkl".format(LANG[country], depth)
    if os.path.exists(graph_name):
        print("Graph file exists! using that.")
        wiki_graph = load_obj(graph_name)
    else:
        wiki_graph = inspect_wikipedia_tree(LANG[country], depth)

    # Get the keywords for all the models, then compute the intersection between all of them
    total_keywords = {}
    total_features = {}
    for model_name in args.models:

        # Get models keywords
        keywords_prefix = get_keywords_prefix(model_name)
        model_total_keywords = pd.read_csv(os.path.join("../data/keywords",
                                                        "{}_{}.txt".format(keywords_prefix, country)),
                                           header=None, names=["page_name"])
        total_keywords[model_name] = model_total_keywords

        # Get selected features
        baseline_results_path = os.path.join(base_dir, model_name, future, country)
        season_years = get_results_filename(baseline_results_path, country)
        features_file = os.path.join(baseline_results_path, "{}_features_{}.csv".format(season_years, country))
        features = pd.read_csv(features_file)[["season", "page_name", "value"]]

        # Filter the data by analyzing only the range we want
        start_season_year = features.season.str.split("-", expand=True)
        features["start_year"] = start_season_year[0]
        features["end_year"] = start_season_year[1]
        features = features[(features["start_year"] >= str(start_year)) & (features["end_year"] <= str(end_year))]

        # Compute the best features over all models
        feature_dictionary = get_feature_dictionary(features)
        best_features = get_important_pages(feature_dictionary, top=5, influenza_seasons=start_year-end_year)
        best_features = [[x[0], x[1]] for x in best_features]

        total_features[model_name] = pd.DataFrame(best_features, columns=["page_name", "mean_weigth"])

        # Remove the year
        total_features[model_name] = total_features[model_name][total_features[model_name].page_name != "year"]

        # Get the features values and choose only the best ones find before. Moreover, filter then by the year.
        features_values = generate(2020, [], path_features="../data/wikipedia_{}/{}".format(country, model_name))
        year_week = features_values.Week.str.split("-", expand=True)
        features_values["start_year"] = year_week[0]
        features_values["week"] = year_week[1]
        features_values = features_values[(features_values["start_year"] >= str(start_year)) & (features_values["start_year"] <= str(end_year))]
        features_values = features_values[~((features_values["start_year"] == str(start_year)) & (features_values["week"] < "42"))]

        # Select only the top-5 and standardize the data
        features_values = features_values[total_features[model_name].page_name]
        features_values, _ = standardize_data(features_values, features_values)

        # Obtain the incidence value
        incidence = pd.read_csv(os.path.join(baseline_results_path, "{}-prediction.csv".format(
            season_years
        )))
        year_week = incidence.week.str.split("-", expand=True)
        incidence["start_year"] = year_week[0]
        incidence["week"] = year_week[1]
        incidence = incidence[
            (incidence["start_year"] >= str(start_year)) & (incidence["start_year"] <= str(end_year))]
        incidence = incidence[
            ~((incidence["start_year"] == str(start_year)) & (incidence["week"] < "42"))]

        # Add the incidence to the total features
        features_values.reset_index(drop=True, inplace=True)
        incidence.reset_index(drop=True, inplace=True)
        features_values["incidence"] = incidence["incidence"]

        correlation_incidence_values = features_values.corr()["incidence"]
        correlation_incidence_values.reset_index(drop=True, inplace=True)
        total_features[model_name]["PCC"] = correlation_incidence_values

    # Save the top-5 feature for each model
    top_5_features = pd.DataFrame()
    pages = pd.DataFrame()
    for k in total_features:

        name, type, dist = convert_naming(k)

        pages["pages"] = total_features[k]["page_name"][0:5].apply(lambda x: x.replace("_", " ")) + " (" + total_features[k]["page_name"][0:5].apply(lambda x: get_wikipedia_page_language(
            x, 'en', LANG[country]
        )) + ")"
        pages["PCC"] = total_features[k]["PCC"][0:5]
        pages["distance"] = total_features[k]["page_name"][0:5].apply(lambda x: get_distance_from_influenza(x, wiki_graph))
        print(pages["distance"])
        top_5_features[[name, type, dist]] = pages

    top_5_features = top_5_features.reindex(sorted(top_5_features.columns), axis=1)
    print(top_5_features)

    with pd.option_context("max_colwidth", 1000):
        top_5_features.to_latex("{}_features_latex.txt".format(country), index=None, float_format="%.2f")


text:
import os
import re
import webapp2
import jinja2
import time
import hashlib
import hmac

from string import letters
from secret import *

from google.appengine.ext import db

template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
                                                                autoescape = True)
###################HASHING FUNCTIONS##################################
def hash_str(s):
    return hmac.new(secret, s).hexdigest()

def make_secure_val(s):
    return "%s|%s" % (s, hash_str(s))

def check_secure_val(h):
    val = h.split('|')[0]
    if h == make_secure_val(val):
        return val

class Handler(webapp2.RequestHandler):
    def write(self, *a, **kw):
        self.response.out.write(*a, **kw)

    def render_str(self, template, **params):
        t = jinja_env.get_template(template)
        return t.render(params)

    def render(self, template, **kw):
        self.write(self.render_str(template, **kw))

    def set_cookie(self, name, val):
        cookie_val = make_secure_val(val)
        self.response.headers.add_header('Set-Cookie', '%s=%s' % (name, cookie_val))

    def read_cookie(self, name, val):
        cookie_val = self.request.cookies.get(name)
        if cookie_val and check_secure_val(cookie_val):
            return cookie_val

class Blog(db.Model):
    #user = db.StringProperty(required = True)
    #password = db.StringProperty(required = True)
    subject = db.StringProperty(required = True)
    blog = db.TextProperty(required = True)
    created = db.DateTimeProperty(auto_now_add = True)
    last_modified = db.DateTimeProperty(auto_now = True)

class IndexPage(Handler):
    def get(self):
        self.render("index.html")

class MainPage(Handler):

    def render_front(self, subject="", blog="", error=""):
        blogs = db.GqlQuery("SELECT * FROM Blog "
                            "ORDER BY created DESC ")
        time.sleep(1)
        self.render("front.html", subject= subject, blog= blog, error = error, blogs = blogs)

    def get(self):
        self.render_front("front.html")

class FormPage(Handler):

    def get(self):
        self.render("form.html")

    def post(self):
        subject = self.request.get("subject")
        blog = self.request.get("blog")

        if subject and blog:
            b = Blog(subject = subject, blog = blog)
            b_key = b.put()

            self.redirect("/blog/%d" % b_key.id())
        else:
            error = "we need both a subject and a body"
            self.render(subject, blog, error)

#Signup to work on. For hashing and validity checks
#Welcome page of user using cookie
#Add projects to website and uploading!
#Changes to CSS of template to make it not seem like a complete copy paste.

class Permalink(MainPage):
    def get(self, blog_id):
        s = Blog.get_by_id(int(blog_id))
        self.render("front.html", blogs=[s])

class SignUp(Handler):
    def get(self):
        visits = 0
        visit_cookie_str  = self.request.cookies.get('visits')
        if visit_cookie_str:
            cookie_val = check_secure_val(visit_cookie_str)
            if cookie_val:
                visits = int(cookie_val)
        visits += 1
        new_cookie_val = make_secure_val(str(visits))
        self.response.headers.add_header('Set-Cookie', 'visits=%s' % new_cookie_val)
        self.write("You've been here %s times!\n" % visits)
        self.render("signup.html")

    def post(self):
        username = self.request.get("username")
        password = self.request.get("password")
        ver_password = self.request.get("ver_password")
        email = self.request.get("email")

        if username and password and ver_password and (password == ver_password):
            self.redirect("/welcome")

class LogIn(Handler):
    def get(self):
        self.render("login.html")

    def post(self):
        username = self.request.get("username")
        password = self.request.get("password")
        if check_secure_val(make_secure_val(password)):
            self.redirect('/welcome')

app = webapp2.WSGIApplication([ ('/', IndexPage),
                                ('/blog', MainPage),
                                ('/newpost', FormPage),
                                ('/blog/(\d+)', Permalink),
                                ('/signup', SignUp),
                                ('/login', LogIn)
                               ],
                                debug = True)


text:
/**
 * Provide a transport of osapi requests over JSON-RPC. Exposed JSON-RPC endpoints and
 * their associated methods are available from config in the "osapi.services" field.
 */
(function() {

  /**
   * Called by a batch to execute all requests
   * @param requests
   * @param callback
   */
  function execute(requests, callback) {

    function processResponse(response) {
      // Convert an XHR failure to a JSON-RPC error
      if (response.errors[0]) {
        callback({
          error : {
            code : response.rc,
            message : response.text
          }
        });
      } else {
        var jsonResponse = response.data;
        if (jsonResponse.error) {
          callback(jsonResponse);
        } else {
          var responseMap = {};
          for (var i = 0; i < jsonResponse.length; i++) {
            responseMap[jsonResponse[i].id] = jsonResponse[i];
          }
          callback(responseMap);
        }
      }
    }

    var request = {
      "POST_DATA" : gadgets.json.stringify(requests),
      "CONTENT_TYPE" : "JSON",
      "METHOD" : "POST",
      "AUTHORIZATION" : "SIGNED"
    };

    var url = this.name;
    var token = shindig.auth.getSecurityToken();
    if (token) {
      url += "?st=";
      url += encodeURIComponent(token);
    }
    gadgets.io.makeNonProxiedRequest(url, processResponse, request, "application/json");
  }

  function init(config) {
    var services = config["osapi.services"];
    if (services) {
      // Iterate over the defined services, extract the http endpoints and
      // create a transport per-endpoint
      for (var endpointName in services) if (services.hasOwnProperty(endpointName)) {
        if (endpointName.indexOf("http") == 0 ||
            endpointName.indexOf("//") == 0) {
          // Expand the host & append the security token
          var endpointUrl = endpointName.replace("%host%", document.location.host);
          var transport = { name : endpointUrl, "execute" : execute };
          var methods = services[endpointName];
          for (var i=0; i < methods.length; i++) {
            osapi._registerMethod(methods[i], transport);
          }
        }
      }
    }
  }

  // Do not run this in container mode.
  if (gadgets.config) {
    gadgets.config.register("osapi.services", null, init);
  }

})();


text:
using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;
using websocketpp::lib::bind;

BroadcastServer::BroadcastServer() {
  wss.init_asio();

  // Log to a file rather than stdout.
  log.open("ws-output.log");
  wss.get_alog().set_ostream(&log);
  wss.get_elog().set_ostream(&log);

  // Print all output to stdout.
  //wss.register_ostream(&std::cout);

  wss.set_open_handler(bind(&BroadcastServer::onOpen, this, ::_1));
  wss.set_close_handler(bind(&BroadcastServer::onClose, this, ::_1));
  wss.set_message_handler(bind(&BroadcastServer::onMessage, this, ::_1, ::_2));
}

void BroadcastServer::onOpen(connectionHandle handle) {
  connections.insert(handle);
}

void BroadcastServer::onClose(connectionHandle handle) {
  connections.erase(handle);
}

void BroadcastServer::onMessage(connectionHandle hdl, message msg) {
  for (auto connection : connections) {
    wss.send(connection, msg);
  }
}

void BroadcastServer::send(std::string msg) {
  for (auto connection : connections) {
    wss.send(connection, msg, websocketpp::frame::opcode::text);
  }
}

void BroadcastServer::run(uint16_t port) {
  wss.listen(port);
  wss.start_accept();
  wss.run();
}


text:
"""
pdlearn.adaptor
~~~~~~~~~~~~~~~

Package of adaptor methods and functions to simplify porting scikit-learn's
models to work transparently with pandas.
"""

from .classifier import classifier
from .regressor import regressor
from .transformer import transformer
from .methods import feature_property


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

// This can be removed if you use __autoload() in config.php OR use Modular Extensions
/** @noinspection PhpIncludeInspection */
require APPPATH . '/libraries/REST_Controller.php';
require APPPATH . '/libraries/storelog.php';        //call function storelog(4,$logmessage); 1-error/warning , 2-debug, 3-info msg
use Restserver\Libraries\REST_Controller;

class Adminroles_api extends REST_Controller {
    function __construct()
    {
        // Construct the parent class
        parent::__construct();
        $this->load->model('Admin_roles');
        // Configure limits on our controller methods
        // Ensure you have created the 'limits' table and enabled 'limits' within application/config/rest.php
        // $this->methods['customers_get']['limit'] = 500; // 500 requests per hour per user/key
        // $this->methods['customer_post']['limit'] = 100; // 100 requests per hour per user/key
        // $this->methods['customer_put']['limit'] = 100; // 100 requests per hour per user/key
        // $this->methods['customer_delete']['limit'] = 50; // 50 requests per hour per user/key
    }

    public function roles_get($id=''){
        if(!empty($id)){
            $result=$this->Admin_roles->get_roles($id);
            if(!empty($result)){
                $this->response(array("status"=>true,"roles"=>$result),200);
            }
            else{
                $this->response(array("msg"=>"Role Id ".$id." Does Not Exist!!","status"=>false),404);
            }
        }
        else
        {
            $result=$this->Admin_roles->get_roles();
            if(!empty($result)){
                $this->response(array("status"=>true,"roles"=>$result),200);
            }
            else{
                $this->response(array("msg"=>"Roles Do Not Exist!!","status"=>false),404);
            }
        }
    }
    public function roles_post(){
        if(!empty($this->post('Role_Name')))
        {
            $role=array("Role_Name"=>trim($this->post('Role_Name')));
            if(!empty($result=$this->Admin_roles->addnew_role($role))){
                $this->response(array("msg"=>$result['msg'],"status"=>$result['status']),200);
            }
            else{
                $this->response(array("msg"=>"Failed To Store Customer","status"=>false),404);
            }
        }
        else{
            $errormsg="Roll Name is Required!!!";
            $this->response(array("msg"=>$errormsg,"status"=>false),404);
        }
    }

    public function roles_put($id=''){
        if(!empty($id)){
            if(!empty($this->put('Role_Name')))
            {
                $role=array(
                    "Role_ID"=>$id,
                    "Role_Name"=>trim($this->put('Role_Name')),
                );
                if(!empty($result=$this->Admin_roles->edit_role($role))){
                    $this->response(array("msg"=>$result['msg'],"status"=>$result['status']),200);
                }
                else{
                    $this->response(array("msg"=>"Failed To Store Role!!!","status"=>false),404);
                }
            }
            else{
                $errormsg="Invalid Role Name !!!";
                $this->response(array("msg"=>$errormsg,"status"=>false),404);
            }
        }
        else{
            $errormsg="Role ID parameter is required!!!";
            $this->response(array("msg"=>$errormsg,"status"=>false),404);
        }
    }

    public function roles_delete($id=''){
        if(!empty($id)){
            $result=$this->Admin_roles->delete_roles($id);
            if(!empty($result)){
                $this->response(array("msg"=>$result['msg'],"status"=>$result['status']),200);
            }
        }
        else
        {
            $result=$this->Admin_roles->delete_roles();
            if(!empty($result)){
                $this->response(array("msg"=>$result['msg'],"status"=>$result['status']),200);
            }
        }
    }

}


text:
from google.analytics import admin_v1alpha

def sample_delete_firebase_link():
    # Create a client
    client = admin_v1alpha.AnalyticsAdminServiceClient()

    # Initialize request argument(s)
    request = admin_v1alpha.DeleteFirebaseLinkRequest(
        name="name_value",
    )

    # Make the request
    client.delete_firebase_link(request=request)

# [END analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteFirebaseLink_sync]