text:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>4K YouTube to MP3 | Free YouTube to MP3 Converter | 4K Download</title>

        <meta name="description" content="Convert YouTube to MP3 on Mac OS X, PC and Linux absolutely for free! Download the entire YouTube playlist and create your audio collection."/>
        <meta name="keywords" content="youtube to mp3, youtubetomp3, free youtube to mp3, vimeo to mp3"/>
        <meta name="author" content="Open Media LLC"/>

        <meta name="robots" content="index,follow"/>

        <link rel="shortcut icon" type="image/x-icon" href="https://static.4kdownload.com/main/img/favicon.14dc87052228.ico" />
        <link rel="apple-touch-icon" href="https://static.4kdownload.com/main/img/apple-touch-icon-57x57.5fc374e89554.png" />
        <link rel="apple-touch-icon" sizes="72x72" href="https://static.4kdownload.com/main/img/apple-touch-icon-72x72.2f5070cba950.png" />
        <link rel="apple-touch-icon" sizes="144x144" href="https://static.4kdownload.com/main/img/apple-touch-icon-114x114.6461ee2446c6.png" />

        <link rel="canonical" href="http://www.4kdownload.com/products/product-youtubetomp3" />

        <meta property="fb:app_id" content="221385841547848" />
        <meta property="og:url" content="http://www.4kdownload.com/products/product-youtubetomp3" />
        <meta property="og:locale" content="en" />
        <meta property="og:site_name" content="4K Download" />
        <meta property="twitter:url" content="http://www.4kdownload.com/products/product-youtubetomp3" />

    <meta property="og:type" content="product" />
    <meta property="og:image" content="http://static.4kdownload.com/main/img/product/youtubetomp3/share.cdb043cc42cc.jpg" />
    <meta property="og:image:secure_url" content="https://static.4kdownload.com/main/img/product/youtubetomp3/share.cdb043cc42cc.jpg" />
    <meta property="product:brand" content="4K Download" />
    <meta property="product:product_link" content="https://www.4kdownload.com/products/product-youtubetomp3" />
    <meta property="product:category" content="Software" />
    <meta property="twitter:card" content="product">
    <meta property="twitter:site" content="@4kdownload">
    <meta property="twitter:creator" content="@4kdownload">
    <meta property="twitter:image" content="https://static.4kdownload.com/main/img/product/youtubetomp3/share.cdb043cc42cc.jpg" />

    <meta property="og:title" content="4K YouTube to MP3 | Free YouTube to MP3 Converter" />
    <meta property="og:description" content="Convert YouTube to MP3 on Mac OS X, PC and Linux absolutely for free! Download the entire YouTube playlist and create your audio collection." />
    <meta property="product:price:amount" content="0" />
    <meta property="product:price:currency" content="USD" />
    <meta property="twitter:title" content="4K YouTube to MP3 | Free YouTube to MP3 Converter" />
    <meta property="twitter:description" content="Convert YouTube to MP3 on Mac OS X, PC and Linux absolutely for free! Download the entire YouTube playlist and create your audio collection." />

    <meta property="twitter:data1" content="Free">
    <meta property="twitter:label1" content="PRICE">
    <meta property="twitter:data2" content="Software">
    <meta property="twitter:label2" content="CATEGORY">

        <link rel="alternate" hreflang="en" href="https://www.4kdownload.com/products/product-youtubetomp3" />

        <link rel="alternate" hreflang="de" href="https://www.4kdownload.com/de/products/product-youtubetomp3" />

        <link rel="alternate" hreflang="fr" href="https://www.4kdownload.com/fr/products/product-youtubetomp3" />

        <link rel="alternate" hreflang="it" href="https://www.4kdownload.com/it/products/product-youtubetomp3" />

        <link rel="alternate" hreflang="es" href="https://www.4kdownload.com/es/products/product-youtubetomp3" />

        <link rel="alternate" hreflang="pt-br" href="https://www.4kdownload.com/pt-br/products/product-youtubetomp3" />

        <link rel="alternate" hreflang="nl" href="https://www.4kdownload.com/nl/products/product-youtubetomp3" />

        <link rel="alternate" hreflang="pl" href="https://www.4kdownload.com/pl/products/product-youtubetomp3" />

        <link rel="alternate" hreflang="zh-cn" href="https://www.4kdownload.com/zh-cn/products/product-youtubetomp3" />

        <link rel="alternate" hreflang="zh-tw" href="https://www.4kdownload.com/zh-tw/products/product-youtubetomp3" />

        <link rel="alternate" hreflang="ko" href="https://www.4kdownload.com/ko/products/product-youtubetomp3" />

        <link rel="alternate" hreflang="ja" href="https://www.4kdownload.com/ja/products/product-youtubetomp3" />

        <link rel="alternate" hreflang="ru" href="https://www.4kdownload.com/ru/products/product-youtubetomp3" />

        <link rel="stylesheet" href="https://static.4kdownload.com/CACHE/css/4955719535b4.css" type="text/css" />

    <link href="https://static.4kdownload.com/3rdparty/lightbox/css/lightbox.f8d150a2345e.css" rel="stylesheet" />

                    Home

                    Download

                    Help

                    Blog

                    About

                                English

                                Deutsch

                                français

                                italiano

                                español

                                Português Brasileiro

                                Nederlands

                                polski

                                简体中文

                                繁體中文

                                한국어

                                日本語

                                Русский

  Сonvert YouTube to MP3, fast and easy

4K YouTube to MP3 was specifically created to extract audio from YouTube, Vimeo or Facebook and save it in MP3, M4A, OGG. No annoying and complicated settings to deal with, just a clean, friendly and functional interface. Downloading is simple and straightforward: just copy the link from your browser and click 'Paste Url'. Done!

        No toolbars, no adware, no malware.

    And best of all it's FREE YouTube to MP3 converter! Enjoy your audio anywhere, any time, and of course even when you are offline!

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

We have more applications you may like...

4K Slideshow Maker

                                        The easiest slideshow maker software. Mix favorite photos, music, gorgeous effects and transitions.

4K Video Downloader

                                        Download video, audio and subtitles from YouTube in the high quality  as fast as possible.

4K Stogram

                                        Free Instagram Downloader for PC, Mac and Linux. Just enter 'username' and photos will be available for you.

                        Show all applications

            Get 4K YouTube to MP3

                Version 3.1,
                Microsoft Windows

                Tweet

            Watch Screenshots

            Watch Video

            View All Platforms

            View Help

Features

Extract audio from YouTube videos and save it in MP3, M4A or OGG in high quality.

Download full YouTube playlists or channels and generate m3u files.

Transfer downloaded tracks automatically into iTunes and upload them on your iPhone or iPod.

Listen music via native built-in music player.

Download and extract audio tracks from SoundCloud, Vimeo, Flickr and DailyMotion videos.

Download audio books from YouTube.

Extract audio tracks even from embedded in HTML page videos.

Use 4K YouTube to MP3 on your PC, Mac or Linux, doesn't matter what OS you prefer.

Summary

                            Application Name: 4K YouTube to MP3

                            <meta itemprop="image" content="https://static.4kdownload.com/main/img/logo/youtubetomp3-48.40140860dfe4.png">
                            <meta itemprop="url" content="https://www.4kdownload.com/products/product-youtubetomp3">

                            Rating:

                                <meta itemprop="worstRating" content="1">
                                4.5
                                (707 rates)
                                <meta itemprop="bestRating" content="5">

                            Price: Free

                                <meta itemprop="url" content="https://www.4kdownload.com/products/product-youtubetomp3">
                                <meta itemprop="price" content="0">
                                <meta itemprop="priceCurrency" content="USD">

                            Current Version:
                            3.1

                            Last Updated:
                            Feb. 3, 2017

                            Software Category: Multimedia

                            Operating System:
                            Windows 10,
                            Windows 8,
                            Windows 7,
                            OSX 10.12,
                            OSX 10.11,
                            OSX 10.10,
                            OSX 10.9,
                            Ubuntu Linux

                            Author:
                            Open Media LLC

User's Comments

                Juan Aguilar

                Excelente. Muchas Gra ias. Saludos.

                Mond 48

                Vielen lieben Dank Leute. Ich konnte so schon viele Lieder in der Qualität, der Stimme oder mit der Melodie herunterladen, wie ich sie gerne wollte. Auch Videos, die es auf Spotiffy nicht gibt, konnte ich so herunterladen. Thanks

                Ricci Emidio

                Grazie tantissime per la musica che piace a me

                YONT PONKA

                very good program!!

                Арсалан Цыренов

                Thank you for your products!

                màrio luìs

                excelent herramienta...gracias

                stuart

                bueno

                Jayant Kulkarni

                Absolutely best.

                vc-nalvic-màrio luìs

                excelent programme...merci beaucoup, c 'est une grande aide....salut!!

                Виктор Окишев

                Хорошая программа для скачивания музыки. Спасибо разработчикам!!!

                Rahul Goel

                the best best program

                jackson Tyc

                Nice!

                mick

                good app..!!

                ibrahim omer

                best progaram

                bob billy

                Good software i can download all of my songs for free. Easy and efficient

                Richard Acosta

                Excelente programa, lo recomiendo 1000%

                christos b

                recommended

                Daikrys

                best youtube to mp3 converter ever!

                mike

                good software keep it on guys!!

                Shinsky

                Best software ever

                SG

                Recommended. Very easy to use. Thanks devs.

                laurent

                tout simplement magnifique !!

                João Paulo

                Perfeito!

                ( ͡° ͜ʖ ͡°)

                Pretty nice.

                Sidney Nogueira

                Excellent free/adfree application. Congrats to all contributors.

                Andre Toledo

                Best Youtube Download Software!

                maguVE

                Sorprendentemente excelente!!!!

                John

                This is so GOOD!

                otakumi

                i don't remember how i was led to this but yo 4kdownloader is the best.
please keep up the good apps :D

                uptoun

                Very reliable and doesn't appear to conflict with anything!

                head gasket repair

                Keep this going please, great job!

                sac louis vuitton blanc

                I love it աhenever people get togetҺer аnd share thоughts.
Great site, keep іt up!

                Tyler

                This is an amazing piece of software!! Keep up the good work :D

                Micah

                OMG this is the best ! keep up the good work guys . (y)

                Riju

                Its good to see software that runs good on all platforms.

                Shirley

                Guys, you are the best...keep going...what amazing piece of software...

                Christian

                Its good to see software that runs good on all platforms.

        <button class="btn btn-default btn-sm">Show More Comments</button>

<form class="comments-form form-horizontal" role="form" action="/comments/post/" method="post">
    <input type='hidden' name='csrfmiddlewaretoken' value='XdemGyf8rsk5aJDaY8weF6I5r4Qi53Ak' />

<input id="id_content_type" name="content_type" type="hidden" value="main.product" />

<input id="id_object_pk" name="object_pk" type="hidden" value="3" />

<input id="id_timestamp" name="timestamp" type="hidden" value="1499876936" />

<input id="id_security_hash" maxlength="40" name="security_hash" type="hidden" value="7c3cd44dcaa7d4aba9cb59a88efb9b5146e128b8" />

                Name

                    <input id="comment_name_id" class="form-control" type="text" name="name" placeholder="Your name" />

                Email

                    <input id="comment_email_id" class="form-control" type="email" name="email" placeholder="Your email address" />

<input id="id_url" name="url" type="url" />

                Comment

                    <textarea id="comment_comment_id" class="form-control" rows="8" name="comment" placeholder="Your comment"></textarea>

<input id="id_honeypot" name="honeypot" type="text" />

            <button class="btn btn-primary" type="submit" name="post">Add Comment</button>
            Cancel

            <input type="hidden" name="recaptcha" id="recaptcha" required>

</form>

                    Copyright © 2016 OpenMedia LLC. All rights reserved.

                        License Agreement

                        Privacy Policy

                        How to uninstall

                                English

                                            English

                                            Deutsch

                                            français

                                            italiano

                                            español

                                            Português Brasileiro

                                            Nederlands

                                            polski

                                            简体中文

                                            繁體中文

                                            한국어

                                            日本語

                                            Русский


text:
require 'sprockets'
require 'tilt'
require 'action_view'
require 'action_view/helpers'

module KnockoutTemplateRails
  class KnockoutTemplate < Tilt::Template
    include ActionView::Helpers::JavaScriptHelper

    def self.default_mime_type
      'text/html'
    end

    def prepare
      @prefix = normalize_prefix(Rails.configuration.knockout_templates.prefix)
    end

    def evaluate(scope, locals, &block)
      %{document.write('<scr' + 'ipt type="text/html" id="#{template_name(scope)}">#{escape_javascript(data)}</scr' + 'ipt>');}
    end

    private

    def normalize_prefix(prefix)
      if prefix.respond_to?(:length) && prefix.length > 0
        prefix = prefix[1, prefix.length - 1] if prefix.start_with?("/")
        prefix += "/" unless prefix.end_with?("/")
      end

      prefix
    end

    def template_name(scope)
      scope.logical_path.sub(@prefix, "")
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
layout: page
title: Wright Industries Conference
date: 2016-05-24
author: Doris Watts
tags: weekly links, java
status: published
summary: Aenean a leo nunc. Cras congue odio sit amet.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 11/15/2017
  endDate: 11/18/2017
  ctyhocn: YYCAPHX
  groupCode: WIC
published: true
---
Morbi in neque id tortor malesuada gravida et nec lectus. Etiam interdum lacus sit amet sem iaculis iaculis. Sed dignissim venenatis leo eget pulvinar. Proin et nisi nisl. Proin pretium tellus sed massa fringilla, consequat feugiat justo maximus. Ut a augue ante. Maecenas at felis non dui ullamcorper elementum eget at erat. Vestibulum lobortis lacus metus, sed sollicitudin orci venenatis id. Nam non neque ut tortor facilisis molestie.
Fusce sit amet sem non orci lacinia efficitur. Etiam vel massa elit. Nunc dictum ut ligula eu sodales. Morbi imperdiet purus in ante accumsan sagittis sed sit amet ligula. Mauris dui arcu, malesuada mattis purus et, tempus dictum leo. Donec tincidunt eros magna, a commodo ligula interdum vel. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;

* Donec lacinia magna quis nisi luctus bibendum
* Cras eget ante ac ipsum elementum dictum
* Nam laoreet lacus venenatis tellus sodales, sit amet rhoncus purus consectetur
* Quisque sed sapien sodales, tempus ex vitae, ultricies ante.

Maecenas semper sapien et arcu volutpat suscipit. Cras quis ultrices neque, non vestibulum velit. Proin vehicula luctus ultrices. Mauris felis leo, molestie nec dui sed, congue posuere ex. Suspendisse est lorem, sodales tempor nisi vitae, luctus lobortis magna. Suspendisse vestibulum leo eu odio semper, ac sollicitudin libero semper. Cras arcu tortor, lobortis non nulla eu, bibendum molestie lectus. Suspendisse ac suscipit ante, a molestie tellus. Mauris elementum erat non ex posuere convallis. Cras gravida egestas lacus, et aliquet lectus maximus vel. Cras vitae convallis mi. Integer aliquet pellentesque nisl, sit amet euismod tortor. Maecenas mattis pharetra orci ornare sagittis. Aliquam ut lorem vestibulum, fermentum metus a, tristique enim. Sed iaculis egestas lobortis. Integer volutpat mauris ligula, quis faucibus arcu vulputate non.


text:
require "spec_helper"

module ShipCompliant
  describe VoidSalesOrder do

    before { savon.mock! }
    after { savon.unmock! }

    let(:message) do
      {
        'Request' => {
          'Security' => {
            'PartnerKey' => 'abc-123',
            'Username' => 'bob@example.com',
            'Password' => 'secret'
          },
          'SalesOrderKey' => 'SomeOrderId'
        }
      }
    end

    let(:success_response) { File.read('spec/fixtures/void_order_success.xml') }

    context "by_order_key" do
      it "queries the client" do
        savon.expects(:void_sales_order)
          .with(message: message).returns(success_response)

        VoidSalesOrder.by_order_key('SomeOrderId')
      end

      it "returns a VoidSalesOrderResult" do
        allow(VoidSalesOrder).to receive(:void_order) { {} }

        result = VoidSalesOrder.by_order_key('SomeOrderId')
        expect(result).to be_kind_of(VoidSalesOrderResult)
      end
    end

  end
end


text:
from PIL import Image
from os import walk, path
from Error import ImgProcessException

def fetchItemsFromDir(directory, const = False):
    for (root, dirnames, filenames) in walk(directory):
        return {'files' : list(filenames), 'folders' : list(dirnames)}

    if not const:
        raise ImgProcessException('File', 'The directory "%s" does not exist.' % (directory))

def fileExists(filename, directory, exception = False):
    if not filename in fetchItemsFromDir(directory)['files']:
        if exception:
            raise ImgProcessException('File', 'The file "%s" does not exist at "%s/%s".' % (filename, directory, filename))

        return False

    return True

def fileGetLines(filename, directory):
    lines = list()

    if fileExists(filename, directory, True):
        f     = open('%s/%s' % (directory, filename), 'r')
        lines = f.readlines()

        f.close()

    return list(lines)

def saveImage(filename, directory, data, width, height):
    outImage = Image.new('L', (width, height))

    outImage.putdata(data)
    outImage.save('%s/%s' % (directory, filename))

def getRawImageData(filename, directory):
    sourceFile    = Image.open('%s/%s' % (directory, filename)) if fileExists(filename, directory, True) else False
    width, height = sourceFile.size

    return width, height, list(sourceFile.getdata())


text:
document.addEventListener('DOMContentLoaded', init);

function init(){
clickBackGround();
clickNo();
clickReview();
clickLater();
}

function clickBackGround(){
document.getElementById("textContent").onclick = openReviewPage;
document.getElementById("icon").onclick = openReviewPage;
}
function clickNo(){
document.getElementById("noBtn").onclick = no;
}
function clickReview(){
document.getElementById("reviewBtn").onclick = review;
}
function clickLater(){
document.getElementById("laterBtn").onclick = later;
}

function openReviewPage(){
	var options = "https://chrome.google.com/webstore/detail/youtweak-for-youtube/cfgpigllcihcpkbokdnmpkjobnebflgh/reviews";
	window.open(options,'_newtab');
	window.close();
}
function no(){
   chrome.storage.sync.set({
		'reviewed' : true
	}, function() {
		// Notify that we saved.
	});
	window.close();
}
function later(){
   //sets install date to today.
	var setDays = convertDateToDays(new Date());

   chrome.storage.sync.set({
		'reviewed' : false,
		'reviewDateDays' : setDays
	}, function() {
		// Notify that we saved.
	});

	window.close();
}
function review(){
   //sets install date to today.
	var setDays = convertDateToDays(new Date());

   chrome.storage.sync.set({
		'reviewed' : true
	}, function() {
		// Notify that we saved.
	});
	openReviewPage();
	window.close();
}

function convertDateToDays(date){
	var temp;
	var month = date.getMonth();
	var aggregateMonths = [0, // January
                           31, // February
                           31 + 28, // March
                           31 + 28 + 31, // April
                           31 + 28 + 31 + 30, // May
                           31 + 28 + 31 + 30 + 31, // June
                           31 + 28 + 31 + 30 + 31 + 30, // July
                           31 + 28 + 31 + 30 + 31 + 30 + 31, // August
                           31 + 28 + 31 + 30 + 31 + 30 + 31 + 31, // September
                           31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30, // October
                           31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31, // November
                           31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30, // December
                         ];
	return (date.getDate() + aggregateMonths[month]);
}


text:
define(
    'bundles/package/index',
    [],
    function () {
        return {
            name: 'bundles/package/index'
        };
    }
);

define('bundlesPackage', ['bundlesPackage/main'],
    function (main) {return main;}
);

define(
    'bundlesPackage/main',
    [],
    function () {
        return {
            name: 'bundlesPackage/main'
        };
    }
);


text:
package jadx.core.codegen;

import jadx.api.JadxArgs;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.PrimitiveType;
import jadx.core.dex.nodes.IDexNode;
import jadx.core.utils.StringUtils;
import jadx.core.utils.Utils;
import jadx.core.utils.exceptions.JadxRuntimeException;

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

public class TypeGen {
	private static final Logger LOG = LoggerFactory.getLogger(TypeGen.class);

	private TypeGen() {
	}

	public static String signature(ArgType type) {
		PrimitiveType stype = type.getPrimitiveType();
		if (stype == PrimitiveType.OBJECT) {
			return Utils.makeQualifiedObjectName(type.getObject());
		}
		if (stype == PrimitiveType.ARRAY) {
			return '[' + signature(type.getArrayElement());
		}
		return stype.getShortName();
	}

	/**
	 * Convert literal value to string according to value type
	 *
	 * @throws JadxRuntimeException for incorrect type or literal value
	 */
	public static String literalToString(long lit, ArgType type, IDexNode dexNode) {
		return literalToString(lit, type, dexNode.root().getStringUtils());
	}

	@Deprecated
	public static String literalToString(long lit, ArgType type) {
		return literalToString(lit, type, new StringUtils(new JadxArgs()));
	}

	private static String literalToString(long lit, ArgType type, StringUtils stringUtils) {
		if (type == null || !type.isTypeKnown()) {
			String n = Long.toString(lit);
			if (Math.abs(lit) > 100) {
				n += "; // 0x" + Long.toHexString(lit)
						+ " float:" + Float.intBitsToFloat((int) lit)
						+ " double:" + Double.longBitsToDouble(lit);
			}
			return n;
		}

		switch (type.getPrimitiveType()) {
			case BOOLEAN:
				return lit == 0 ? "false" : "true";
			case CHAR:
				return stringUtils.unescapeChar((char) lit);
			case BYTE:
				return formatByte((byte) lit);
			case SHORT:
				return formatShort((short) lit);
			case INT:
				return formatInteger((int) lit);
			case LONG:
				return formatLong(lit);
			case FLOAT:
				return formatFloat(Float.intBitsToFloat((int) lit));
			case DOUBLE:
				return formatDouble(Double.longBitsToDouble(lit));

			case OBJECT:
			case ARRAY:
				if (lit != 0) {
					LOG.warn("Wrong object literal: {} for type: {}", lit, type);
					return Long.toString(lit);
				}
				return "null";

			default:
				throw new JadxRuntimeException("Unknown type in literalToString: " + type);
		}
	}

	public static String formatShort(short s) {
		if (s == Short.MAX_VALUE) {
			return "Short.MAX_VALUE";
		}
		if (s == Short.MIN_VALUE) {
			return "Short.MIN_VALUE";
		}
		return "(short) " + Short.toString(s);
	}

	public static String formatByte(byte b) {
		if (b == Byte.MAX_VALUE) {
			return "Byte.MAX_VALUE";
		}
		if (b == Byte.MIN_VALUE) {
			return "Byte.MIN_VALUE";
		}
		return "(byte) " + Byte.toString(b);
	}

	public static String formatInteger(int i) {
		if (i == Integer.MAX_VALUE) {
			return "Integer.MAX_VALUE";
		}
		if (i == Integer.MIN_VALUE) {
			return "Integer.MIN_VALUE";
		}
		return Integer.toString(i);
	}

	public static String formatLong(long l) {
		if (l == Long.MAX_VALUE) {
			return "Long.MAX_VALUE";
		}
		if (l == Long.MIN_VALUE) {
			return "Long.MIN_VALUE";
		}
		String str = Long.toString(l);
		if (Math.abs(l) >= Integer.MAX_VALUE) {
			str += "L";
		}
		return str;
	}

	public static String formatDouble(double d) {
		if (Double.isNaN(d)) {
			return "Double.NaN";
		}
		if (d == Double.NEGATIVE_INFINITY) {
			return "Double.NEGATIVE_INFINITY";
		}
		if (d == Double.POSITIVE_INFINITY) {
			return "Double.POSITIVE_INFINITY";
		}
		if (d == Double.MIN_VALUE) {
			return "Double.MIN_VALUE";
		}
		if (d == Double.MAX_VALUE) {
			return "Double.MAX_VALUE";
		}
		if (d == Double.MIN_NORMAL) {
			return "Double.MIN_NORMAL";
		}
		return Double.toString(d) + "d";
	}

	public static String formatFloat(float f) {
		if (Float.isNaN(f)) {
			return "Float.NaN";
		}
		if (f == Float.NEGATIVE_INFINITY) {
			return "Float.NEGATIVE_INFINITY";
		}
		if (f == Float.POSITIVE_INFINITY) {
			return "Float.POSITIVE_INFINITY";
		}
		if (f == Float.MIN_VALUE) {
			return "Float.MIN_VALUE";
		}
		if (f == Float.MAX_VALUE) {
			return "Float.MAX_VALUE";
		}
		if (f == Float.MIN_NORMAL) {
			return "Float.MIN_NORMAL";
		}
		return Float.toString(f) + "f";
	}

}


text:
({
    _count: 1,
    _createCmpCompletionCount: 0,
    _deleteLastComponentCount: 0,
    _deleteFirstComponentCount: 0
})


text:
"""Proximal stochastic dual coordinate ascent optimizer for linear models."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import collections

from six.moves import range
import tensorflow as tf
from tensorflow.python.framework import ops
from tensorflow.python.framework.ops import internal_convert_to_tensor
from tensorflow.python.framework.ops import name_scope
from tensorflow.python.ops import gen_sdca_ops
from tensorflow.python.ops import variables as var_ops
from tensorflow.python.ops.nn import log_poisson_loss
from tensorflow.python.ops.nn import sigmoid_cross_entropy_with_logits
from tensorflow_estimator.python.estimator.canned.linear_optimizer.python.utils.sharded_mutable_dense_hashtable import _ShardedMutableDenseHashTable

class _SparseFeatureColumn(object):
  """Represents a sparse feature column.

  This is meant to be a more efficient representation than tf.SparseFeature for
  the purpose of SDCA optimization.
  Contains three tensors representing a sparse feature column, they are
  example indices (`int64`), feature indices (`int64`), and feature
  values (`float`).
  Feature weights are optional, and are treated as `1.0f` if missing.

  For example, consider a batch of 4 examples, which contains the following
  features in a particular `_SparseFeatureColumn`:

  * Example 0: feature 5, value 1
  * Example 1: feature 6, value 1 and feature 10, value 0.5
  * Example 2: no features
  * Example 3: two copies of feature 2, value 1

  This _SparseFeatureColumn will be represented as follows:

  ```
   <0, 5,  1>
   <1, 6,  1>
   <1, 10, 0.5>
   <3, 2,  1>
   <3, 2,  1>
  ```

  For a batch of 2 examples below:

  * Example 0: feature 5
  * Example 1: feature 6

  is represented by `_SparseFeatureColumn` as:

  ```
   <0, 5,  1>
   <1, 6,  1>

  ```

  @@__init__
  @@example_indices
  @@feature_indices
  @@feature_values
  """

  def __init__(self, example_indices, feature_indices, feature_values):
    """Creates a `_SparseFeatureColumn` representation.

    Args:
      example_indices: A 1-D int64 tensor of shape `[N]`. Also, accepts python
        lists, or numpy arrays.
      feature_indices: A 1-D int64 tensor of shape `[N]`. Also, accepts python
        lists, or numpy arrays.
      feature_values: An optional 1-D tensor float tensor of shape `[N]`. Also,
        accepts python lists, or numpy arrays.

    Returns:
      A `_SparseFeatureColumn`
    """
    with name_scope(None, 'SparseFeatureColumn',
                    [example_indices, feature_indices]):
      self._example_indices = internal_convert_to_tensor(
          example_indices, name='example_indices', dtype=tf.dtypes.int64)
      self._feature_indices = internal_convert_to_tensor(
          feature_indices, name='feature_indices', dtype=tf.dtypes.int64)
    self._feature_values = None
    if feature_values is not None:
      with name_scope(None, 'SparseFeatureColumn', [feature_values]):
        self._feature_values = internal_convert_to_tensor(
            feature_values, name='feature_values', dtype=tf.dtypes.float32)

  @property
  def example_indices(self):
    """The example indices represented as a dense tensor.

    Returns:
      A 1-D Tensor of int64 with shape `[N]`.
    """
    return self._example_indices

  @property
  def feature_indices(self):
    """The feature indices represented as a dense tensor.

    Returns:
      A 1-D Tensor of int64 with shape `[N]`.
    """
    return self._feature_indices

  @property
  def feature_values(self):
    """The feature values represented as a dense tensor.

    Returns:
      May return None, or a 1-D Tensor of float32 with shape `[N]`.
    """
    return self._feature_values

class _SDCAModel(object):
  """Stochastic dual coordinate ascent solver for linear models.

    Loss functions supported:

     * Binary logistic loss
     * Squared loss
     * Hinge loss
     * Smooth hinge loss
     * Poisson log loss

    ### Usage

    ```python
    # Create a solver with the desired parameters.
    lr = _SDCAModel(examples, variables, options)
    min_op = lr.minimize()
    opt_op = lr.update_weights(min_op)

    predictions = lr.predictions(examples)
    # Primal loss + L1 loss + L2 loss.
    regularized_loss = lr.regularized_loss(examples)
    # Primal loss only
    unregularized_loss = lr.unregularized_loss(examples)

    examples: {
      sparse_features: list of SparseFeatureColumn.
      dense_features: list of dense tensors of type float32.
      example_labels: a tensor of type float32 and shape [Num examples]
      example_weights: a tensor of type float32 and shape [Num examples]
      example_ids: a tensor of type string and shape [Num examples]
    }
    variables: {
      sparse_features_weights: list of tensors of shape [vocab size]
      dense_features_weights: list of tensors of shape [dense_feature_dimension]
    }
    options: {
      symmetric_l1_regularization: 0.0
      symmetric_l2_regularization: 1.0
      loss_type: "logistic_loss"
      num_loss_partitions: 1 (Optional, with default value of 1. Number of
      partitions of the global loss function, 1 means single machine solver,
      and >1 when we have more than one optimizer working concurrently.)
      num_table_shards: 1 (Optional, with default value of 1. Number of shards
      of the internal state table, typically set to match the number of
      parameter servers for large data sets.
    }
    ```

    In the training program you will just have to run the returned Op from
    minimize().

    ```python
    # Execute opt_op and train for num_steps.
    for _ in range(num_steps):
      opt_op.run()

    # You can also check for convergence by calling
    lr.approximate_duality_gap()
    ```
  """

  def __init__(self, examples, variables, options):
    """Create a new sdca optimizer."""

    if not examples or not variables or not options:
      raise ValueError('examples, variables and options must all be specified.')

    supported_losses = ('logistic_loss', 'squared_loss', 'hinge_loss',
                        'smooth_hinge_loss', 'poisson_loss')
    if options['loss_type'] not in supported_losses:
      raise ValueError('Unsupported loss_type: ', options['loss_type'])

    self._assert_specified([
        'example_labels', 'example_weights', 'example_ids', 'sparse_features',
        'dense_features'
    ], examples)
    self._assert_list(['sparse_features', 'dense_features'], examples)

    self._assert_specified(
        ['sparse_features_weights', 'dense_features_weights'], variables)
    self._assert_list(['sparse_features_weights', 'dense_features_weights'],
                      variables)

    self._assert_specified([
        'loss_type', 'symmetric_l2_regularization',
        'symmetric_l1_regularization'
    ], options)

    if options['symmetric_l2_regularization'] <= 0.0:
      raise ValueError('symmetric_l2_regularization should be positive.')
    if options['symmetric_l2_regularization'] <= 1.0:
      tf.compat.v1.logging.warn(
          'symmetric_l2_regularization for SDCA should typically be '
          'larger than for online optimization methods. Recommended '
          'value is of the order of the average L2 norm of the '
          'training examples.')
    if options['symmetric_l1_regularization'] < 0.0:
      raise ValueError('symmetric_l1_regularization should be non-negative.')

    self._examples = examples
    self._variables = variables
    self._options = options
    self._create_slots()
    self._hashtable = _ShardedMutableDenseHashTable(
        key_dtype=tf.dtypes.int64,
        value_dtype=tf.dtypes.float32,
        num_shards=self._num_table_shards(),
        default_value=[0.0, 0.0, 0.0, 0.0],
        # SdcaFprint never returns 0 or 1 for the low64 bits, so this a safe
        # empty_key (that will never collide with actual payloads).
        empty_key=[0, 0],
        deleted_key=[1, 1])

    tf.compat.v1.summary.scalar('approximate_duality_gap',
                                self.approximate_duality_gap())
    tf.compat.v1.summary.scalar('examples_seen', self._hashtable.size())

  def _symmetric_l1_regularization(self):
    return self._options['symmetric_l1_regularization']

  def _symmetric_l2_regularization(self):
    return self._options['symmetric_l2_regularization']

  def _num_loss_partitions(self):
    # Number of partitions of the global objective.
    return self._options.get('num_loss_partitions', 1)

  def _adaptive(self):
    # Perform adaptive sampling.
    return self._options.get('adaptive', True)

  def _num_table_shards(self):
    # Number of hash table shards.
    # Return 1 if not specified or if the value is 'None'
    num_shards = self._options.get('num_table_shards')
    return 1 if num_shards is None else num_shards

  def _create_slots(self):
    """Make unshrunk internal variables (slots)."""
    # Unshrunk variables have the updates before applying L1 regularization.
    # Each unshrunk slot variable is either a `Variable` or list of
    # `Variable`, depending on the value of its corresponding primary variable.
    # We avoid using `PartitionedVariable` for the unshrunk slots since we do
    # not need any of the extra information.
    self._slots = collections.defaultdict(list)
    for name in ['sparse_features_weights', 'dense_features_weights']:
      for var in self._variables[name]:
        # Our primary variable may be either a PartitionedVariable, or a list
        # of Variables (each representing a partition).
        if (isinstance(var, var_ops.PartitionedVariable) or
            isinstance(var, list)):
          var_list = []
          for v in var:
            with ops.colocate_with(v):
              slot_var = tf.Variable(
                  initial_value=tf.compat.v1.zeros_like(v.initialized_value(),
                                                        tf.dtypes.float32),
                  name=v.op.name + '_unshrunk')
              var_list.append(slot_var)
          self._slots['unshrunk_' + name].append(var_list)
        else:
          with tf.compat.v1.device(var.device):
            self._slots['unshrunk_' + name].append(
                tf.Variable(
                    tf.compat.v1.zeros_like(var.initialized_value(),
                                            tf.dtypes.float32),
                    name=var.op.name + '_unshrunk'))

  def _assert_specified(self, items, check_in):
    for x in items:
      if check_in[x] is None:
        raise ValueError(check_in[x] + ' must be specified.')

  def _assert_list(self, items, check_in):
    for x in items:
      if not isinstance(check_in[x], list):
        raise ValueError(x + ' must be a list.')

  def _var_to_list(self, var):
    """Wraps var in a list if it is not a list or PartitionedVariable."""
    if not isinstance(var, (list, var_ops.PartitionedVariable)):
      var = [var]
    return var

  def _l1_loss(self):
    """Computes the (un-normalized) l1 loss of the model."""
    with name_scope('sdca/l1_loss'):
      sums = []
      for name in ['sparse_features_weights', 'dense_features_weights']:
        for var in self._variables[name]:
          for v in self._var_to_list(var):
            weights = internal_convert_to_tensor(v)
            with tf.compat.v1.device(weights.device):
              sums.append(
                  tf.math.reduce_sum(
                      tf.math.abs(tf.cast(weights, tf.dtypes.float64))))
      # SDCA L1 regularization cost is: l1 * sum(|weights|)
      return self._symmetric_l1_regularization() * tf.math.add_n(sums)

  def _l2_loss(self):
    """Computes the (un-normalized) l2 loss of the model."""
    with name_scope('sdca/l2_loss'):
      sums = []
      for name in ['sparse_features_weights', 'dense_features_weights']:
        for var in self._variables[name]:
          for v in self._var_to_list(var):
            weights = internal_convert_to_tensor(v)
            with tf.compat.v1.device(weights.device):
              sums.append(
                  tf.math.reduce_sum(
                      tf.math.square(tf.cast(weights, tf.dtypes.float64))))
      # SDCA L2 regularization cost is: l2 * sum(weights^2) / 2
      return self._symmetric_l2_regularization() * tf.math.add_n(sums) / 2.0

  def _convert_n_to_tensor(self, input_list, as_ref=False):
    """Converts input list to a set of tensors."""
    # input_list can be a list of Variables (that are implicitly partitioned),
    # in which case the underlying logic in internal_convert_to_tensor will not
    # concatenate the partitions together.  This method takes care of the
    # concatenating (we only allow partitioning on the first axis).
    output_list = []
    for x in input_list:
      tensor_to_convert = x
      if isinstance(x, list) or isinstance(x, var_ops.PartitionedVariable):
        # We only allow for partitioning on the first axis.
        tensor_to_convert = tf.concat(x, axis=0)
      output_list.append(
          internal_convert_to_tensor(tensor_to_convert, as_ref=as_ref))
    return output_list

  def _get_first_dimension_size_statically(self, w, num_partitions):
    """Compute the static size of the first dimension for a sharded variable."""
    dim_0_size = w[0].get_shape()[0]
    for p in range(1, num_partitions):
      dim_0_size += w[p].get_shape()[0]
    return dim_0_size

  def _linear_predictions(self, examples):
    """Returns predictions of the form w*x.

    Args:
      examples: Examples to compute predictions on.
    """
    with name_scope('sdca/prediction'):
      batch_size = tf.compat.v1.shape(examples['example_ids'])[0]

      predictions = tf.zeros([batch_size])
      sparse_variables = self._convert_n_to_tensor(
          self._variables['sparse_features_weights'])
      for sfc, sv in zip(examples['sparse_features'], sparse_variables):
        unpadded_dot_product = tf.math.segment_sum(
            tf.math.multiply(
                tf.compat.v1.gather(sv, sfc.feature_indices),
                sfc.feature_values), sfc.example_indices)
        predictions += tf.compat.v1.pad(
            unpadded_dot_product,
            [[0, batch_size - tf.compat.v1.shape(unpadded_dot_product)[0]]])

      dense_features = self._convert_n_to_tensor(examples['dense_features'])
      dense_variables = self._convert_n_to_tensor(
          self._variables['dense_features_weights'])
      for i in range(len(dense_variables)):
        predictions += tf.compat.v1.squeeze(
            tf.linalg.matmul(dense_features[i],
                             tf.compat.v1.expand_dims(dense_variables[i], -1)))

    return predictions

  def predictions(self, examples):
    """Add operations to compute predictions by the model.

    If logistic_loss is being used, predicted probabilities are returned.
    If poisson_loss is being used, predictions are exponentiated.
    Otherwise, (raw) linear predictions (w*x) are returned.

    Args:
      examples: Examples to compute predictions on.

    Returns:
      An Operation that computes the predictions for examples.

    Raises:
      ValueError: if examples are not well defined.
    """
    self._assert_specified(
        ['example_weights', 'sparse_features', 'dense_features'], examples)
    self._assert_list(['sparse_features', 'dense_features'], examples)

    result = self._linear_predictions(examples)
    if self._options['loss_type'] == 'logistic_loss':
      # Convert logits to probability for logistic loss predictions.
      with name_scope('sdca/logistic_prediction'):
        result = tf.math.sigmoid(result)
    elif self._options['loss_type'] == 'poisson_loss':
      # Exponeniate the prediction for poisson loss predictions.
      with name_scope('sdca/poisson_prediction'):
        result = tf.math.exp(result)
    return result

  def _get_partitioned_update_ops(self, v_num, num_partitions_by_var,
                                  p_assignments_by_var, gather_ids_by_var,
                                  weights, full_update, p_assignments,
                                  num_partitions):
    """Get updates for partitioned variables."""
    num_partitions = num_partitions_by_var[v_num]
    p_assignments = p_assignments_by_var[v_num]
    gather_ids = gather_ids_by_var[v_num]
    updates = tf.dynamic_partition(full_update, p_assignments, num_partitions)
    update_ops = []
    for p in range(num_partitions):
      with ops.colocate_with(weights[p]):
        result = tf.compat.v1.scatter_add(weights[p], gather_ids[p], updates[p])
      update_ops.append(result)
    return update_ops

  def minimize(self, global_step=None, name=None):
    """Add operations to train a linear model by minimizing the loss function.

    Args:
      global_step: Optional `Variable` to increment by one after the variables
        have been updated.
      name: Optional name for the returned operation.

    Returns:
      An Operation that updates the variables passed in the constructor.
    """
    # Technically, the op depends on a lot more than the variables,
    # but we'll keep the list short.
    with name_scope(name, 'sdca/minimize'):
      sparse_example_indices = []
      sparse_feature_indices = []
      sparse_features_values = []
      for sf in self._examples['sparse_features']:
        sparse_example_indices.append(sf.example_indices)
        sparse_feature_indices.append(sf.feature_indices)
        # If feature values are missing, sdca assumes a value of 1.0f.
        if sf.feature_values is not None:
          sparse_features_values.append(sf.feature_values)

      example_ids_hashed = tf.compat.v1.train.sdca_fprint(
          internal_convert_to_tensor(self._examples['example_ids']))
      example_state_data = self._hashtable.lookup(example_ids_hashed)
      # Solver returns example_state_update, new delta sparse_feature_weights
      # and delta dense_feature_weights.

      sparse_weights = []
      sparse_indices = []
      # If we have partitioned variables, keep a few dictionaries of Tensors
      # around that we need for the assign_add after the op call to
      # gen_sdca_ops.sdca_optimizer().  These are keyed because we may have a
      # mix of partitioned and un-partitioned variables.
      num_partitions_by_var = {}
      p_assignments_by_var = {}
      gather_ids_by_var = {}
      for v_num, (w, i) in enumerate(
          zip(self._slots['unshrunk_sparse_features_weights'],
              sparse_feature_indices)):
        # Append the sparse_indices (in full-variable space).
        sparse_idx = tf.cast(
            tf.unique(tf.cast(i, tf.dtypes.int32))[0], tf.dtypes.int64)
        sparse_indices.append(sparse_idx)
        if isinstance(w, list) or isinstance(w, var_ops.PartitionedVariable):
          num_partitions = len(w)
          flat_ids = tf.reshape(sparse_idx, [-1])
          # We use div partitioning, which is easiest to support downstream.
          # Compute num_total_ids as the sum of dim-0 of w, then assign
          # to partitions based on a constant number of ids per partition.
          # Optimize if we already know the full shape statically.
          dim_0_size = self._get_first_dimension_size_statically(
              w, num_partitions)

          if tf.compat.dimension_value(dim_0_size):
            num_total_ids = tf.constant(
                tf.compat.dimension_value(dim_0_size), flat_ids.dtype)
          else:
            dim_0_sizes = []
            for p in range(num_partitions):
              if tf.compat.dimension_value(w[p].shape[0]) is not None:
                dim_0_sizes.append(tf.compat.dimension_value(w[p].shape[0]))
              else:
                with ops.colocate_with(w[p]):
                  dim_0_sizes.append(tf.compat.v1.shape(w[p])[0])
            num_total_ids = tf.math.reduce_sum(
                tf.cast(tf.stack(dim_0_sizes), flat_ids.dtype))
          ids_per_partition = num_total_ids // num_partitions
          extras = num_total_ids % num_partitions

          p_assignments = tf.math.maximum(flat_ids // (ids_per_partition + 1),
                                          (flat_ids - extras) //
                                          ids_per_partition)

          # Emulate a conditional using a boolean indicator tensor
          new_ids = tf.where(p_assignments < extras,
                             flat_ids % (ids_per_partition + 1),
                             (flat_ids - extras) % ids_per_partition)

          # Cast partition assignments to int32 for use in dynamic_partition.
          # There really should not be more than 2^32 partitions.
          p_assignments = tf.cast(p_assignments, tf.dtypes.int32)
          # Partition list of ids based on assignments into num_partitions
          # separate lists.
          gather_ids = tf.dynamic_partition(new_ids, p_assignments,
                                            num_partitions)
          # Add these into the dictionaries for use in the later update.
          num_partitions_by_var[v_num] = num_partitions
          p_assignments_by_var[v_num] = p_assignments
          gather_ids_by_var[v_num] = gather_ids

          # Gather the weights from each partition.
          partition_gathered_weights = []
          for p in range(num_partitions):
            with ops.colocate_with(w[p]):
              partition_gathered_weights.append(
                  tf.compat.v1.gather(w[p], gather_ids[p]))

          # Stitch the weights back together in the same order they were before
          # we dynamic_partitioned them.
          condition_indices = tf.dynamic_partition(
              tf.range(tf.compat.v1.shape(new_ids)[0]), p_assignments,
              num_partitions)
          batch_gathered_weights = tf.dynamic_stitch(
              condition_indices, partition_gathered_weights)
        else:
          w_as_tensor = internal_convert_to_tensor(w)
          with tf.compat.v1.device(w_as_tensor.device):
            batch_gathered_weights = tf.compat.v1.gather(
                w_as_tensor, sparse_idx)
        sparse_weights.append(batch_gathered_weights)

      if tf.compat.forward_compatible(year=2018, month=10, day=30):
        esu, sfw, dfw = gen_sdca_ops.sdca_optimizer_v2(
            sparse_example_indices,
            sparse_feature_indices,
            sparse_features_values,
            self._convert_n_to_tensor(self._examples['dense_features']),
            internal_convert_to_tensor(self._examples['example_weights']),
            internal_convert_to_tensor(self._examples['example_labels']),
            sparse_indices,
            sparse_weights,
            self._convert_n_to_tensor(
                self._slots['unshrunk_dense_features_weights']),
            example_state_data,
            loss_type=self._options['loss_type'],
            l1=self._symmetric_l1_regularization(),
            l2=self._symmetric_l2_regularization(),
            num_loss_partitions=self._num_loss_partitions(),
            num_inner_iterations=1,
            adaptive=self._adaptive())
      else:
        esu, sfw, dfw = tf.compat.v1.train.sdca_optimizer(
            sparse_example_indices,
            sparse_feature_indices,
            sparse_features_values,
            self._convert_n_to_tensor(self._examples['dense_features']),
            internal_convert_to_tensor(self._examples['example_weights']),
            internal_convert_to_tensor(self._examples['example_labels']),
            sparse_indices,
            sparse_weights,
            self._convert_n_to_tensor(
                self._slots['unshrunk_dense_features_weights']),
            example_state_data,
            loss_type=self._options['loss_type'],
            l1=self._symmetric_l1_regularization(),
            l2=self._symmetric_l2_regularization(),
            num_loss_partitions=self._num_loss_partitions(),
            num_inner_iterations=1,
            adaptative=self._adaptive())

      with tf.control_dependencies([esu]):
        update_ops = [self._hashtable.insert(example_ids_hashed, esu)]
        # Update the weights before the proximal step.
        for v_num, (w, i, u) in enumerate(
            zip(self._slots['unshrunk_sparse_features_weights'], sparse_indices,
                sfw)):
          if (isinstance(w, var_ops.PartitionedVariable) or
              isinstance(w, list)):
            update_ops += self._get_partitioned_update_ops(
                v_num, num_partitions_by_var, p_assignments_by_var,
                gather_ids_by_var, w, u, p_assignments, num_partitions)
          else:
            update_ops.append(tf.compat.v1.scatter_add(w, i, u))
        for w, u in zip(self._slots['unshrunk_dense_features_weights'], dfw):
          if (isinstance(w, var_ops.PartitionedVariable) or
              isinstance(w, list)):
            split_updates = tf.split(
                u, num_or_size_splits=[v.shape.as_list()[0] for v in w])
            for v, split_update in zip(w, split_updates):
              update_ops.append(tf.compat.v1.assign_add(v, split_update))
          else:
            update_ops.append(tf.compat.v1.assign_add(w, u))
      if global_step is None:
        return tf.group(*update_ops)
      with tf.control_dependencies(update_ops):
        return tf.compat.v1.assign_add(global_step, 1, name=name).op

  def update_weights(self, train_op):
    """Updates the model weights.

    This function must be called on at least one worker after `minimize`.
    In distributed training this call can be omitted on non-chief workers to
    speed up training.

    Args:
      train_op: The operation returned by the `minimize` call.

    Returns:
      An Operation that updates the model weights.
    """
    with tf.control_dependencies([train_op]):
      update_ops = []
      # Copy over unshrunk weights to user provided variables.
      for name in ['sparse_features_weights', 'dense_features_weights']:
        for var, slot_var in zip(self._variables[name],
                                 self._slots['unshrunk_' + name]):
          for v, sv in zip(self._var_to_list(var), self._var_to_list(slot_var)):
            update_ops.append(v.assign(sv))

    # Apply proximal step.
    if self._symmetric_l1_regularization() > 0:
      shrinkage = (
          self._symmetric_l1_regularization() /
          self._symmetric_l2_regularization())
      with tf.control_dependencies(update_ops):
        update_ops = []
        for name in ['sparse_features_weights', 'dense_features_weights']:
          for var in self._variables[name]:
            for v in self._var_to_list(var):
              with tf.compat.v1.device(v.device):
                v_shrunk = tf.math.sign(v) * tf.math.maximum(
                    0.0,
                    tf.math.abs(v) - shrinkage)
                update_ops.append(v.assign(v_shrunk))
        return tf.group(*update_ops)
    else:
      return tf.group(*update_ops)

  def approximate_duality_gap(self):
    """Add operations to compute the approximate duality gap.

    Returns:
      An Operation that computes the approximate duality gap over all
      examples.
    """
    with name_scope('sdca/approximate_duality_gap'):
      _, values_list = self._hashtable.export_sharded()
      shard_sums = []
      for values in values_list:
        with tf.compat.v1.device(values.device):
          # For large tables to_double() below allocates a large temporary
          # tensor that is freed once the sum operation completes. To reduce
          # peak memory usage in cases where we have multiple large tables on a
          # single device, we serialize these operations.
          # Note that we need double precision to get accurate results.
          with tf.control_dependencies(shard_sums):
            shard_sums.append(
                tf.math.reduce_sum(tf.cast(values, dtype=tf.dtypes.float64), 0))
      summed_values = tf.math.add_n(shard_sums)

      primal_loss = summed_values[1]
      dual_loss = summed_values[2]
      example_weights = summed_values[3]
      # Note: we return NaN if there are no weights or all weights are 0, e.g.
      # if no examples have been processed
      return (primal_loss + dual_loss + self._l1_loss() +
              (2.0 * self._l2_loss())) / example_weights

  def unregularized_loss(self, examples):
    """Add operations to compute the loss (without the regularization loss).

    Args:
      examples: Examples to compute unregularized loss on.

    Returns:
      An Operation that computes mean (unregularized) loss for given set of
      examples.

    Raises:
      ValueError: if examples are not well defined.
    """
    self._assert_specified([
        'example_labels', 'example_weights', 'sparse_features', 'dense_features'
    ], examples)
    self._assert_list(['sparse_features', 'dense_features'], examples)
    with name_scope('sdca/unregularized_loss'):
      predictions = tf.cast(
          self._linear_predictions(examples), tf.dtypes.float64)
      labels = tf.cast(
          internal_convert_to_tensor(examples['example_labels']),
          tf.dtypes.float64)
      weights = tf.cast(
          internal_convert_to_tensor(examples['example_weights']),
          tf.dtypes.float64)

      if self._options['loss_type'] == 'logistic_loss':
        return tf.math.reduce_sum(
            tf.math.multiply(
                sigmoid_cross_entropy_with_logits(
                    labels=labels, logits=predictions),
                weights)) / tf.math.reduce_sum(weights)

      if self._options['loss_type'] == 'poisson_loss':
        return tf.math.reduce_sum(
            tf.math.multiply(
                log_poisson_loss(targets=labels, log_input=predictions),
                weights)) / tf.math.reduce_sum(weights)

      if self._options['loss_type'] in ['hinge_loss', 'smooth_hinge_loss']:
        # hinge_loss = max{0, 1 - y_i w*x} where y_i \in {-1, 1}. So, we need to
        # first convert 0/1 labels into -1/1 labels.
        all_ones = tf.compat.v1.ones_like(predictions)
        adjusted_labels = tf.math.subtract(2 * labels, all_ones)
        # Tensor that contains (unweighted) error (hinge loss) per
        # example.
        error = tf.nn.relu(
            tf.math.subtract(all_ones,
                             tf.math.multiply(adjusted_labels, predictions)))
        weighted_error = tf.math.multiply(error, weights)
        return tf.math.reduce_sum(weighted_error) / tf.math.reduce_sum(weights)

      # squared loss
      err = tf.math.subtract(labels, predictions)

      weighted_squared_err = tf.math.multiply(tf.math.square(err), weights)
      # SDCA squared loss function is sum(err^2) / (2*sum(weights))
      return (tf.math.reduce_sum(weighted_squared_err) /
              (2.0 * tf.math.reduce_sum(weights)))

  def regularized_loss(self, examples):
    """Add operations to compute the loss with regularization loss included.

    Args:
      examples: Examples to compute loss on.

    Returns:
      An Operation that computes mean (regularized) loss for given set of
      examples.
    Raises:
      ValueError: if examples are not well defined.
    """
    self._assert_specified([
        'example_labels', 'example_weights', 'sparse_features', 'dense_features'
    ], examples)
    self._assert_list(['sparse_features', 'dense_features'], examples)
    with name_scope('sdca/regularized_loss'):
      weights = internal_convert_to_tensor(examples['example_weights'])
      return ((self._l1_loss() + self._l2_loss()) /
              tf.math.reduce_sum(tf.cast(weights, tf.dtypes.float64)) +
              self.unregularized_loss(examples))


text:
package org.cfeclipse.cfml.editors.actions;

import org.cfeclipse.cfml.editors.CFMLEditor;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorActionDelegate;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.texteditor.ITextEditor;

/**
 * @author Matt
 * Class to find the matching bracker for the selected/highlighted
 *         bracket.
 */
public class FindBracketAction implements IWorkbenchWindowActionDelegate,IEditorActionDelegate
{
	private CFMLEditor editor;

	public FindBracketAction()
	{
		editor = null;
	}

	/*
	 * Sets the active editor, which appears to tell my action what to actually
	 * act upon.
	 *
	 * @see org.eclipse.ui.IEditorActionDelegate#setActiveEditor(org.eclipse.jface.action.IAction,
	 *      org.eclipse.ui.IEditorPart)
	 */
	public void setActiveEditor(IAction action, IEditorPart targetEditor)
	{
		if (targetEditor instanceof CFMLEditor)
		{
			editor = (CFMLEditor) targetEditor;
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	public void run(IAction action)
	{
//		get the document and selection and pass it to the word manipulator
		//so it can extract and rewrite what we want (super class)
		IDocument doc =  editor.getDocumentProvider().getDocument(editor.getEditorInput());
		ITextSelection sel = (ITextSelection)editor.getSelectionProvider().getSelection();
		this.findBracket(doc,sel);

	}

	public void findBracket(IDocument doc, ITextSelection sel)
	{
		try
		{
			if(!sel.isEmpty() && !(sel.getLength()==0) )
			{
				int offset = sel.getOffset();
				int len  = sel.getLength();
				int iterator = 0;
				String searchingFor = "";

				//search forwards if it's a left bracket, backwards for right brackets
				if( doc.get(offset,len).equals("(") )
				{
					iterator = 1;
					searchingFor = ")";
				}
				else if( doc.get(offset,len).equals(")"))
				{
					iterator = -1;
					searchingFor = "(";
				}
				boolean found = false;
				//do a search in the appropriate direction for a matching bracket
				//TODO: need to implement a stack-based checking to ensure we get the
				//*right* bracket
				for( int bracketOffset = offset; !found; bracketOffset += iterator )
				{
					if( doc.get(bracketOffset,1).equals(searchingFor) )
					{

						//doc.replace(bracketOffset,1,"a"+doc.get(bracketOffset,1) );
						//editor.setHighlightRange(bracketOffset,1,false);
						editor.selectAndReveal(bracketOffset,1);

						//editor.se

						editor.selectAndReveal(offset,1);
						found = true;
					}
				}

			}
		}
		catch(BadLocationException e)
		{
			e.printStackTrace(System.err);
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction,
	 *      org.eclipse.jface.viewers.ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection){
		if(editor != null){
			setActiveEditor(null,  editor.getSite().getPage().getActiveEditor());
		}
	}

	public void dispose() {
		// TODO Auto-generated method stub

	}

	public void init(IWorkbenchWindow window) {
		IEditorPart activeEditor = window.getActivePage().getActiveEditor();
		if(activeEditor instanceof CFMLEditor){
			editor = (CFMLEditor)activeEditor;
		}

	}
}


text:
using System.Linq;
using Moq;
using NUnit.Framework;
using Pustota.Maven.Actions;
using Pustota.Maven.Models;
using Pustota.Maven.Serialization.Data;

namespace Pustota.Maven.Base.Tests.Actions
{
	[TestFixture]
	public class ApplyClassifierActionTests
	{
		[Test]
		public void TwoProjectsDependencyTest()
		{
			var projectA = new Project
			{
				GroupId = "group",
				ArtifactId = "a",
				Version = "1.0.0-SNAPSHOT".ToVersion()
            };

			var projectB = new Project
			{
				GroupId = "group",
				ArtifactId = "b",
				Version = "1.0.1-SNAPSHOT".ToVersion()
            };

			projectB.Dependencies.Add(
				new Dependency
				{
					GroupId = "group",
					ArtifactId = "a",
					Version = "1.0.0-SNAPSHOT".ToVersion(),
                    Classifier = "${test}"
				}
				);

			var repo = new Mock<IProjectsRepository>();
			repo.SetupGet(r => r.AllProjects).Returns(new IProject[] { projectA, projectB });

			var action = new ApplyClassifierAction(repo.Object, "test", "Release");

			action.Execute();

			var dependency = projectB.Dependencies.Single();
			Assert.That(dependency.Classifier, Is.EqualTo("Release"));
		}

		[Test]
		public void ProjectWithProfileDependencyTest()
		{
			var projectA = new Project
			{
				GroupId = "group",
				ArtifactId = "a",
				Version = "1.0.0-SNAPSHOT".ToVersion()
            };
			projectA.Dependencies.Add(
				new Dependency
				{
					GroupId = "group",
					ArtifactId = "a",
					Version = "1.0.0-SNAPSHOT".ToVersion(),

                    Classifier = "${test}"
				}
				);
			var profile = new Profile();
			profile.Dependencies.Add(new Dependency
			{
				GroupId = "group",
				ArtifactId = "a",
				Version = "1.0.0-SNAPSHOT".ToVersion(),
				Classifier = "${test}"
			}
			);

			projectA.Profiles.Add(profile);

			var repo = new Mock<IProjectsRepository>();
			repo.SetupGet(r => r.AllProjects).Returns(new IProject[] { projectA });

			var action = new ApplyClassifierAction(repo.Object, "test", "Release");

			action.Execute();

			var dependency = projectA.Dependencies.Single();
			Assert.That(dependency.Classifier, Is.EqualTo("Release"));

			var dependency2 = projectA.Profiles.Single().Dependencies.Single();
			Assert.That(dependency2.Classifier, Is.EqualTo("Release"));
		}

		[Test]
		public void SearchProjectsDependencyClassifierTest()
		{
			var projectA = new Project
			{
				GroupId = "group",
				ArtifactId = "a",
				Version = "1.0.0-SNAPSHOT".ToVersion()
            };

			var projectB = new Project
			{
				GroupId = "group",
				ArtifactId = "b",
				Version = "1.0.1-SNAPSHOT".ToVersion()
            };

			projectB.Dependencies.Add(
				new Dependency
				{
					GroupId = "group",
					ArtifactId = "a",
					Version = "1.0.0-SNAPSHOT".ToVersion(),
					Classifier = "${test}-suffix"
				}
				);

			var repo = new Mock<IProjectsRepository>();
			repo.SetupGet(r => r.AllProjects).Returns(new IProject[] { projectA, projectB });

			var action = new ApplyClassifierAction(repo.Object, "test", "Release");

			action.Execute();

			var dependency = projectB.Dependencies.Single();
			Assert.That(dependency.Classifier, Is.EqualTo("Release-suffix"));
		}
	}
}


text:
<?php namespace Anomaly\Streams\Platform\Ui\Table\Component\Column;

use Anomaly\Streams\Platform\Ui\Table\TableBuilder;

/**
 * Class ColumnNormalizer
 *
 * @link   http://pyrocms.com/
 * @author PyroCMS, Inc. <support@pyrocms.com>
 * @author Ryan Thompson <ryan@pyrocms.com>
 */
class ColumnNormalizer
{

    /**
     * Normalize the column input.
     *
     * @param TableBuilder $builder
     */
    public function normalize(TableBuilder $builder)
    {
        $columns = $builder->getColumns();

        foreach ($columns as $key => &$column) {

            /*
             * If the key is non-numerical then
             * use it as the header and use the
             * column as the column if it's a class.
             */
            if (!is_numeric($key) && !is_array($column) && class_exists($column)) {
                $column = [
                    'heading' => $key,
                    'column'  => $column,
                ];
            }

            /*
             * If the key is non-numerical then
             * use it as the header and use the
             * column as the value.
             */
            if (!is_numeric($key) && !is_array($column) && !class_exists($column)) {
                $column = [
                    'heading' => $key,
                    'value'   => $column,
                ];
            }

            /*
             * If the column is not already an
             * array then treat it as the value.
             */
            if (!is_array($column)) {
                $column = [
                    'value' => $column,
                ];
            }

            /*
             * If the key is non-numerical and
             * the column is an array without
             * a heading then use the key.
             */
            if (!is_numeric($key) && is_array($column) && !array_has($column, 'field')) {
                $column['field'] = $key;
            }

            /*
             * If the key is non-numerical and
             * the column is an array without
             * a value then use the key.
             */
            if (!is_numeric($key) && is_array($column) && !isset($column['value'])) {
                $column['value'] = $key;
            }

            /*
             * If no value wrap is set
             * then use a default.
             */
            array_set($column, 'wrapper', array_get($column, 'wrapper', '{value}'));

            /*
             * If there is no value then use NULL
             */
            array_set($column, 'value', array_get($column, 'value', null));
        }

        $builder->setColumns($columns);
    }
}


text:
// @flow
/* global SETTINGS:false */
import React from "react"

import { TOUCHSTONE_URL } from "../../lib/url"

type Props = {
  next?: string
}

const TouchstoneLoginButton = ({ next }: Props) => (
  <a
    className="link-button outlined touchstone-text-logo"
    href={next ? `${TOUCHSTONE_URL}&next=${next}` : TOUCHSTONE_URL}
  >
    Touchstone
    @
    MIT

)

export default TouchstoneLoginButton


text:
package types

import (
	"github.com/containous/mux"
)

// InternalRouter router used by server to register internal routes (/api, /ping ...)
type InternalRouter interface {
	AddRoutes(systemRouter *mux.Router)
}


text:
/*
 *  Error helpers
 */

#include "duk_internal.h"

/*
 *  Get prototype object for an integer error code.
 */

duk_hobject *duk_error_prototype_from_code(duk_hthread *thr, int err_code) {
	switch (err_code) {
	case DUK_ERR_EVAL_ERROR:
		return thr->builtins[DUK_BIDX_EVAL_ERROR_PROTOTYPE];
	case DUK_ERR_RANGE_ERROR:
		return thr->builtins[DUK_BIDX_RANGE_ERROR_PROTOTYPE];
	case DUK_ERR_REFERENCE_ERROR:
		return thr->builtins[DUK_BIDX_REFERENCE_ERROR_PROTOTYPE];
	case DUK_ERR_SYNTAX_ERROR:
		return thr->builtins[DUK_BIDX_SYNTAX_ERROR_PROTOTYPE];
	case DUK_ERR_TYPE_ERROR:
		return thr->builtins[DUK_BIDX_TYPE_ERROR_PROTOTYPE];
	case DUK_ERR_URI_ERROR:
		return thr->builtins[DUK_BIDX_URI_ERROR_PROTOTYPE];

	/* XXX: more specific error classes? */
	case DUK_ERR_UNIMPLEMENTED_ERROR:
	case DUK_ERR_INTERNAL_ERROR:
	case DUK_ERR_ALLOC_ERROR:
	case DUK_ERR_ASSERTION_ERROR:
	case DUK_ERR_API_ERROR:
	case DUK_ERR_ERROR:
	default:
		return thr->builtins[DUK_BIDX_ERROR_PROTOTYPE];
	}
}

/*
 *  Exposed helper for setting up heap longjmp state.
 */

void duk_err_setup_heap_ljstate(duk_hthread *thr, int lj_type) {
	duk_tval tv_tmp;

	thr->heap->lj.type = lj_type;

	DUK_ASSERT(thr->valstack_top > thr->valstack);
	DUK_TVAL_SET_TVAL(&tv_tmp, &thr->heap->lj.value1);
	DUK_TVAL_SET_TVAL(&thr->heap->lj.value1, thr->valstack_top - 1);
	DUK_TVAL_INCREF(thr, &thr->heap->lj.value1);
	DUK_TVAL_DECREF(thr, &tv_tmp);

	duk_pop((duk_context *) thr);
}


text:
default['putty']['version']      = "0.62"
default['putty']['url']          = "http://the.earth.li/~sgtatham/putty/#{default['putty']['version']}/x86/putty-#{default['putty']['version']}-installer.exe"
default['putty']['package_name'] = "PuTTY version #{default['putty']['version']}"

default['putty']['home']    = "#{ENV['SYSTEMDRIVE']}\\putty"


text:
sap.ui.define(['sap/ui/core/UIComponent'],
	function(UIComponent) {
	"use strict";

	var Component = UIComponent.extend("sap.ui.unified.sample.CalendarSingleDaySelection.Component", {

		metadata : {
			rootView : "sap.ui.unified.sample.CalendarSingleDaySelection.CalendarSingleDaySelection",
			dependencies : {
				libs : [
					"sap.ui.unified"
				]
			},
			includes: ["../style.css"],
			config : {
				sample : {
					files : [
						"CalendarSingleDaySelection.view.xml",
						"CalendarSingleDaySelection.controller.js"
					]
				}
			}
		}
	});

	return Component;

});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Can. J. Bot. 47(12): 2035 (1970)

#### Original name
Podospora pistillata Mirza & Cain

### Remarks
null


text:
/* stats.c:  expose traffic server stats over http
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#include <limits.h>
#include <ts/ts.h>
#include <string.h>
#include <inttypes.h>
#include <getopt.h>

#include "tscore/ink_defs.h"

#define PLUGIN_NAME "stats_over_http"

/* global holding the path used for access to this JSON data */
static const char *url_path = "_stats";
static int url_path_len;

static bool integer_counters = false;
static bool wrap_counters    = false;

typedef struct stats_state_t {
  TSVConn net_vc;
  TSVIO read_vio;
  TSVIO write_vio;

  TSIOBuffer req_buffer;
  TSIOBuffer resp_buffer;
  TSIOBufferReader resp_reader;

  int output_bytes;
  int body_written;
} stats_state;

static void
stats_cleanup(TSCont contp, stats_state *my_state)
{
  if (my_state->req_buffer) {
    TSIOBufferDestroy(my_state->req_buffer);
    my_state->req_buffer = NULL;
  }

  if (my_state->resp_buffer) {
    TSIOBufferDestroy(my_state->resp_buffer);
    my_state->resp_buffer = NULL;
  }
  TSVConnClose(my_state->net_vc);
  TSfree(my_state);
  TSContDestroy(contp);
}

static void
stats_process_accept(TSCont contp, stats_state *my_state)
{
  my_state->req_buffer  = TSIOBufferCreate();
  my_state->resp_buffer = TSIOBufferCreate();
  my_state->resp_reader = TSIOBufferReaderAlloc(my_state->resp_buffer);
  my_state->read_vio    = TSVConnRead(my_state->net_vc, contp, my_state->req_buffer, INT64_MAX);
}

static int
stats_add_data_to_resp_buffer(const char *s, stats_state *my_state)
{
  int s_len = strlen(s);

  TSIOBufferWrite(my_state->resp_buffer, s, s_len);

  return s_len;
}

static const char RESP_HEADER[] = "HTTP/1.0 200 Ok\r\nContent-Type: text/javascript\r\nCache-Control: no-cache\r\n\r\n";

static int
stats_add_resp_header(stats_state *my_state)
{
  return stats_add_data_to_resp_buffer(RESP_HEADER, my_state);
}

static void
stats_process_read(TSCont contp, TSEvent event, stats_state *my_state)
{
  TSDebug(PLUGIN_NAME, "stats_process_read(%d)", event);
  if (event == TS_EVENT_VCONN_READ_READY) {
    my_state->output_bytes = stats_add_resp_header(my_state);
    TSVConnShutdown(my_state->net_vc, 1, 0);
    my_state->write_vio = TSVConnWrite(my_state->net_vc, contp, my_state->resp_reader, INT64_MAX);
  } else if (event == TS_EVENT_ERROR) {
    TSError("[%s] stats_process_read: Received TS_EVENT_ERROR", PLUGIN_NAME);
  } else if (event == TS_EVENT_VCONN_EOS) {
    /* client may end the connection, simply return */
    return;
  } else if (event == TS_EVENT_NET_ACCEPT_FAILED) {
    TSError("[%s] stats_process_read: Received TS_EVENT_NET_ACCEPT_FAILED", PLUGIN_NAME);
  } else {
    printf("Unexpected Event %d\n", event);
    TSReleaseAssert(!"Unexpected Event");
  }
}

#define APPEND(a) my_state->output_bytes += stats_add_data_to_resp_buffer(a, my_state)
#define APPEND_STAT(a, fmt, v)                                                   \
  do {                                                                           \
    char b[256];                                                                 \
    if (snprintf(b, sizeof(b), "\"%s\": \"" fmt "\",\n", a, v) < (int)sizeof(b)) \
      APPEND(b);                                                                 \
  } while (0)
#define APPEND_STAT_NUMERIC(a, fmt, v)                                               \
  do {                                                                               \
    char b[256];                                                                     \
    if (integer_counters) {                                                          \
      if (snprintf(b, sizeof(b), "\"%s\": " fmt ",\n", a, v) < (int)sizeof(b)) {     \
        APPEND(b);                                                                   \
      }                                                                              \
    } else {                                                                         \
      if (snprintf(b, sizeof(b), "\"%s\": \"" fmt "\",\n", a, v) < (int)sizeof(b)) { \
        APPEND(b);                                                                   \
      }                                                                              \
    }                                                                                \
  } while (0)

// This wraps uint64_t values to the int64_t range to fit into a Java long. Java 8 has an unsigned long which
// can interoperate with a full uint64_t, but it's unlikely that much of the ecosystem supports that yet.
static uint64_t
wrap_unsigned_counter(uint64_t value)
{
  if (wrap_counters) {
    return (value > INT64_MAX) ? value % INT64_MAX : value;
  } else {
    return value;
  }
}

static void
json_out_stat(TSRecordType rec_type ATS_UNUSED, void *edata, int registered ATS_UNUSED, const char *name,
              TSRecordDataType data_type, TSRecordData *datum)
{
  stats_state *my_state = edata;

  switch (data_type) {
  case TS_RECORDDATATYPE_COUNTER:
    APPEND_STAT_NUMERIC(name, "%" PRIu64, wrap_unsigned_counter(datum->rec_counter));
    break;
  case TS_RECORDDATATYPE_INT:
    APPEND_STAT_NUMERIC(name, "%" PRIu64, wrap_unsigned_counter(datum->rec_int));
    break;
  case TS_RECORDDATATYPE_FLOAT:
    APPEND_STAT_NUMERIC(name, "%f", datum->rec_float);
    break;
  case TS_RECORDDATATYPE_STRING:
    APPEND_STAT(name, "%s", datum->rec_string);
    break;
  default:
    TSDebug(PLUGIN_NAME, "unknown type for %s: %d", name, data_type);
    break;
  }
}
static void
json_out_stats(stats_state *my_state)
{
  const char *version;
  APPEND("{ \"global\": {\n");

  TSRecordDump((TSRecordType)(TS_RECORDTYPE_PLUGIN | TS_RECORDTYPE_NODE | TS_RECORDTYPE_PROCESS), json_out_stat, my_state);
  version = TSTrafficServerVersionGet();
  APPEND("\"server\": \"");
  APPEND(version);
  APPEND("\"\n");
  APPEND("  }\n}\n");
}

static void
stats_process_write(TSCont contp, TSEvent event, stats_state *my_state)
{
  if (event == TS_EVENT_VCONN_WRITE_READY) {
    if (my_state->body_written == 0) {
      TSDebug(PLUGIN_NAME, "plugin adding response body");
      my_state->body_written = 1;
      json_out_stats(my_state);
      TSVIONBytesSet(my_state->write_vio, my_state->output_bytes);
    }
    TSVIOReenable(my_state->write_vio);
  } else if (TS_EVENT_VCONN_WRITE_COMPLETE) {
    stats_cleanup(contp, my_state);
  } else if (event == TS_EVENT_ERROR) {
    TSError("[%s] stats_process_write: Received TS_EVENT_ERROR", PLUGIN_NAME);
  } else {
    TSReleaseAssert(!"Unexpected Event");
  }
}

static int
stats_dostuff(TSCont contp, TSEvent event, void *edata)
{
  stats_state *my_state = TSContDataGet(contp);
  if (event == TS_EVENT_NET_ACCEPT) {
    my_state->net_vc = (TSVConn)edata;
    stats_process_accept(contp, my_state);
  } else if (edata == my_state->read_vio) {
    stats_process_read(contp, event, my_state);
  } else if (edata == my_state->write_vio) {
    stats_process_write(contp, event, my_state);
  } else {
    TSReleaseAssert(!"Unexpected Event");
  }
  return 0;
}

static int
stats_origin(TSCont contp ATS_UNUSED, TSEvent event ATS_UNUSED, void *edata)
{
  TSCont icontp;
  stats_state *my_state;
  TSHttpTxn txnp = (TSHttpTxn)edata;
  TSMBuffer reqp;
  TSMLoc hdr_loc = NULL, url_loc = NULL;
  TSEvent reenable = TS_EVENT_HTTP_CONTINUE;

  TSDebug(PLUGIN_NAME, "in the read stuff");

  if (TSHttpTxnClientReqGet(txnp, &reqp, &hdr_loc) != TS_SUCCESS) {
    goto cleanup;
  }

  if (TSHttpHdrUrlGet(reqp, hdr_loc, &url_loc) != TS_SUCCESS) {
    goto cleanup;
  }

  int path_len     = 0;
  const char *path = TSUrlPathGet(reqp, url_loc, &path_len);
  TSDebug(PLUGIN_NAME, "Path: %.*s", path_len, path);

  if (!(path_len != 0 && path_len == url_path_len && !memcmp(path, url_path, url_path_len))) {
    goto notforme;
  }

  TSSkipRemappingSet(txnp, 1); // not strictly necessary, but speed is everything these days

  /* This is us -- register our intercept */
  TSDebug(PLUGIN_NAME, "Intercepting request");

  icontp   = TSContCreate(stats_dostuff, TSMutexCreate());
  my_state = (stats_state *)TSmalloc(sizeof(*my_state));
  memset(my_state, 0, sizeof(*my_state));
  TSContDataSet(icontp, my_state);
  TSHttpTxnIntercept(icontp, txnp);
  goto cleanup;

notforme:

cleanup:
  if (url_loc) {
    TSHandleMLocRelease(reqp, hdr_loc, url_loc);
  }
  if (hdr_loc) {
    TSHandleMLocRelease(reqp, TS_NULL_MLOC, hdr_loc);
  }

  TSHttpTxnReenable(txnp, reenable);
  return 0;
}

void
TSPluginInit(int argc, const char *argv[])
{
  TSPluginRegistrationInfo info;

  static const char usage[]             = PLUGIN_NAME ".so [--integer-counters] [PATH]";
  static const struct option longopts[] = {{(char *)("integer-counters"), no_argument, NULL, 'i'},
                                           {(char *)("wrap-counters"), no_argument, NULL, 'w'},
                                           {NULL, 0, NULL, 0}};

  info.plugin_name   = PLUGIN_NAME;
  info.vendor_name   = "Apache Software Foundation";
  info.support_email = "dev@trafficserver.apache.org";

  if (TSPluginRegister(&info) != TS_SUCCESS) {
    TSError("[%s] registration failed", PLUGIN_NAME);
  }

  for (;;) {
    switch (getopt_long(argc, (char *const *)argv, "iw", longopts, NULL)) {
    case 'i':
      integer_counters = true;
      break;
    case 'w':
      wrap_counters = true;
      break;
    case -1:
      goto init;
    default:
      TSError("[%s] usage: %s", PLUGIN_NAME, usage);
    }
  }

init:
  argc -= optind;
  argv += optind;

  if (argc > 0) {
    url_path = TSstrdup(argv[0] + ('/' == argv[0][0] ? 1 : 0)); /* Skip leading / */
  }
  url_path_len = strlen(url_path);

  /* Create a continuation with a mutex as there is a shared global structure
     containing the headers to add */
  TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, TSContCreate(stats_origin, TSMutexCreate()));
  TSDebug(PLUGIN_NAME, "stats module registered");
}


text:
namespace Bookmarks.Web.RequestModels
{
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    using Data.Models;
    using Infrastructure.Mapping;

    public class BookmarkRequestModel : IMapFrom<Bookmark>
    {
        [Required]
        public string Title { get; set; }

        [Required]
        public string Url { get; set; }

        [Required]
        public WebSiteRequestModel Website { get; set; }

        public string Description { get; set; }

        public string SnapshotBase64String { get; set; }

        public IEnumerable<TagRequestModel> Tags { get; set; }
    }
}


text:
% preamble.tex

\usepackage{lmodern}

\usepackage{xeCJK}
\usetheme{CambridgeUS} % try Madrid, Pittsburgh
\usecolortheme{beaver}
\usefonttheme[]{serif} % try "professionalfonts"

\setbeamertemplate{itemize items}[default]
\setbeamertemplate{enumerate items}[default]

\usepackage{amsmath, amsfonts, latexsym, mathtools}
% \usepackage{fdsymbol} % for poker
\newcommand{\set}[1]{\{#1\}}
\DeclareMathOperator*{\argmin}{\arg\!\min}

\definecolor{bgcolor}{rgb}{0.95,0.95,0.92}

% colors
\newcommand{\red}[1]{\textcolor{red}{#1}}
\newcommand{\redoverlay}[2]{\textcolor<#2>{red}{#1}}
\newcommand{\green}[1]{\textcolor{green}{#1}}
\newcommand{\blue}[1]{\textcolor{blue}{#1}}
\newcommand{\blueoverlay}[2]{\textcolor<#2>{blue}{#1}}
\newcommand{\teal}[1]{\textcolor{teal}{#1}}
\newcommand{\purple}[1]{\textcolor{purple}{#1}}

% colorded box
\newcommand{\rbox}[1]{\red{\boxed{#1}}}
\newcommand{\gbox}[1]{\green{\boxed{#1}}}
\newcommand{\bbox}[1]{\blue{\boxed{#1}}}
\newcommand{\pbox}[1]{\purple{\boxed{#1}}}

\usepackage{pifont}
\usepackage{wasysym}

\newcommand{\cmark}{\green{\ding{51}}}
\newcommand{\xmark}{\red{\ding{55}}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% for fig without caption: #1: width/size; #2: fig file
\newcommand{\fig}[2]{
  \begin{figure}[htp]
    \centering
      \includegraphics[#1]{#2}
  \end{figure}
}

\usepackage{tikz}
\usetikzlibrary{positioning}
\usepackage{adjustbox}
% \resizebox{0.90\textwidth}{!}{\input{tikz/chain-intersection}}

\newcommand{\titletext}{1-13 Boolean Algebra}
\newcommand{\ps}[1]{\mathcal{P}(#1)}
\newcommand{\N}{\mathbb{N}}
\newcommand{\R}{\mathbb{R}}
\newcommand{\CP}{\mathbb{C}}

\newcommand{\thankyou}{
  \begin{frame}[noframenumbering]{}
    \fig{width = 0.50\textwidth}{figs/thankyou.png}
  \end{frame}
}


text:
Ordenar la actualizacion del documento <?php echo $documento['nombre_archivo'].' '.$documento['titulo'] ?>

 Documentos

Ordenar actualizacion documento

<form action="?c=documento&a=Guardar_Orden_Actualizacion" method="post" autocomplete="off" onsubmit="return confSubmit()">
    <input type="hidden" name="pkdocumento" class="form-control" value="<?php echo $documento['_id'] ?>">

                Titulo documento:
                <input type="text" class="form-control" value="<?php echo $documento['titulo'] ?>" readonly >

                Usuario responsable para la actualizacion:

                    <select class="parcmb" name="usuario" required>
                        <?php foreach ($usuarios as $u): ?>
                            <option value="<?php echo $u->pkusuario; ?>"><?php echo $u->nombre; ?></option>
                        <?php endforeach ?>
                    </select>

                Comentario

                    <textarea class="form-control" placeholder="Comentario" name="comentario" style="resize: vertical"></textarea>

        <button type="submit" class="btn btn-success btn-lg" id="guardar"> Guardar</button>

</form>


text:
package androidpath.ll.hackdemo;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

/**
 * Created by Le on 2015/11/10.
 */
public class BaseActivity extends AppCompatActivity {

    public static void actionStart(Context context, @Nullable String data1, @Nullable String data2, Class<?> classname) {
        Intent intent = new Intent(context, classname);
        if (data1 != null) {
            intent.putExtra("param1", data1);
        }
        if (data2 != null) {
            intent.putExtra("param2", data2);
        }
        context.startActivity(intent);
    }

    public static void actionStart(Context context, Class<?> classname) {
        actionStart(context, null, null, classname);
    }
}


text:
{-# LANGUAGE CPP                        #-}
{-# LANGUAGE DeriveDataTypeable         #-}
{-# LANGUAGE FlexibleContexts           #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MagicHash                  #-}
{-# LANGUAGE StandaloneDeriving         #-}
{-# LANGUAGE TemplateHaskell            #-}
{-# LANGUAGE TypeFamilies               #-}

#if __GLASGOW_HASKELL__ >= 706
{-# LANGUAGE DataKinds                  #-}
#endif

#if !MIN_VERSION_containers(0,5,8)
{-# OPTIONS_GHC -fno-warn-orphans #-}
#endif

{-|
Module:      Types
Copyright:   (C) 2015-2017 Ryan Scott
License:     BSD-style (see the file LICENSE)
Maintainer:  Ryan Scott

Data types for testing `lift-generics`' capabilities.
-}
module Types (
    PureQ, runPureQ
  , Unit(..)
  , Product(..)
  , Sum(..)
  , Const(..)
  , Ap(..)
  , p, s, u, c, z, w
#if MIN_VERSION_base(4,5,0)
  , Unit'(..)
  , Product'(..)
  , Sum'(..)
  , Const'(..)
  , Ap'(..)
  , p', s', u', c', z'
#endif
  ) where

import Data.Tree (Tree (..))
#if MIN_VERSION_base(4,5,0)
import Data.Typeable (Typeable)
#endif

import Control.Monad.State

import Generics.Deriving.TH (deriveAll)

import GHC.Exts

import Language.Haskell.TH.Lift.Generics
  ( genericLiftWithPkg
#if MIN_VERSION_base(4,5,0)
  , genericLift
#endif
#if MIN_VERSION_template_haskell(2,16,0)
  , genericLiftTypedCompatWithPkg
  , genericLiftTypedCompat
#endif
  )
import Language.Haskell.TH.Syntax hiding (newName)
import Language.Haskell.TH.Syntax.Compat

import Prelude ()
import Prelude.Compat

newtype PureQ a = MkPureQ (State Uniq a)
  deriving (Functor, Applicative, Monad, MonadState Uniq)

runPureQ :: PureQ a -> a
runPureQ m = case m of MkPureQ m' -> evalState m' 0

instance Quote PureQ where
  newName s = state $ \i -> (mkNameU s i, i + 1)

#if !MIN_VERSION_containers(0,5,8)
$(deriveAll ''Tree)
#endif

data Unit = Unit
  deriving (Eq, Ord, Show)
$(deriveAll ''Unit)

data Product a b c d = Product a b c d
  deriving (Eq, Ord, Show)
$(deriveAll ''Product)

data Sum a b = Inl a | Inr b
  deriving (Eq, Ord, Show)
$(deriveAll ''Sum)

newtype Const a b = Const a
  deriving (Eq, Ord, Show)
$(deriveAll ''Const)

newtype Ap f a = Ap (f a)
  deriving (Eq, Ord, Show)
$(deriveAll ''Ap)

data Unboxed a
   = Unboxed a
#if MIN_VERSION_template_haskell(2,11,0)
             Char#
#endif
             Double#
             Float#
             Int#
             Word#
  deriving (Eq, Ord, Show)
$(deriveAll ''Unboxed)

p :: Product Char Int Bool String
p = Product 'a' 1 True "b"

s :: Sum Char Int
s = Inl 'c'

u :: Unboxed Int
u = Unboxed 1
#if MIN_VERSION_template_haskell(2,11,0)
            '1'#
#endif
            1.0##
            1.0#
            1#
            1##

c :: Const Int a
c = Const 1

z :: Ap Maybe Int
z = Ap (Just 3)

w :: Tree Int
w = Node 3 [Node 4 [], Node 5 []]

#if MIN_VERSION_base(4,5,0)

-- The types below are essentially the same as the ones above.  However, we
-- give them genericLift-based instances rather than genericLiftWithPkg ones,
-- to ensure that the former work too.

data Unit' = Unit'
  deriving (Eq, Ord, Show, Typeable)
$(deriveAll ''Unit')

data Product' a b c d = Product' a b c d
  deriving (Eq, Ord, Show, Typeable)
$(deriveAll ''Product')

data Sum' a b = Inl' a | Inr' b
  deriving (Eq, Ord, Show, Typeable)
$(deriveAll ''Sum')

newtype Const' a b = Const' a
  deriving (Eq, Ord, Show, Typeable)
$(deriveAll ''Const')

newtype Ap' f a = Ap' (f a)
  deriving (Eq, Ord, Show)
#if __GLASGOW_HASKELL__ >= 708
deriving instance Typeable Ap'
#endif
$(deriveAll ''Ap')

data Unboxed' a
   = Unboxed' a
# if MIN_VERSION_template_haskell(2,11,0)
             Char#
# endif
             Double#
             Float#
             Int#
             Word#
  deriving (Eq, Ord, Show, Typeable)
$(deriveAll ''Unboxed')

p' :: Product' Char Int Bool String
p' = Product' 'a' 1 True "b"

s' :: Sum Char Int
s' = Inl 'c'

u' :: Unboxed' Int
u' = Unboxed' 1
# if MIN_VERSION_template_haskell(2,11,0)
            '1'#
# endif
            1.0##
            1.0#
            1#
            1##

c' :: Const' Int a
c' = Const' 1

z' :: Ap' Maybe Int
z' = Ap' (Just 3)
#endif

pkgKey :: String
pkgKey = "main"

instance Lift Unit where
    lift = genericLiftWithPkg pkgKey
#if MIN_VERSION_template_haskell(2,16,0)
    liftTyped = genericLiftTypedCompatWithPkg pkgKey
#endif

instance (Lift a, Lift b, Lift c, Lift d) => Lift (Product a b c d) where
    lift = genericLiftWithPkg pkgKey
#if MIN_VERSION_template_haskell(2,16,0)
    liftTyped = genericLiftTypedCompatWithPkg pkgKey
#endif

instance (Lift a, Lift b) => Lift (Sum a b) where
    lift = genericLiftWithPkg pkgKey
#if MIN_VERSION_template_haskell(2,16,0)
    liftTyped = genericLiftTypedCompatWithPkg pkgKey
#endif

instance Lift a => Lift (Unboxed a) where
    lift = genericLiftWithPkg pkgKey
#if MIN_VERSION_template_haskell(2,16,0)
    liftTyped = genericLiftTypedCompatWithPkg pkgKey
#endif

instance Lift a => Lift (Const a b) where
    lift = genericLiftWithPkg pkgKey
#if MIN_VERSION_template_haskell(2,16,0)
    liftTyped = genericLiftTypedCompatWithPkg pkgKey
#endif

instance Lift (f a) => Lift (Ap f a) where
    lift = genericLiftWithPkg pkgKey
#if MIN_VERSION_template_haskell(2,16,0)
    liftTyped = genericLiftTypedCompatWithPkg pkgKey
#endif

#if MIN_VERSION_base(4,5,0)

instance Lift Unit' where
    lift = genericLift
# if MIN_VERSION_template_haskell(2,16,0)
    liftTyped = genericLiftTypedCompat
# endif

instance (Lift a, Lift b, Lift c, Lift d) => Lift (Product' a b c d) where
    lift = genericLift
# if MIN_VERSION_template_haskell(2,16,0)
    liftTyped = genericLiftTypedCompat
# endif

instance (Lift a, Lift b) => Lift (Sum' a b) where
    lift = genericLift
# if MIN_VERSION_template_haskell(2,16,0)
    liftTyped = genericLiftTypedCompat
# endif

instance Lift a => Lift (Unboxed' a) where
    lift = genericLift
# if MIN_VERSION_template_haskell(2,16,0)
    liftTyped = genericLiftTypedCompat
# endif

-- This instance shows that we can have parametric polymorphism—we don't need
-- Typeable instances for @a@ or @b@.
instance Lift a => Lift (Const' a b) where
    lift = genericLift
# if MIN_VERSION_template_haskell(2,16,0)
    liftTyped = genericLiftTypedCompat
# endif

# if __GLASGOW_HASKELL__ >= 708
-- This instance demonstrates some polykindedness—the arguments to Ap' aren't
-- all of kind Type. This only works for GHC 7.8 and later.
instance Lift (f a) => Lift (Ap' f a) where
    lift = genericLift
#  if MIN_VERSION_template_haskell(2,16,0)
    liftTyped = genericLiftTypedCompat
#  endif
# endif
#endif


text:
<?php
namespace Topxia\Service\User\AuthProvider;

use Topxia\Service\Common\BaseService;

class PhpwindAuthProvider extends BaseService implements AuthProvider
{
    public function register($registration)
    {
        $api = $this->getWindidApi('user');

        $result = $api->register($registration['nickname'], $registration['email'], $registration['password']);
        if ($result < 1) {
            $result = $this->convertApiResult($result);
            throw new \RuntimeException("{$result[0]}:{$result[1]}");
        }

        $registration['id'] = $result;

        return $registration;
    }

    public function syncLogin($userId)
    {
        $api = $this->getWindidApi('user');
        return $api->synLogin($userId);
    }

    public function syncLogout($userId)
    {
        $api = $this->getWindidApi('user');
        return $api->synLogout($userId);
    }

    public function changeNickname($userId, $newName)
    {
        $api    = $this->getWindidApi('user');
        $result = $api->editUser($userId, null, array('username' => $newName));
        return $result == 1;
    }

    public function changeEmail($userId, $password, $newEmail)
    {
        $api    = $this->getWindidApi('user');
        $result = $api->editUser($userId, null, array('email' => $newEmail));
        return $result == 1;
    }

    public function changePassword($userId, $oldPassword, $newPassword)
    {
        $api    = $this->getWindidApi('user');
        $result = $api->editUser($userId, $oldPassword, array('password' => $newPassword));
        return $result == 1;
    }

    public function checkUsername($username)
    {
        $api = $this->getWindidApi('user');

        // 1: check username.
        $result = $api->checkUserInput($username, 1);

        return $this->convertApiResult($result);
    }

    public function checkEmail($email)
    {
        $api = $this->getWindidApi('user');

        // 1: check nickname.
        $result = $api->checkUserInput($email, 3);

        return $this->convertApiResult($result);
    }

    public function checkMobile($mobile)
    {
        return array('success', '');
    }

    public function checkPassword($userId, $password)
    {
        $api                    = $this->getWindidApi('user');
        list($result, $apiUser) = $api->login($userId, $password, 1);
        return $result == 1;
    }

    public function checkLoginById($userId, $password)
    {
        $api = $this->getWindidApi('user');

        list($result, $apiUser) = $api->login($userId, $password, 1);
        if ($result != 1) {
            return null;
        }

        return array(
            'id'          => $apiUser['uid'],
            'nickname'    => $apiUser['username'],
            'email'       => $apiUser['email'],
            'createdTime' => $apiUser['regdate'],
            'createdIp'   => $apiUser['regip']
        );
    }

    public function checkLoginByNickname($nickname, $password)
    {
        $api = $this->getWindidApi('user');

        list($result, $apiUser) = $api->login($nickname, $password, 2);
        if ($result != 1) {
            return null;
        }

        return array(
            'id'          => $apiUser['uid'],
            'nickname'    => $apiUser['username'],
            'email'       => $apiUser['email'],
            'createdTime' => $apiUser['regdate'],
            'createdIp'   => $apiUser['regip']
        );
    }

    public function checkLoginByEmail($email, $password)
    {
        $api = $this->getWindidApi('user');

        list($result, $apiUser) = $api->login($email, $password, 3);
        if ($result != 1) {
            return null;
        }

        return array(
            'id'          => $apiUser['uid'],
            'nickname'    => $apiUser['username'],
            'email'       => $apiUser['email'],
            'createdTime' => $apiUser['regdate'],
            'createdIp'   => $apiUser['regip']
        );
    }

    public function getAvatar($userId, $size = 'middle')
    {
        $api = $this->getWindidApi('avatar');
        $url = $api->getAvatar($userId, $size);

        if ($this->checkUrlExist($url)) {
            return $url;
        }

        return null;
    }

    public function getProviderName()
    {
        return 'phpwind';
    }

    protected function getWindidApi($name)
    {
        define('WEKIT_TIMESTAMP', time());
        require_once __DIR__.'/../../../../../vendor_user/windid_client/src/windid/WindidApi.php';
        return \WindidApi::api($name);
    }

    protected function convertApiResult($result)
    {
        switch ($result) {
            case \WindidError::SUCCESS:
                return array('success', '');
            case \WindidError::NAME_EMPTY:
                return array('error_empty_name', $this->getKernel()->trans('名称为空'));
            case \WindidError::NAME_LEN:
                return array('error_length_invalid', $this->getKernel()->trans('名称长度不符合'));
            case \WindidError::NAME_ILLEGAL_CHAR:
                return array('error_illegal_char', $this->getKernel()->trans('名称含有非法字符'));
            case \WindidError::NAME_FORBIDDENNAME:
                return array('error_forbidden_name', $this->getKernel()->trans('名称含有禁用字符'));
            case \WindidError::NAME_DUPLICATE:
                return array('error_duplicate', $this->getKernel()->trans('名称已被注册'));
            case \WindidError::EMAIL_EMPTY:
                return array('error_empty', $this->getKernel()->trans('Email为空为空'));
            case \WindidError::EMAIL_ILLEGAL:
                return array('error_illegal', $this->getKernel()->trans('Email格式不正确'));
            case \WindidError::EMAIL_WHITE_LIST:
                return array('error_white_list', $this->getKernel()->trans('Email不在白名单'));
            case \WindidError::EMAIL_BLACK_LIST:
                return array('error_black_list', $this->getKernel()->trans('Email处在黑名单'));
            case \WindidError::EMAIL_DUPLICATE:
                return array('error_duplicate', $this->getKernel()->trans('Email已存在'));
            case \WindidError::PASSWORD_LEN:
                return array('error_password_length_invalid', $this->getKernel()->trans('密码长度不符合'));
            case \WindidError::PASSWORD_ILLEGAL_CHAR:
                return array('error_password_illegal_char', $this->getKernel()->trans('密码含有非法字符'));
            case \WindidError::PASSWORD_ERROR:
                return array('error_password_error', $this->getKernel()->trans('原密码错误'));
            case \WindidError::FAIL:
            default:
                return array('error_unknown', $this->getKernel()->trans('未知错误'));
        }
    }

    public function checkUrlExist($url)
    {
        $headers = get_headers($url);
        return strpos($headers[0], ' 200 ') > 0;
    }

    public function checkConnect()
    {
        return true;
    }
}


text:
/**
 * Typings for https://github.com/freeall/progress-stream
 */
declare module "progress-stream" {
  interface ProgressStream extends NodeJS.ReadWriteStream {
    on(ev: "progress", cb: (info: ProgressInfo) => void): ProgressStream;
    on(ev: "error", cb: (err: Error) => void);
  }

  interface ProgressStreamOpts {
    length: number;
    time: number;
  }

  declare function makeStream(opts: ProgressStreamOpts): ProgressStream;
  export = makeStream;
}