text:
namespace omnibox {

const char kToggleSuggestionGroupIdOffHistogram[] =
    "Omnibox.ToggleSuggestionGroupId.Off";
const char kToggleSuggestionGroupIdOnHistogram[] =
    "Omnibox.ToggleSuggestionGroupId.On";

// A client-side toggle for document (Drive) suggestions.
// Also gated by a feature and server-side Admin Panel controls.
const char kDocumentSuggestEnabled[] = "documentsuggest.enabled";

// Enum specifying the active behavior for the intranet redirect detector.
// The browser pref kDNSInterceptionChecksEnabled also impacts the redirector.
// Values are defined in omnibox::IntranetRedirectorBehavior.
const char kIntranetRedirectBehavior[] = "browser.intranet_redirect_behavior";

// Boolean that controls whether scoped search mode can be triggered by <space>.
const char kKeywordSpaceTriggeringEnabled[] =
    "omnibox.keyword_space_triggering_enabled";

// Boolean that specifies whether the omnibox should display a lock icon for
// secure connections.
const char kLockIconInAddressBarEnabled[] =
    "omnibox.lock_icon_in_address_bar_enabled";

// A dictionary of visibility preferences for suggestion groups. The key is the
// suggestion group ID serialized as a string, and the value is
// SuggestionGroupVisibility serialized as an integer.
const char kSuggestionGroupVisibility[] = "omnibox.suggestionGroupVisibility";

// Boolean that specifies whether to always show full URLs in the omnibox.
const char kPreventUrlElisionsInOmnibox[] = "omnibox.prevent_url_elisions";

// A cache of zero suggest results using JSON serialized into a string.
const char kZeroSuggestCachedResults[] = "zerosuggest.cachedresults";

void RegisterProfilePrefs(PrefRegistrySimple* registry) {
  registry->RegisterDictionaryPref(kSuggestionGroupVisibility);
  registry->RegisterBooleanPref(
      kKeywordSpaceTriggeringEnabled, true,
      user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
}

SuggestionGroupVisibility GetUserPreferenceForSuggestionGroupVisibility(
    PrefService* prefs,
    int suggestion_group_id) {
  DCHECK(prefs);

  const base::Value* dictionary =
      prefs->GetDictionary(kSuggestionGroupVisibility);
  DCHECK(dictionary);

  absl::optional<int> value =
      dictionary->FindIntKey(base::NumberToString(suggestion_group_id));

  if (value == SuggestionGroupVisibility::HIDDEN ||
      value == SuggestionGroupVisibility::SHOWN) {
    return static_cast<SuggestionGroupVisibility>(*value);
  }

  return SuggestionGroupVisibility::DEFAULT;
}

void SetSuggestionGroupVisibility(PrefService* prefs,
                                  int suggestion_group_id,
                                  SuggestionGroupVisibility new_value) {
  DCHECK(prefs);

  DictionaryPrefUpdate update(prefs, kSuggestionGroupVisibility);
  update->SetIntKey(base::NumberToString(suggestion_group_id), new_value);

  base::SparseHistogram::FactoryGet(
      new_value == SuggestionGroupVisibility::SHOWN
          ? kToggleSuggestionGroupIdOnHistogram
          : kToggleSuggestionGroupIdOffHistogram,
      base::HistogramBase::kUmaTargetedHistogramFlag)
      ->Add(suggestion_group_id);
}

}  // namespace omnibox


text:
"""
    This wonderfull app permits to display boardgame scores and stats
"""
from __future__ import print_function

import argparse
import json
import os
import sys
import flask
import flask_login
from flask import Flask, jsonify, render_template, request

import scores.scores as scores
import scores.database as database
import scores.stats.stats_overall as s_overall
from mongokit.document import StructureError

THIS_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__)))

class Config(object):
    """A configuration class"""
    DEBUG = False
    TESTING = False
    FILE_URI = os.path.join(THIS_DIR, 'scores.yml')
    # ex: mongodb://<dbuser>:<dbpassword>@ds019664.mlab.com:19664/zesk06
    DATABASE_URI = 'mongodb://<dbuser>:<dbpassword>@<instance>.mlab.com:<port>/<dbname>'
    if 'DATABASE_URI' in os.environ:
        DATABASE_URI = os.environ['DATABASE_URI']

class DevelopmentConfig(Config):
    """The dev configuration"""
    DEBUG = True

class TestConfig(Config):
    """The test config"""
    TESTING = True
    FILE_URI = os.path.join(THIS_DIR, 'target/scores.yml')
    DATABASE_URI = 'mongodb://<dbuser>:<dbpassword>@<instance>.mlab.com:<port>/<dbname>_test'
    if 'TEST_DATABASE_URI' in os.environ:
        DATABASE_URI = os.environ['TEST_DATABASE_URI']

app = Flask(__name__)
app.config.from_object(Config)

# used by flask-login
app.secret_key = 'idontwanttobeinthepubliccode'
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"

app.database = None

def get_db():
    """Return the Database
    :rtype: scores.database.Database"""
    if app.database is None:
        print('connecting to %s' % app.config['DATABASE_URI'])
        app.database = database.Database(app.config['DATABASE_URI'])
    return app.database

@login_manager.user_loader
def user_loader(login_s):
    # retrieve user from database
    print('user_loader')
    db = get_db()
    user = db.get_user(login_s)
    return user

@login_manager.request_loader
def request_loader(mrequest):
    print('request loader')
    mlogin = mrequest.form.get('username')
    passwd = mrequest.form.get('pw')
    if mlogin and passwd:
        db = get_db()
        user = db.get_user(mlogin)
        if user:
            if not user.authenticate(passwd):
                print('wrong password for %s' % mlogin)
        else:
            print('user %s not found' % mlogin)
        return user

@app.route('/login', methods=['GET', 'POST'])
def login():
    if flask.request.method == 'GET':
        return '''
               <form action='login' method='POST'>
                <input type='text' name='username' id='username' placeholder='username'></input>
                <input type='password' name='pw' id='pw' placeholder='password'></input>
                <input type='submit' name='submit'></input>
               </form>
               '''

    login = request.form.get('username')
    password = request.form['pw']
    db = get_db()
    user = db.get_user(login)
    if user and user.authenticate(password):
        flask_login.login_user(user)
        flask.flash('Logged in successfully.')
        # what is the next page?
        next_url = flask.request.args.get('next')
        if not next_is_valid(next_url, authenticated=True):
            return flask.abort(400)
        return flask.redirect(next_url or flask.url_for('index'))
    return 'Bad login'

def next_is_valid(url, authenticated):
    """Return True if next page is valid
    """
    protected_urls = ('protected', )
    if url in protected_urls and not authenticated:
        return False
    return True

@app.route('/logout')
def logout():
    """To logout from the web app"""
    flask_login.logout_user()
    flask.flash('Logged out successfully.')
    # what is the next page?
    next_url = flask.request.args.get('next')
    if not next_is_valid(next_url, False):
        return flask.abort(400)

    return flask.redirect(next_url or flask.url_for('index'))

@app.route('/protected')
@flask_login.login_required
def protected():
    return 'Logged in as: ' + flask_login.current_user.id

@app.route('/')
def index():
    print('index')
    mscores = get_mscores()
    stats = s_overall.OverallWinnerStat()
    stats.parse(mscores)
    print('rendering')
    return render_template('base.html', title=u'GAME STATS', stats=stats)

def get_mscores():
    "returns the mscores"
    return scores.Scores(database=get_db())

@app.route('/api/v1/is_logged', methods=["GET"])
def is_logged():
    """
    :return: {"logged": "true"} if user is logged
    """

    return jsonify({"logged": True, "user_id": flask_login.current_user.get_id()})

@app.route('/api/v1/plays', methods=["POST"])
@flask_login.login_required
def add_play():
    """Adds a new play"""
    if 'Logged in as: ' + flask_login.current_user.get_id():
        play_json = request.json
        if request.json is None and request.data:
            play_json = request.data
        if play_json:
            try:
                # insert the created by information in play
                print('play_json is %s' % type(play_json))
                play_obj = play_json
                if isinstance(play_json, basestring):
                    play_obj = json.loads(play_json)
                play_obj['created_by'] = '%s' % flask_login.current_user.get_id()
                play_json = json.dumps(play_obj)
                #
                new_play = get_db().add_play_from_json(play_json)
                return jsonify(msg='added play %s' % new_play.id,
                               id=new_play.id,
                               data=new_play.to_json()), 201
            except StructureError, error:
                return jsonify('BAD JSON %s: %s' % (error, play_json)), 400
        else:
            return jsonify('Failed to find JSON data in your POST'), 404
    return jsonify('You must be logged in to add a play'), 401

@app.route('/api/v1/plays', methods=["GET"])
def get_plays():
    """
    : return: the plays
    """
    mscores = get_mscores()
    return jsonify([json.loads(play.to_json()) for play in mscores.plays])

@app.route('/api/v1/plays/<play_id>', methods=["GET"])
def get_play(play_id):
    """
    : return: the play with given ID
    """
    mscores = get_mscores()
    play = mscores.get_play(play_id)
    if play:
        return jsonify(json.loads(play.to_json()))
    return jsonify('Failed to find play with id %s' % play_id), 404

@app.route('/api/v1/plays/<play_id>/elos', methods=["GET"])
def get_play_elos(play_id):
    """
    : return: the elos of the play with given ID
    """
    stats = s_overall.OverallWinnerStat()
    stats.parse(get_mscores())
    elos_per_player = stats.elo_stats.get_elos_per_player(play_id)
    if elos_per_player:
        json_object = []
        for player_login, elos in elos_per_player.iteritems():
            json_object.append({
                "login": player_login,
                "elo_before": elos[0],
                "elo_after": elos[1],
                "elos": elos[1] - elos[0],
            })
        return jsonify(json_object)
    return jsonify('Failed to find elos of play with id %s' % play_id), 404

@app.route('/api/v1/plays/<play_id>', methods=["DELETE"])
@flask_login.login_required
def delete_play(play_id):
    """
    Delete the play with the given id
    :param play_id: The id of the play to delete
    """
    mscores = get_mscores()
    play = mscores.get_play(play_id)
    if play:
        if play.created_by == flask_login.current_user.get_id():
            play.delete()
            return jsonify(msg='play deleted id %s' % play_id, data=play.to_json()), 200
        else:
            msg = 'You can\'t delete play you did not create'
            return jsonify(msg=msg, data=play.to_json()), 403
    return jsonify('Failed to find play with id %s' % play_id), 404

@app.route('/api/v1/games', methods=["GET"])
def get_games():
    """Return the list of games"""
    stats = s_overall.OverallWinnerStat()
    stats.parse(get_mscores())
    return jsonify(sorted(list(stats.game_stats)))

@app.route('/api/v1/games/<string:game_id>', methods=["GET"])
def get_game(game_id):
    """
    : return: the game with given ID
    """
    stats = s_overall.OverallWinnerStat()
    stats.parse(get_mscores())
    if game_id in stats.game_stats:
        return jsonify(stats.game_stats[game_id].to_json())
    return jsonify('Failed to find game %s' % game_id), 404

@app.route('/api/v1/players', methods=["GET"])
def get_players():
    """
    : return: Get all player stats
    """
    stats = s_overall.OverallWinnerStat()
    stats.parse(get_mscores())
    return jsonify([player_stat.to_json()
                    for player_stat in stats.player_stats.values()])

@app.route('/api/v1/players/<string:player_id>', methods=["GET"])
def get_player(player_id):
    """
    : return: the player with given ID
    """
    stats = s_overall.OverallWinnerStat()
    stats.parse(get_mscores())
    if player_id in stats.player_stats:
        return jsonify(stats.player_stats[player_id].to_json())
    return jsonify('Failed to find player with id %s' % player_id), 404

if __name__ == '__main__':
    parser = argparse.ArgumentParser('app.py')
    parser.add_argument(
        '-d', '-r', help='goes in flask debug mode', action="store_true")
    parser.add_argument('port', help='The port, 5000 by default', nargs='?',
                        type=int, default=5000)
    args = parser.parse_args()

    print('launching server with args [%s]' % ', '.join(sys.argv))
    app.run(debug=args.d, port=args.port)

redpajama_set_name: RedPajamaGithub


text:
<?php

// Define constants
define('<%= _(name).chain().underscored().value().toUpperCase() %>_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('<%= _(name).chain().underscored().value().toUpperCase() %>_PLUGIN_URL', plugin_dir_url(__FILE__));
define('<%= _(name).chain().underscored().value().toUpperCase() %>_PLUGIN_WORDPRESS_VERSION', get_bloginfo( 'version' ));

// Includes
// require_once(<%= _(name).chain().underscored().value().toUpperCase() %>_PLUGIN_DIR.'bower_components/wordpress-tools-.php');

class <%= _.camelize(name) %>_Plugin {

	static function init(){
		return new <%= _.camelize(name) %>_Plugin();
	}

	const ID = '<%= _(name).chain().underscored().value().toUpperCase() %>';

	/**
	 * Initializes the plugin by setting localization, filters, and administration functions.
	 */
	private function __construct() {
		register_activation_hook(__FILE__, array( &$this, 'activate' ) );
		register_deactivation_hook(__FILE__, array( &$this, 'deactivate' ) );

		// TODO write more functionality here
	}

	/**
	 * Fired when the plugin is activated.
	 *
	 * @param	boolean	$network_wide	True if WPMU superadmin uses "Network Activate" action, false if WPMU is disabled or plugin is activated on an individual blog
	 */
	public function activate( $network_wide ) {

	}

	/**
	 * Fired when the plugin is deactivated.
	 *
	 * @param	boolean	$network_wide	True if WPMU superadmin uses "Network Activate" action, false if WPMU is disabled or plugin is activated on an individual blog
	 */
	function deactivate( $network_wide ) {

	}

} // end class

add_action( 'plugins_loaded', array('<%= _.camelize(name) %>_Plugin', 'init' ) );

?>


text:
/*
 * File: app/view/Firstcontainer.js
 *
 * This file was generated by Sencha Architect version 3.1.0.
 * http://www.sencha.com/products/architect/
 *
 * This file requires use of the Sencha Touch 2.3.x library, under independent license.
 * License of Sencha Architect does not include license for Sencha Touch 2.3.x. For more
 * details see http://www.sencha.com/license or contact license@sencha.com.
 *
 * This file will be auto-generated each and everytime you save your project.
 *
 * Do NOT hand edit this file.
 */

Ext.define('DemoApp.view.Firstcontainer', {
    extend: 'Ext.Container',
    alias: 'widget.firstcontainer',

    requires: [
        'Ext.Button',
        'Ext.Spacer',
        'Ext.Img'
    ],

    config: {
        padding: 40,
        items: [
            {
                xtype: 'button',
                height: 54,
                itemId: 'firstSignIn',
                text: 'New User? SIGN UP'
            },
            {
                xtype: 'spacer',
                height: 26
            },
            {
                xtype: 'image',
                height: 201,
                src: 'heartbeat.jpg'
            },
            {
                xtype: 'spacer',
                height: 30
            },
            {
                xtype: 'button',
                height: 54,
                itemId: 'firstLogin',
                text: 'LOGIN'
            }
        ],
        listeners: [
            {
                fn: 'onFirstSignInTap',
                event: 'tap',
                delegate: '#firstSignIn'
            },
            {
                fn: 'onFirstLoginTap',
                event: 'tap',
                delegate: '#firstLogin'
            }
        ]
    },

    onFirstSignInTap: function(button, e, eOpts) {
              Ext.Viewport.add(
                {
                    xtype: 'signcontainer'
                });
              Ext.Viewport.setActiveItem(
                {
                    xtype: 'signcontainer'
                });

    },

    onFirstLoginTap: function(button, e, eOpts) {
        Ext.Viewport.add(
                {
                    xtype: 'logincontainer'
                });
                        Ext.Viewport.setActiveItem(
                        {
                            xtype: 'logincontainer'
                        });

    }

});


text:
package com.yueny.demo.dynamic.scheduler.shared;

/**
 * @author yueny09 <deep_blue_yang@163.com>
 *
 * @DATE 2016年1月29日 上午12:35:50
 *
 */
public abstract class ThreadLocalHolder {
	// Filter中ThreadLocalHolder.clientIp(clientIp);;使用时ThreadLocalHolder.clientIp()
	private static ThreadLocal<String> clientIpThreadLocal = new ThreadLocal<>();

	public static String clientIp() {
		return clientIpThreadLocal.get();
	}

	public static void clientIp(final String clientIp) {
		clientIpThreadLocal.set(clientIp);
	}

	protected ThreadLocalHolder() {
		//
	}

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.marcelogomes.exomeanalysis.model;

/**
 *
 * @author marcelo
 */
public enum Profile {
    administrator,
    manager,
    reviser
}


text:
importScripts('labor.js');

var lib = {};

lib.first_arg = function() {
	return arguments[0];
};

var router = new labor.Router(lib);


text:
using Advanced_Combat_Tracker;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace RainbowMage.ActLocalizer
{
    public class PluginMain : IActPluginV1
    {
        TabPage pluginTab;
        Label statusLabel;
        Config config;
        ConfigPanel configPanel;

        public void InitPlugin(TabPage pluginScreenSpace, Label pluginStatusText)
        {
            pluginTab = pluginScreenSpace;
            statusLabel = pluginStatusText;
            pluginTab.Text = "Localizer";

            PopulateConfig();

            if (config.ExportOriginalOnNextBoot)
            {
                Localizer.ExportLocalizerXml();
                config.ExportOriginalOnNextBoot = false;
            }

            PopulateConfigPanel();
            ApplyLocalizer();

            statusLabel.Text = "Initialized.";
        }

        public void DeInitPlugin()
        {
            config.Save(GetConfigPath());
            statusLabel.Text = "Finalized.";
        }

        private void PopulateConfig()
        {
            try
            {
                var configPath = GetConfigPath();
                if (File.Exists(configPath))
                {
                    config = Config.Load(configPath);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Failed to load config file.\n\n" + e.ToString());
            }

            if (config == null)
            {
                config = new Config();
            }
        }

        private void PopulateConfigPanel()
        {
            configPanel = new ConfigPanel(config);
            configPanel.Dock = DockStyle.Fill;

            configPanel.LocaleChanged += (o, e) =>
            {
                //ApplyLocalizer();
            };

            pluginTab.Controls.Add(configPanel);
        }

        private void ApplyLocalizer()
        {
            if (config.IsEnabled)
            {
                try
                {
                    var localizer = new Localizer(config.Locale);
                    localizer.Localize();
                }
                catch (Exception e)
                {
                    MessageBox.Show("Failed to create or apply localizer.\n\n" + e.ToString());
                }
            }
        }

        private static string GetConfigPath()
        {
            var path = Path.Combine(
                ActGlobals.oFormActMain.AppDataFolder.FullName,
                "Config",
                "RainbowMage.ActLocalizer.config.xml");

            return path;
        }
    }

}


text:
import { DiceDisplay } from "models/dice";
import { DiceRect, DiceLayout } from "./layout";

const DICE_SPACE = 0.1;
const GROUP_SPACE = 0.5;
const MAX_SIZE_PROPORTION = 0.05;

export default class HorizontalDiceLayout implements DiceLayout {
	public compute(width: number, height: number, dices: DiceDisplay[][]): ReadonlyMap<DiceDisplay, DiceRect> {
		const result = new Map<DiceDisplay, DiceRect>();

		const count = dices.length;
		const length = dices.reduce((max, group) => Math.max(max, group.length), 0);
		if (count > 0 && length > 0) {
			const blockWidth = width / count;

			const ratio = length + DICE_SPACE * (length - 1) + GROUP_SPACE;
			const maxSize = this.getMaxSize(width, height);
			const rawSize = Math.floor(blockWidth / ratio);
			const size = Math.min(rawSize, maxSize);

			const y = Math.round((height - size) * 0.5);
			const diceStep = (1 + DICE_SPACE) * size;
			const diceOffset = (DICE_SPACE * size) / 2;

			for (const [i, group] of dices.entries()) {
				const groupWidth = diceStep * group.length;
				const groupOffset = (blockWidth - groupWidth) / 2;
				const groupX = blockWidth * i + groupOffset;
				for (const [j, dice] of group.entries()) {
					const x = Math.round(diceStep * j + groupX + diceOffset);

					result.set(dice, { x, y, size });
				}
			}
		}

		return result;
	}

	private getMaxSize(width: number, height: number): number {
		return Math.floor(Math.sqrt(width * height * MAX_SIZE_PROPORTION));
	}
}


text:
#include "common/network/dns_impl.h"

#include <chrono>
#include <cstdint>
#include <list>
#include <memory>
#include <string>

#include "envoy/common/platform.h"

#include "common/common/assert.h"
#include "common/common/fmt.h"
#include "common/network/address_impl.h"
#include "common/network/utility.h"

#include "absl/strings/str_join.h"
#include "ares.h"

namespace Envoy {
namespace Network {

DnsResolverImpl::DnsResolverImpl(
    Event::Dispatcher& dispatcher,
    const std::vector<Network::Address::InstanceConstSharedPtr>& resolvers,
    const bool use_tcp_for_dns_lookups)
    : dispatcher_(dispatcher),
      timer_(dispatcher.createTimer([this] { onEventCallback(ARES_SOCKET_BAD, 0); })),
      use_tcp_for_dns_lookups_(use_tcp_for_dns_lookups) {

  AresOptions options = defaultAresOptions();
  initializeChannel(&options.options_, options.optmask_);

  if (!resolvers.empty()) {
    std::vector<std::string> resolver_addrs;
    resolver_addrs.reserve(resolvers.size());
    for (const auto& resolver : resolvers) {
      // This should be an IP address (i.e. not a pipe).
      if (resolver->ip() == nullptr) {
        ares_destroy(channel_);
        throw EnvoyException(
            fmt::format("DNS resolver '{}' is not an IP address", resolver->asString()));
      }
      // Note that the ip()->port() may be zero if the port is not fully specified by the
      // Address::Instance.
      // resolver->asString() is avoided as that format may be modified by custom
      // Address::Instance implementations in ways that make the <port> not a simple
      // integer. See https://github.com/envoyproxy/envoy/pull/3366.
      resolver_addrs.push_back(fmt::format(resolver->ip()->ipv6() ? "[{}]:{}" : "{}:{}",
                                           resolver->ip()->addressAsString(),
                                           resolver->ip()->port()));
    }
    const std::string resolvers_csv = absl::StrJoin(resolver_addrs, ",");
    int result = ares_set_servers_ports_csv(channel_, resolvers_csv.c_str());
    RELEASE_ASSERT(result == ARES_SUCCESS, "");
  }
}

DnsResolverImpl::~DnsResolverImpl() {
  timer_->disableTimer();
  ares_destroy(channel_);
}

DnsResolverImpl::AresOptions DnsResolverImpl::defaultAresOptions() {
  AresOptions options{};

  if (use_tcp_for_dns_lookups_) {
    options.optmask_ |= ARES_OPT_FLAGS;
    options.options_.flags |= ARES_FLAG_USEVC;
  }

  return options;
}

void DnsResolverImpl::initializeChannel(ares_options* options, int optmask) {
  options->sock_state_cb = [](void* arg, os_fd_t fd, int read, int write) {
    static_cast<DnsResolverImpl*>(arg)->onAresSocketStateChange(fd, read, write);
  };
  options->sock_state_cb_data = this;
  ares_init_options(&channel_, options, optmask | ARES_OPT_SOCK_STATE_CB);
}

void DnsResolverImpl::PendingResolution::onAresGetAddrInfoCallback(int status, int timeouts,
                                                                   ares_addrinfo* addrinfo) {
  // We receive ARES_EDESTRUCTION when destructing with pending queries.
  if (status == ARES_EDESTRUCTION) {
    ASSERT(owned_);
    // This destruction might have been triggered by a peer PendingResolution that received a
    // ARES_ECONNREFUSED. If the PendingResolution has not been cancelled that means that the
    // callback_ target _should_ still be around. In that case, raise the callback_ so the target
    // can be done with this query and initiate a new one.
    if (!cancelled_) {
      callback_(ResolutionStatus::Failure, {});
    }
    delete this;
    return;
  }
  if (!fallback_if_failed_) {
    completed_ = true;

    // If c-ares returns ARES_ECONNREFUSED and there is no fallback we assume that the channel_ is
    // broken. Mark the channel dirty so that it is destroyed and reinitialized on a subsequent call
    // to DnsResolver::resolve(). The optimal solution would be for c-ares to reinitialize the
    // channel, and not have Envoy track side effects.
    // context: https://github.com/envoyproxy/envoy/issues/4543 and
    // https://github.com/c-ares/c-ares/issues/301.
    //
    // The channel cannot be destroyed and reinitialized here because that leads to a c-ares
    // segfault.
    if (status == ARES_ECONNREFUSED) {
      parent_.dirty_channel_ = true;
    }
  }

  std::list<DnsResponse> address_list;
  ResolutionStatus resolution_status;
  if (status == ARES_SUCCESS) {
    resolution_status = ResolutionStatus::Success;
    if (addrinfo != nullptr && addrinfo->nodes != nullptr) {
      if (addrinfo->nodes->ai_family == AF_INET) {
        for (const ares_addrinfo_node* ai = addrinfo->nodes; ai != nullptr; ai = ai->ai_next) {
          sockaddr_in address;
          memset(&address, 0, sizeof(address));
          address.sin_family = AF_INET;
          address.sin_port = 0;
          address.sin_addr = reinterpret_cast<sockaddr_in*>(ai->ai_addr)->sin_addr;

          address_list.emplace_back(
              DnsResponse(std::make_shared<const Address::Ipv4Instance>(&address),
                          std::chrono::seconds(ai->ai_ttl)));
        }
      } else if (addrinfo->nodes->ai_family == AF_INET6) {
        for (const ares_addrinfo_node* ai = addrinfo->nodes; ai != nullptr; ai = ai->ai_next) {
          sockaddr_in6 address;
          memset(&address, 0, sizeof(address));
          address.sin6_family = AF_INET6;
          address.sin6_port = 0;
          address.sin6_addr = reinterpret_cast<sockaddr_in6*>(ai->ai_addr)->sin6_addr;
          address_list.emplace_back(
              DnsResponse(std::make_shared<const Address::Ipv6Instance>(address),
                          std::chrono::seconds(ai->ai_ttl)));
        }
      }
    }

    if (!address_list.empty()) {
      completed_ = true;
    }

    ASSERT(addrinfo != nullptr);
    ares_freeaddrinfo(addrinfo);
  } else {
    resolution_status = ResolutionStatus::Failure;
  }

  if (timeouts > 0) {
    ENVOY_LOG(debug, "DNS request timed out {} times", timeouts);
  }

  if (completed_) {
    if (!cancelled_) {
      try {
        callback_(resolution_status, std::move(address_list));
      } catch (const EnvoyException& e) {
        ENVOY_LOG(critical, "EnvoyException in c-ares callback: {}", e.what());
        dispatcher_.post([s = std::string(e.what())] { throw EnvoyException(s); });
      } catch (const std::exception& e) {
        ENVOY_LOG(critical, "std::exception in c-ares callback: {}", e.what());
        dispatcher_.post([s = std::string(e.what())] { throw EnvoyException(s); });
      } catch (...) {
        ENVOY_LOG(critical, "Unknown exception in c-ares callback");
        dispatcher_.post([] { throw EnvoyException("unknown"); });
      }
    }
    if (owned_) {
      delete this;
      return;
    }
  }

  if (!completed_ && fallback_if_failed_) {
    fallback_if_failed_ = false;
    getAddrInfo(AF_INET);
    // Note: Nothing can follow this call to getAddrInfo due to deletion of this
    // object upon synchronous resolution.
    return;
  }
}

void DnsResolverImpl::updateAresTimer() {
  // Update the timeout for events.
  timeval timeout;
  timeval* timeout_result = ares_timeout(channel_, nullptr, &timeout);
  if (timeout_result != nullptr) {
    const auto ms =
        std::chrono::milliseconds(timeout_result->tv_sec * 1000 + timeout_result->tv_usec / 1000);
    ENVOY_LOG(trace, "Setting DNS resolution timer for {} milliseconds", ms.count());
    timer_->enableTimer(ms);
  } else {
    timer_->disableTimer();
  }
}

void DnsResolverImpl::onEventCallback(os_fd_t fd, uint32_t events) {
  const ares_socket_t read_fd = events & Event::FileReadyType::Read ? fd : ARES_SOCKET_BAD;
  const ares_socket_t write_fd = events & Event::FileReadyType::Write ? fd : ARES_SOCKET_BAD;
  ares_process_fd(channel_, read_fd, write_fd);
  updateAresTimer();
}

void DnsResolverImpl::onAresSocketStateChange(os_fd_t fd, int read, int write) {
  updateAresTimer();
  auto it = events_.find(fd);
  // Stop tracking events for fd if no more state change events.
  if (read == 0 && write == 0) {
    if (it != events_.end()) {
      events_.erase(it);
    }
    return;
  }

  // If we weren't tracking the fd before, create a new FileEvent.
  if (it == events_.end()) {
    events_[fd] = dispatcher_.createFileEvent(
        fd, [this, fd](uint32_t events) { onEventCallback(fd, events); },
        Event::FileTriggerType::Level, Event::FileReadyType::Read | Event::FileReadyType::Write);
  }
  events_[fd]->setEnabled((read ? Event::FileReadyType::Read : 0) |
                          (write ? Event::FileReadyType::Write : 0));
}

ActiveDnsQuery* DnsResolverImpl::resolve(const std::string& dns_name,
                                         DnsLookupFamily dns_lookup_family, ResolveCb callback) {
  // TODO(hennna): Add DNS caching which will allow testing the edge case of a
  // failed initial call to getAddrInfo followed by a synchronous IPv4
  // resolution.

  // @see DnsResolverImpl::PendingResolution::onAresGetAddrInfoCallback for why this is done.
  if (dirty_channel_) {
    dirty_channel_ = false;
    ares_destroy(channel_);

    AresOptions options = defaultAresOptions();
    initializeChannel(&options.options_, options.optmask_);
  }
  std::unique_ptr<PendingResolution> pending_resolution(
      new PendingResolution(*this, callback, dispatcher_, channel_, dns_name));
  if (dns_lookup_family == DnsLookupFamily::Auto) {
    pending_resolution->fallback_if_failed_ = true;
  }

  if (dns_lookup_family == DnsLookupFamily::V4Only) {
    pending_resolution->getAddrInfo(AF_INET);
  } else {
    pending_resolution->getAddrInfo(AF_INET6);
  }

  if (pending_resolution->completed_) {
    // Resolution does not need asynchronous behavior or network events. For
    // example, localhost lookup.
    return nullptr;
  } else {
    // Enable timer to wake us up if the request times out.
    updateAresTimer();

    // The PendingResolution will self-delete when the request completes (including if cancelled or
    // if ~DnsResolverImpl() happens via ares_destroy() and subsequent handling of ARES_EDESTRUCTION
    // in DnsResolverImpl::PendingResolution::onAresGetAddrInfoCallback()).
    pending_resolution->owned_ = true;
    return pending_resolution.release();
  }
}

void DnsResolverImpl::PendingResolution::getAddrInfo(int family) {
  struct ares_addrinfo_hints hints = {};
  hints.ai_family = family;

  /**
   * ARES_AI_NOSORT result addresses will not be sorted and no connections to resolved addresses
   * will be attempted
   */
  hints.ai_flags = ARES_AI_NOSORT;

  ares_getaddrinfo(
      channel_, dns_name_.c_str(), /* service */ nullptr, &hints,
      [](void* arg, int status, int timeouts, ares_addrinfo* addrinfo) {
        static_cast<PendingResolution*>(arg)->onAresGetAddrInfoCallback(status, timeouts, addrinfo);
      },
      this);
}

} // namespace Network
} // namespace Envoy


text:
<?php

namespace Framework\Exceptions;

/**
 * FatalException
 */
class FatalException extends \Exception
{
    public $responseCode = '500';
}


text:
package series

type SendEncoding uint8

const (
	ENCODE_JSON SendEncoding = iota
	ENCODE_MSGP
	ENCODE_PROTOBUF
)

func SendEncodingFromString(enc string) SendEncoding {
	switch enc {
	case "json":
		return ENCODE_JSON
	case "protobuf":
		return ENCODE_PROTOBUF
	default:
		return ENCODE_MSGP
	}
}

type MessageType uint8

const (
	MSG_SERIES MessageType = iota
	MSG_SINGLE
	MSG_UNPROCESSED
	MSG_UID
	MSG_RAW
	MSG_ANY
	MSG_WRITTEN
	MSG_SINGLE_LIST
	MSG_UNPROCESSED_LIST
	MSG_RAW_LIST
	MSG_ANY_LIST
)

func MetricTypeFromString(enc string) MessageType {
	switch enc {
	case "series":
		return MSG_SERIES
	case "unprocessed":
		return MSG_UNPROCESSED
	case "uid":
		return MSG_UID
	case "raw":
		return MSG_RAW
	case "single":
		return MSG_SINGLE
	case "any", "all":
		return MSG_ANY
	case "written":
		return MSG_WRITTEN
	case "single_list":
		return MSG_SINGLE_LIST
	case "unprocessed_list":
		return MSG_UNPROCESSED_LIST
	case "raw_list":
		return MSG_RAW_LIST
	case "all_list", "any_list":
		return MSG_ANY_LIST
	default:
		return MSG_SINGLE
	}
}


text:
    Una descrizione (facoltativa) per consentire di distinguere credenziali
    simili.


text:
package specification.steps.ui;

import jdo.party.model.Person;

import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Pending;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import org.seleniumhq.selenium.fluent.TestableString;

import specification.pages.CrmIndex;
import specification.pages.CustomersNew;
import specification.pages.PageFactory;

/**
 * Crm steps for the UI portion.
 *
 * @author Jim
 *
 */
public class CrmSteps {

    /**
     * The index page.
     */
    private CrmIndex index;
    /**
     * The /customers/new page.
     */
    private CustomersNew customerNew;

    /**
     * The person who is a customer.
     */
    private Person person;

    /**
     * Construct the object by getting the pages that will be used in the steps.
     *
     * @param pageFactory
     *            The factory for the page.
     */
    public CrmSteps(final PageFactory pageFactory) {
	index = pageFactory.crmIndex();
	customerNew = pageFactory.customerNew();
    }

    /**
     * Map the step to the function.
     */
    @Given("I am on the crm site")
    public final void givenIAmOnTheCrmSite() {
	index.go();
	index.onCorrectPage();
	index.title().shouldBe("Customer Relationship Management");
	index.pageHeader().shouldBe("Customer Relationship Management");
    }

    /**
     * Map the step to the function.
     */
    @Given("I've chosen to add a person as a customer")
    public final void addPersonAsCustomer() {
	index.clickAddButton();
	customerNew.onCorrectPage();
	customerNew.selectCustomerType("Person");
	person = new Person();
    }

    /**
     * Map the step to the function.
     *
     * @param firstName
     *            of the customer
     */
    @Given("I enter the first name as $firstName")
    public final void enterFirstNameAs(final String firstName) {
	customerNew.setFirstName(firstName);
	person.setFirstName(firstName);
    }

    /**
     * Map the step to the function.
     *
     * @param lastName
     *            of the customer
     */
    @Given("I enter the last name as $lastName")
    public final void enterLastNameAs(final String lastName) {
	customerNew.setLastName(lastName);
	person.setLastName(lastName);
    }

    /**
     * Map the step to the function.
     */
    @When("I save the customer")
    public final void whenISaveTheCustomer() {
	customerNew.clickSaveButton();
    }

    /**
     * Map the step.
     */
    @Then("I get a message indicating the successful save")
    public final void thenIGetAMessageIndicatingTheSuccessfulSave() {
	TestableString flashMessage = customerNew.flashMessage();
	flashMessage.shouldBe("New customer added.");
    }

    /**
     * Map the step.
     */
    @Then("I get shown the list of customers")
    public final void thenIGetShownTheListOfCustomers() {
	index.onCorrectPage();
    }

    /**
     * Map the step.
     */
    @Then("the new customer in the list.")
    public final void thenTheNewCustomerInTheList() {
	index.customerList().contains(person.getFirstName() + " " + person.getLastName());
    }

    /**
     * Map the step.
     */
    @Given("I've chosen to add a customer")
    @Pending
    public final void givenIHaveChosenToAddACustomer() {
	// PENDING
    }

    /**
     * Map the step.
     */
    @Given("I enter the organization name")
    @Pending
    public final void givenIEnterTheOrganizationName() {
	// PENDING
    }

    /**
     * Map the step.
     */
    @Then("I get shown the list of customers with the new customer in the list.")
    @Pending
    public final void thenIGetShownTheListOfCustomersWithTheNewCustomerInTheList() {
	// PENDING
    }

}


text:
RECORD () {
    $verbose && local quiet='' || local quiet='>/dev/null 2>&1'
    [ -n "$2" ] && local timeout="utils/timeout.sh $2" || local timeout=""
    local cmd="$timeout python $quiet recorders/snowboy/main.py $gain $1 $quiet"
    $verbose && jv_debug "$cmd"
    printf $_gray
    eval $cmd # need eval because of timeout, maybe better to change this
    local retcode=$?
    printf $_reset
    [ $retcode -eq 124 ] && return 124 # timeout
    if [ "$retcode" -ne 0 ]; then
        jv_error "ERROR: rec command failed"
        jv_warning "HELP: retry in troubleshooting mode for more details"
        jv_exit 1
    fi
}


text:
var formModule = angular.module('mlcl_forms.form');
var fieldStringText = function fieldStringText($compile, $templateCache, $rootScope) {
  return function (fieldScope) {
    var self = this;
    this.render = function () {
      var inputHtml = $templateCache.get('plugins/field_string/field_string_text.tpl.html');
      self.htmlObject = $compile(inputHtml)(fieldScope);
      return this;
    };
  };
};
formModule.factory('string:text', [
  '$compile',
  '$templateCache',
  '$rootScope',
  fieldStringText
]);
formModule.factory('string', [
  '$compile',
  '$templateCache',
  '$rootScope',
  fieldStringText
]);


text:
package com.evernote.client.android.asyncclient;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.evernote.client.android.EvernoteSession;
import com.evernote.client.android.helper.EvernotePreconditions;
import com.evernote.edam.error.EDAMNotFoundException;
import com.evernote.edam.error.EDAMSystemException;
import com.evernote.edam.error.EDAMUserException;
import com.evernote.edam.type.LinkedNotebook;
import com.evernote.edam.type.Note;
import com.evernote.edam.type.Notebook;
import com.evernote.edam.type.SharedNotebook;
import com.evernote.thrift.TException;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

/**
 * Provides several helper methods for {@link LinkedNotebook}s. The easiest way to create an instance
 * is to call {@link EvernoteClientFactory#getLinkedNotebookHelper(LinkedNotebook)}.
 *
 * @author rwondratschek
 */
@SuppressWarnings("unused")
public class EvernoteLinkedNotebookHelper extends EvernoteAsyncClient {

    protected final EvernoteNoteStoreClient mClient;
    protected final LinkedNotebook mLinkedNotebook;

    /**
     * @param client The note store client referencing the linked notebook note store url.
     * @param linkedNotebook The desired linked notebook.
     * @param executorService The executor running the actions in the background.
     */
    public EvernoteLinkedNotebookHelper(@NonNull EvernoteNoteStoreClient client, @NonNull LinkedNotebook linkedNotebook, @NonNull ExecutorService executorService) {
        super(executorService);
        mClient = EvernotePreconditions.checkNotNull(client);
        mLinkedNotebook = EvernotePreconditions.checkNotNull(linkedNotebook);
    }

    /**
     * @return The note store client referencing the linked notebook's note store.
     */
    public EvernoteNoteStoreClient getClient() {
        return mClient;
    }

    public LinkedNotebook getLinkedNotebook() {
        return mLinkedNotebook;
    }

    /**
     * @param note The new note.
     * @return The new created note from the server.
     */
    public Note createNoteInLinkedNotebook(@NonNull Note note) throws EDAMUserException, EDAMSystemException, TException, EDAMNotFoundException {
        SharedNotebook sharedNotebook = mClient.getSharedNotebookByAuth();
        note.setNotebookGuid(sharedNotebook.getNotebookGuid());
        return mClient.createNote(note);
    }

    /**
     * @see #createNoteInLinkedNotebook(Note)
     */
    public Future<Note> createNoteInLinkedNotebookAsync(@NonNull final Note note, @Nullable EvernoteCallback<Note> callback) {
        return submitTask(new Callable<Note>() {
            @Override
            public Note call() throws Exception {
                return createNoteInLinkedNotebook(note);
            }
        }, callback);
    }

    /**
     * @param session The current valid session.
     * @return A flag indicating if the action was successful.
     * @see EvernoteNoteStoreClient#expungeLinkedNotebook(String)
     */
    public int deleteLinkedNotebook(@NonNull EvernoteSession session) throws TException, EDAMUserException, EDAMSystemException, EDAMNotFoundException {
        return deleteLinkedNotebook(session.getEvernoteClientFactory().getNoteStoreClient());
    }

    /**
     * @param defaultClient The note store client, which references the user's note store.
     * @return A flag indicating if the action was successful.
     * @see EvernoteNoteStoreClient#expungeLinkedNotebook(String)
     */
    public int deleteLinkedNotebook(@NonNull EvernoteNoteStoreClient defaultClient) throws TException, EDAMUserException, EDAMSystemException, EDAMNotFoundException {
        SharedNotebook sharedNotebook = mClient.getSharedNotebookByAuth();
        List<Long> sharedNotebookIds = new ArrayList<>();
        sharedNotebookIds.add(sharedNotebook.getId());

        mClient.expungeSharedNotebooks(sharedNotebookIds);

        return defaultClient.expungeLinkedNotebook(mLinkedNotebook.getGuid());
    }

    /**
     * @see #deleteLinkedNotebook(EvernoteSession)
     */
    public Future<Integer> deleteLinkedNotebookAsync(@NonNull final EvernoteSession session, @Nullable EvernoteCallback<Integer> callback) {
        return deleteLinkedNotebookAsync(session.getEvernoteClientFactory().getNoteStoreClient(), callback);
    }

    /**
     * @see #deleteLinkedNotebook(EvernoteNoteStoreClient)
     */
    public Future<Integer> deleteLinkedNotebookAsync(@NonNull final EvernoteNoteStoreClient defaultClient, @Nullable EvernoteCallback<Integer> callback) {
        return submitTask(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                return deleteLinkedNotebook(defaultClient);
            }
        }, callback);
    }

    /**
     * @return The notebook for this linked notebook.
     */
    public Notebook getCorrespondingNotebook() throws TException, EDAMUserException, EDAMSystemException, EDAMNotFoundException {
        SharedNotebook sharedNotebook = mClient.getSharedNotebookByAuth();
        return mClient.getNotebook(sharedNotebook.getNotebookGuid());
    }

    /**
     * @see #getCorrespondingNotebook()
     */
    public Future<Notebook> getCorrespondingNotebookAsync(@Nullable EvernoteCallback<Notebook> callback) {
        return submitTask(new Callable<Notebook>() {
            @Override
            public Notebook call() throws Exception {
                return getCorrespondingNotebook();
            }
        }, callback);
    }

    /**
     * @return {@code true} if this linked notebook is writable.
     */
    public boolean isNotebookWritable() throws EDAMUserException, TException, EDAMSystemException, EDAMNotFoundException {
        Notebook notebook = getCorrespondingNotebook();
        return !notebook.getRestrictions().isNoCreateNotes();
    }

    /**
     * @see #isNotebookWritable()
     */
    public Future<Boolean> isNotebookWritableAsync(@Nullable EvernoteCallback<Boolean> callback) {
        return submitTask(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                return isNotebookWritable();
            }
        }, callback);
    }
}


text:
package io.spine.server.delivery.given;

import com.google.protobuf.Timestamp;
import io.spine.base.Identifier;
import io.spine.base.Time;
import io.spine.client.EntityId;
import io.spine.core.Command;
import io.spine.server.delivery.DeliveryStrategy;
import io.spine.server.delivery.InboxId;
import io.spine.server.delivery.InboxLabel;
import io.spine.server.delivery.InboxMessage;
import io.spine.server.delivery.InboxMessageId;
import io.spine.server.delivery.InboxMessageMixin;
import io.spine.server.delivery.InboxMessageStatus;
import io.spine.server.delivery.InboxSignalId;
import io.spine.test.delivery.AddNumber;
import io.spine.test.delivery.DTask;
import io.spine.testing.client.TestActorRequestFactory;
import io.spine.type.TypeUrl;

import static io.spine.server.delivery.InboxMessageStatus.DELIVERED;
import static io.spine.server.delivery.InboxMessageStatus.TO_CATCH_UP;
import static io.spine.server.delivery.InboxMessageStatus.TO_DELIVER;

/**
 * Provides the instances of {@link InboxMessage}s to use as a data in tests.
 */
public final class TestInboxMessages {

    private static final TestActorRequestFactory factory =
            new TestActorRequestFactory(TestInboxMessages.class);

    /**
     * Does not allow to instantiate this utility class.
     */
    private TestInboxMessages() {
    }

    /**
     * Copies the original {@code InboxMessage} but generates a new {@link InboxMessageId}
     * for the copy.
     */
    public static InboxMessage copyWithNewId(InboxMessage original) {
        return original.toBuilder()
                .setId(InboxMessageMixin.generateIdWith(original.shardIndex()))
                .build();
    }

    /**
     * Copies the original {@code InboxMessage} but sets the specified status to the copy.
     */
    public static InboxMessage copyWithStatus(InboxMessage original, InboxMessageStatus newStatus) {
        return original.toBuilder()
                .setStatus(newStatus)
                .build();
    }

    /**
     * Generates a new {@code InboxMessage} in
     * {@link io.spine.server.delivery.InboxMessageStatus#TO_CATCH_UP TO_CATCH_UP} status.
     *
     * @param targetId
     *         the ID of the target for the generated message
     * @param targetType
     *         the type URL of the target for the generated message
     * @return an instance of the generated message
     */
    public static InboxMessage catchingUp(Object targetId, TypeUrl targetType) {
        return newMessage(targetId, targetType, TO_CATCH_UP);
    }

    /**
     * Generates a new {@code InboxMessage} in
     * {@link io.spine.server.delivery.InboxMessageStatus#TO_CATCH_UP TO_CATCH_UP} status
     * and the receiving time specified.
     *
     * @param targetId
     *         the ID of the target for the generated message
     * @param targetType
     *         the type URL of the target for the generated message
     * @param whenReceived
     *         the message receiving time to set
     * @return an instance of the generated message
     */
    public static InboxMessage catchingUp(Object targetId,
                                          TypeUrl targetType,
                                          Timestamp whenReceived) {
        return newMessage(targetId, targetType, TO_CATCH_UP)
                .toBuilder()
                .setWhenReceived(whenReceived)
                .build();
    }

    /**
     * Generates a new {@code InboxMessage} in
     * {@link io.spine.server.delivery.InboxMessageStatus#TO_DELIVER TO_DELIVER} status.
     *
     * @param targetId
     *         the ID of the target for the generated message
     * @param targetType
     *         the type URL of the target for the generated message
     * @return an instance of the generated message
     */
    public static InboxMessage toDeliver(Object targetId, TypeUrl targetType) {
        return newMessage(targetId, targetType, TO_DELIVER);
    }

    /**
     * Generates a new {@code InboxMessage} in
     * {@link io.spine.server.delivery.InboxMessageStatus#TO_DELIVER TO_DELIVER} status and
     * the receiving time specified.
     *
     * @param targetId
     *         the ID of the target for the generated message
     * @param targetType
     *         the type URL of the target for the generated message
     * @param whenReceived
     *         the message receiving time to set
     * @return an instance of the generated message
     */
    public static InboxMessage toDeliver(Object targetId,
                                         TypeUrl targetType,
                                         Timestamp whenReceived) {
        return newMessage(targetId, targetType, TO_DELIVER)
                .toBuilder()
                .setWhenReceived(whenReceived)
                .build();
    }

    /**
     * Generates a new {@code InboxMessage} in
     * {@link io.spine.server.delivery.InboxMessageStatus#DELIVERED DELIVERED} status.
     *
     * @param targetId
     *         the ID of the target for the generated message
     * @param targetType
     *         the type URL of the target for the generated message
     * @return an instance of the generated message
     */
    public static InboxMessage delivered(Object targetId, TypeUrl targetType) {
        return newMessage(targetId, targetType, DELIVERED);
    }

    /**
     * Generates a new {@code InboxMessage} in
     * {@link io.spine.server.delivery.InboxMessageStatus#TO_DELIVER TO_DELIVER} status on top
     * of the passed command in  and sets the receiving time according to the passed value.
     */
    public static InboxMessage toDeliver(Command source, Timestamp whenReceived) {
        var inboxId = newInboxId("some-target", TypeUrl.of(DTask.class));
        var message = messageReceivedAt(source, TO_DELIVER, inboxId, whenReceived);
        return message;
    }

    private static InboxMessage newMessage(Object target, TypeUrl type, InboxMessageStatus status) {
        var command = generateCommand(target);
        var inboxId = newInboxId(target, type);
        var message = messageReceivedAt(command, status, inboxId, Time.currentTime());
        return message;
    }

    private static InboxMessage messageReceivedAt(Command command,
                                                  InboxMessageStatus status,
                                                  InboxId inboxId,
                                                  Timestamp whenReceived) {
        var index = DeliveryStrategy.newIndex(0, 1);
        var id = InboxMessageMixin.generateIdWith(index);
        var signalId = InboxSignalId.newBuilder()
                .setValue(command.getId().value());
        var result = InboxMessage.newBuilder()
                .setId(id)
                .setStatus(status)
                .setCommand(command)
                .setInboxId(inboxId)
                .setSignalId(signalId)
                .setLabel(InboxLabel.HANDLE_COMMAND)
                .setWhenReceived(whenReceived)
                .build();
        return result;
    }

    private static InboxId newInboxId(Object targetId, TypeUrl targetType) {
        return InboxId.newBuilder()
                .setEntityId(EntityId.newBuilder()
                                     .setId(Identifier.pack(targetId))
                                     .build())
                .setTypeUrl(targetType.value())
                .build();
    }

    private static Command generateCommand(Object targetId) {
        var commandMessage = AddNumber.newBuilder()
                .setCalculatorId("some-id-" + targetId)
                .setValue(targetId.hashCode())
                .build();
        return factory.createCommand(commandMessage);
    }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace Microsoft.Protocols.TestTools.StackSdk.Compression.Mppc
{
    /// <summary>
    /// Compressed mode, 8k or 64k
    /// </summary>
    public enum SlidingWindowSize
    {
        /// <summary>
        /// use 8k sliding window
        /// </summary>
        EightKB,

        /// <summary>
        /// use 64k sliding window
        /// </summary>
        SixtyFourKB,
    }
}


text:
<?xml version="1.0"?>
<!-- !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!-->
<!-- !!!!!!!!!!!!!!!!!!!      PLEASE DO NOT EDIT THIS FILE       !!!!!!!!!!! -->
<!-- !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!-->

<!--
Default QoS Profile for BulkDataNT.
-->
<dds xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <!-- this line is needed just if we want to validate the document or similar, ..
    xsi:noNamespaceSchemaLocation="/alma/ACS-X.Y/RTI/ndds.4.5e/resource/qos_profiles_4.5e/schema/rti_dds_qos_profiles.xsd"
     version="4.5e"
    -->

    <!-- QoS Library containing the QoS profile used in the generated example.

        A QoS library is a named set of QoS profiles.
    -->
    <qos_library name="BulkDataQoSLibrary">

        <!-- QoS profile used to configure reliable communication between the DataWriter
             and DataReader created in the example code.

             A QoS profile groups a set of related QoS.
        -->

        <qos_profile name="DefaultStreamQosProfile" >

            <participant_qos>
                <transport_builtin>
                    <!--
                    <mask>DDS_TRANSPORTBUILTIN_MASK_NONE</mask>
                    -->

                    <mask>DDS_TRANSPORTBUILTIN_UDPv4</mask>

                </transport_builtin>
                <receiver_pool>
                    <buffer_size>65536</buffer_size>
                </receiver_pool>
                <event>
                    <max_count>16384</max_count>
                </event>

                <property>
                    <value>
                        <!--    TCP  -->
                        <element>
                            <name>dds.transport.load_plugins</name>
                            <value>dds.transport.TCPv4.tcp1</value>
                        </element>
                        <element>
                            <name>dds.transport.TCPv4.tcp1.library</name>
                            <value>nddstransporttcp</value>
                        </element>
                        <element>
                            <name>dds.transport.TCPv4.tcp1.create_function</name>
                            <value>NDDS_Transport_TCPv4_create</value>
                        </element>
                        <element>
                            <name>dds.transport.TCPv4.tcp1.parent.classid</name>
                            <value>NDDS_TRANSPORT_CLASSID_TCPV4_LAN</value>
                        </element>

                        <element>
                            <name>dds.transport.TCPv4.tcp1.parent.message_size_max</name>
                            <value>65536</value>
                        </element>

                        <element>
                            <name>dds.transport.TCPv4.tcp1.send_socket_buffer_size</name>
                            <value>65536</value>
                        </element>
                        <element>
                            <name>dds.transport.TCPv4.tcp1.recv_socket_buffer_size</name>
                            <value>131072</value>
                        </element>

                        <!-- UDP -->
                        <element>
                            <name>dds.transport.UDPv4.builtin.parent.message_size_max</name>
                            <value>65536</value>
                        </element>
                        <element>
                            <name>dds.transport.UDPv4.builtin.send_socket_buffer_size</name>
                            <value>65536</value>
                        </element>
                        <element>
                            <name>dds.transport.UDPv4.builtin.recv_socket_buffer_size</name>
                            <value>131072</value>
                        </element>
                        <element>
                            <name>dds.transport.UDPv4.builtin.multicast_ttl</name>
                            <value>3</value>
                        </element>
                    </value>
                </property>
            </participant_qos>

        </qos_profile>

        <qos_profile name="SenderStreamDefaultQosProfile" base_name="DefaultStreamQosProfile">
        </qos_profile>

        <qos_profile name="ReceiverStreamDefaultQosProfile" base_name="DefaultStreamQosProfile">
        </qos_profile>

        <qos_profile name="SenderFlowDefaultQosProfile">
            <publisher_qos>
            </publisher_qos>
            <datawriter_qos>
                <transport_selection>
                    <enabled_transports>
                        <element>tcpv4_lan</element>
                    </enabled_transports>
                </transport_selection>

                <reliability>
                    <kind>RELIABLE_RELIABILITY_QOS</kind>
                    <max_blocking_time>
                        <sec>10</sec>
                        <nanosec>0</nanosec>
                    </max_blocking_time>
                </reliability>

                <history>
                    <kind>KEEP_ALL_HISTORY_QOS</kind>
                    <depth>1</depth>
                </history>

                <liveliness>
                    <lease_duration>
                        <sec>9</sec>
                        <nanosec>0</nanosec>
                    </lease_duration>
                </liveliness>

                <resource_limits>
                    <max_samples>5</max_samples>
                    <initial_samples>5</initial_samples>
                    <initial_instances>1</initial_instances>
                    <max_instances>1</max_instances>
                    <max_samples_per_instance>5</max_samples_per_instance>
                </resource_limits>
                <protocol>
                    <push_on_write>true</push_on_write>
                    <disable_positive_acks>false</disable_positive_acks>

                    <rtps_reliable_writer>

                        <min_send_window_size>2</min_send_window_size>
                        <max_send_window_size>5</max_send_window_size>

                        <high_watermark>5</high_watermark>
                        <fast_heartbeat_period>
                            <sec>120</sec>
                            <nanosec>0</nanosec>
                        </fast_heartbeat_period>
                        <heartbeats_per_max_samples>5</heartbeats_per_max_samples>
                        <heartbeat_period>
                            <sec>604800</sec>
                        </heartbeat_period>
                        <max_heartbeat_retries>100</max_heartbeat_retries>
                        <min_nack_response_delay>
                            <sec>0</sec>
                            <nanosec>0</nanosec>
                        </min_nack_response_delay>
                        <max_nack_response_delay>
                            <sec>0</sec>
                            <nanosec>0</nanosec>
                        </max_nack_response_delay>
                        <max_bytes_per_nack_response>65500</max_bytes_per_nack_response>
                    </rtps_reliable_writer>
                </protocol>
            </datawriter_qos>

        </qos_profile>

        <qos_profile name="ReceiverFlowDefaultQosProfile">
            <datareader_qos>

                <transport_selection>
                    <enabled_transports>
                        <element>tcpv4_lan</element>
                    </enabled_transports>
                </transport_selection>
                <reliability>
                    <kind>RELIABLE_RELIABILITY_QOS</kind>
                </reliability>

                <history>
                    <kind>KEEP_ALL_HISTORY_QOS</kind>
                    <depth>10</depth>
                </history>

                <liveliness>
                    <lease_duration>
                        <sec>10</sec>
                        <nanosec>0</nanosec>
                    </lease_duration>
                </liveliness>

                <reader_resource_limits>
                    <initial_remote_writers>1</initial_remote_writers>
                    <max_remote_writers>1</max_remote_writers>
                    <max_remote_writers_per_sample>1</max_remote_writers_per_sample>
                    <initial_remote_writers_per_instance>1</initial_remote_writers_per_instance>
                    <max_remote_writers_per_instance>1</max_remote_writers_per_instance>
                    <max_samples_per_remote_writer>10</max_samples_per_remote_writer>
                </reader_resource_limits>
                <resource_limits>
                    <max_samples>10</max_samples>
                    <initial_samples>10</initial_samples>
                    <max_samples_per_instance>10</max_samples_per_instance>
                </resource_limits>

                <protocol>
                    <rtps_reliable_reader>
                        <min_heartbeat_response_delay>
                            <sec>0</sec>
                            <nanosec>0</nanosec>
                        </min_heartbeat_response_delay>
                        <max_heartbeat_response_delay>
                            <sec>0</sec>
                            <nanosec>0</nanosec>
                        </max_heartbeat_response_delay>
                    </rtps_reliable_reader>
                </protocol>
            </datareader_qos>
        </qos_profile>
    </qos_library>
</dds>


text:
This is an Elixir binding for OpenSLP toolkit.

#### What is SLP and why it's useful

Wiki says:
  "The Service Location Protocol (SLP, srvloc) is a service discovery protocol that allows computers and other devices to find services in a local area network without prior configuration. SLP has been designed to scale from small, unmanaged networks to large enterprise networks."

The protocol is being used in almost all the modern printers and local network shared services which are able to be discovered and connected with zero config e.g. Apple Bonjour, iTunes shared folders, etc.

The protocol applicability is really wide and might be used in almost any local netowrk.

#### About this library
This library is basically a binding for [slptool unix command](http://manpages.ubuntu.com/manpages/gutsy/man1/slptool.1.html) which is a part of [openslp project](http://www.openslp.org/).

The library provides some base modules which extend the distributed nature of Elixir by providing the zero-conf functionality.

#### Example:
Given 2 Erlang nodes running. We want to connect the nodes with no prior knowledge of each other.

Node one:

```elixir
iex(one@127.0.0.1)1> Node.self
:"one@127.0.0.1"
iex(one@127.0.0.1)2> Node.list
[]
```

Node two:

```elixir
iex(two@127.0.0.1)1> Node.self
:"two@127.0.0.1"
iex(two@127.0.0.1)2> Node.list
[]
```

Let's register the services:

```elixir
iex(one@127.0.0.1)3> ExSlp.Service.register
{:ok, ""}
```

Node two:

```elixir
iex(two@127.0.0.1)3> ExSlp.Service.register
{:ok, ""}
```

Everything is ready for the discovery. Running:

```elixir
iex(one@127.0.0.1)4> ExSlp.Service.discover
["service:exslp://two@127.0.0.1,65535"]
```

One could see node one received the information about node 2 without any clue it exists.

Let's connect 'em:

```elixir
iex(two@127.0.0.1)4> ExSlp.Service.discover |> List.first |> ExSlp.Service.connect
true
iex(two@127.0.0.1)5> Node.list
[:"one@127.0.0.1"]
```

Node one says:

```elixir
iex(one@127.0.0.1)5> Node.list
[:"two@127.0.0.1"]
```

This is it. 2 erlang/elixir nodes are connected and we did it using a network multicast request.

For more examples check out `examples` folder.

#### Dependencies:

Basic requirements are

  * libslp  v1.2+
  * slptool v1.2+
  * Elixir  v1.1+

To install OpenSLP  on debian-based systems something like this should do the trick:

    sudo apt-get install slptool slpd libslp1
    sudo /etc/init.d/slpd restart

You could also use a docker image like [vcrhonek/openslp](https://hub.docker.com/r/vcrhonek/openslp/).  To run slpd as a daemon, you'll need a command like this:

    docker run -d -p 427:427/tcp -p 427:427/udp --name openslp vcrhonek/openslp

#### Settings:

By default the ex_slp library will interact with the "slptool" command by assuming it is available as "slptool".  To change the details of that invocation, just add a section like this to your `config.exs` file:

    config :ex_slp,
      slptool: "/some/path/to/slptool"

Or, you could invoke slptool with [a docker image](https://hub.docker.com/r/vcrhonek/openslp/):

    config :ex_slp,
      slptool: "docker run --rm vcrhonek/openslp slptool"

#### Testing

Test suite is slp toolkit version sensitive.

One could check the toolkit version running: `slptool -v`.

Depending on the version one should disable version-specific tests, as:

```
slptool -v
> slptool version = 2.0.0
> libslp version = 2.0.0
> libslp configuration file = /usr/local/Cellar/openslp/2.0.0/etc/slp.conf
mix test --exclude v1
> ...
> Finished in 3.0 seconds (0.3s on load, 2.7s on tests)
```

Version 1 does not support extended command arguments as: interfaces and unicastic requests. Unicastic option allows you to query the local network interface only. Without this option slptool will send a multicast request to the local network and therefore running the test suit takes a while.

#### Known problems
  - `slptool findsrvtypes` might kill slpd on versions prior to 2.0.0


text:
import { Serializer } from '@conversationai/moderator-jsonapi';

export class TaggingSensitivitySerializer extends Serializer {
  constructor(prefix: string) {
    super('tagging_sensitivities', prefix, null, ['tag', 'user', 'category'], ['updatedAt']);
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>InvokeJCLTest xref</title>
<link type="text/css" rel="stylesheet" href="../../../../stylesheet.css" />

View Javadoc

1
25
26  package org.apache.commons.logging;
27
28  import junit.framework.TestCase;
29
30
31  public class InvokeJCLTest extends TestCase {
32
33    public void testIsEnabledAPI() {
34      // assume that we are running over slf4j-jdk14
35      Log log = LogFactory.getLog(InvokeJCLTest.class);
36      assertFalse(log.isTraceEnabled());
37      assertFalse(log.isDebugEnabled());
38      assertTrue(log.isInfoEnabled());
39      assertTrue(log.isWarnEnabled());
40      assertTrue(log.isErrorEnabled());
41      assertTrue(log.isFatalEnabled());
42    }
43
44    public void testPrintAPI() {
45      Log log = LogFactory.getLog(InvokeJCLTest.class);
46      Exception e = new Exception("just testing");
47
48      log.trace(null);
49      log.trace("trace message");
50
51      log.debug(null);
52      log.debug("debug message");
53
54      log.info(null);
55      log.info("info  message");
56
57      log.warn(null);
58      log.warn("warn message");
59
60      log.error(null);
61      log.error("error message");
62
63      log.fatal(null);
64      log.fatal("fatal message");
65
66
67      log.trace(null, e);
68      log.trace("trace message", e);
69
70      log.debug(null, e);
71      log.debug("debug message", e);
72
73      log.info(null, e);
74      log.info("info  message", e);
75
76      log.warn(null, e);
77      log.warn("warn message", e);
78
79      log.error(null, e);
80      log.error("error message", e);
81
82      log.fatal(null, e);
83      log.fatal("fatal message", e);
84    }
85  }

This page was automatically generated by Maven


text:
**This gem has been moved to the [mince](https://github.com/coffeencoke/mince) core gem, and this repo is deprecated**

# Version 2.0 Release Notice

Version 2.0 is currently in preview, available on <http://rubygems.org> and at [@coffeencoke's github repo](https://github.com/coffeencoke)

This repo will be moved to @coffeencoke once version 2.0 is officially released.

# MinceModel

Common model behavior for objects backed by Mince

## Installation

Add this line to your application's Gemfile:

    gem 'mince_model'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install mince_model

## Usage

1. Write your models as plain old Ruby objects.
2. In your model, `include MinceModel`.
3. In your model, define the data model with `data_model DataModelClass`.
4. In your model, define fields with `field :field_name, assignable: true`.

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
module RespondToMissing
  autoload :Version, 'respond_to_missing/version'

  def respond_to?(method_name, include_private = false)
    super || !!respond_to_missing?(method_name, include_private)
  end

  def respond_to_missing?(method_name, include_private)
    false
  end
end

Object.send(:include, RespondToMissing) unless respond_to?(:respond_to_missing?)


text:
package org.apache.isis.viewer.scimpi.dispatcher.view.display;

import java.util.List;
import org.apache.isis.core.commons.authentication.MessageBroker;
import org.apache.isis.core.runtime.system.context.IsisContext;
import org.apache.isis.viewer.scimpi.dispatcher.AbstractElementProcessor;
import org.apache.isis.viewer.scimpi.dispatcher.processor.Request;

public class Warnings extends AbstractElementProcessor {

    @Override
    public void process(final Request request) {
        final String cls = request.getOptionalProperty(CLASS);
        final StringBuffer buffer = new StringBuffer();
        write(cls, buffer);
        if (buffer.length() > 0) {
            request.appendHtml("
");
            request.appendHtml(buffer.toString());
            request.appendHtml("
");
        }
    }

    public static void write(String cls, final StringBuffer buffer) {
        if (cls == null) {
            cls = "warning";
        }
        final MessageBroker messageBroker = IsisContext.getMessageBroker();
        final List<String> warnings = messageBroker.getWarnings();
        for (final String warning : warnings) {
            buffer.append("
" + warning + "
");
        }
    }

    @Override
    public String getName() {
        return "warnings";
    }

}


text:
if sed -i "/reverseProxyPrefix/c\\  \"reverseProxyPrefix\" : \"\"," "$APPSETTINGS"; then
    echo "Updated reverseProxyPrefix in $APPSETTINGS"
fi


text:
var Select = antd.Select;
var Option = Select.Option;

React.render(
<form className="ant-form-horizontal">
  <div className="ant-form-item">
    <label className="col-6" htmlFor="site1">标签输入框:</label>
    <div className="col-16">
      <div className="ant-input-group">
        <span className="ant-input-group-addon" id="basic-addon1">Http://</span>
        <input type="text" id="site1" className="ant-input" defaultValue="mysite.com" />
      </div>
    </div>
  </div>
  <div className="ant-form-item">
    <label className="col-6" htmlFor="site3">标签输入框:</label>
    <div className="col-16">
      <div className="ant-input-group">
        <span className="ant-input-group-addon" id="basic-addon3">Http://</span>
        <input type="text" className="ant-input" id="site3" defaultValue="mysite" />
        <span className="ant-input-group-addon" id="basic-addon4">.com</span>
      </div>
    </div>
  </div>
  <div className="ant-form-item">
    <label className="col-6" htmlFor="site4">select 标签输入框:</label>
    <div className="col-16">
      <div className="ant-input-group">
        <input type="text" className="ant-input" id="site4" placeholder="www.mysite" />
        <div className="ant-input-group-wrap">
          <Select defaultValue=".com" style={{width:70}}>
            <Option value=".com">.com</Option>
            <Option value=".jp">.jp</Option>
            <Option value=".cn">.cn</Option>
            <Option value=".org">.org</Option>
          </Select>
        </div>
      </div>
    </div>
  </div>
  <div className="ant-form-item">
    <label className="col-6" htmlFor="certNo1">输入身份证:</label>
    <div className="col-16">
      <div className="ant-input-group">
        <div className="col-6">
          <input className="ant-input" type="text" id="certNo1" />
        </div>
        <div className="col-6">
          <input className="ant-input" type="text" id="certNo2" />
        </div>
        <div className="col-6">
          <input className="ant-input" type="text" id="certNo3" />
        </div>
        <div className="col-6">
          <input className="ant-input" type="text" id="certNo4" />
        </div>
      </div>
    </div>
  </div>
  <div className="ant-form-item">
    <label className="col-6" htmlFor="tel1">电话号码:</label>
    <div className="col-16">
      <div className="row">
        <div className="col-4">
          <input className="ant-input" type="text" id="tel1" defaultValue="086" />
        </div>
        <div className="col-2">
          <p className="ant-form-split">--</p>
        </div>
        <div className="col-18">
          <div className="ant-input-group">
            <div className="col-8">
              <input className="ant-input" type="text" id="tel1" />
            </div>
            <div className="col-8">
              <input className="ant-input" type="text" id="tel2" />
            </div>
            <div className="col-8">
              <input className="ant-input" type="text" id="tel3" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</form>
, document.getElementById('components-form-demo-inputs'));

      Input 输入框集合

带标签的输入框:使用 .ant-input-group 类并结合 .ant-input-group-addon 类可以创建带标签的输入框。


text:
<configuration debug="false">
  <!-- debug: reports all changes to this configuration on System.out -->

  <include resource="org/terasology/engine/logback/setup.xml" />

  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <!-- encoders are assigned the type PatternLayoutEncoder by default -->
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>

    <include resource="org/terasology/engine/logback/filter-reflections.xml" />
  </appender>

  <!-- JUnit collects console output during test execution
       and include it in the report for the test. -->
  <root level="${logOverrideLevel:-debug}">
    <appender-ref ref="CONSOLE" />
  </root>

  <logger name="org.terasology" level="${logOverrideLevel:-info}" />
  <logger name="org.terasology.engine.i18n" level="warn" />
  <logger name="org.reflections.Reflections" level="warn" />

</configuration>


text:
Releasing
========

 1. Change the version in `gradle.properties` to a non-SNAPSHOT version.
 2. Update the `CHANGELOG.md` for the upcoming release.
 3. Update the `README.md` with the new version dependencies.
 4. `git commit -am "Prepare version x.y.z for release"` (where x.y.z is the new version)
 5. `git tag -a x.y.z -m "Version x.y.z"` (where x.y.z is the new version)
 6. `./gradlew clean uploadArchives`
 7. Update the `gradle.properties` to the next SNAPSHOT version.
 8. `git commit -am "Prepare next development version"`
 9. `git push && git push --tags`
 10. Visit [Sonatype Nexus](https://oss.sonatype.org/) and promote the artifact:
    * Log-in (credentials are in 'Nexus - VanGogh' entry in 1Password PSPDFKit Developers vault
    * Go to `Staging Repositories` and find the latest VanGogh repository in the list
    * Select it and press `Close` in the menu
    * Once the closing process is done (10-15 mins), select the same thing and press `Promote`
    * Once that is done (again 10-15 mins), select it one more time and press `Release`


text:
// Usage: capture_tpu_profile --service_addr="localhost:8466" --logdir=/tmp/log
//
// Initiates a TPU profiling on the TPUProfiler service at service_addr,
// receives and dumps the profile data to a tensorboard log directory.

#include "grpc++/grpc++.h"

#include <cstdio>
#include <ctime>
#include <vector>

#include "tensorflow/contrib/tpu/profiler/dump_tpu_profile.h"
#include "tensorflow/contrib/tpu/profiler/tpu_profiler.grpc.pb.h"
#include "tensorflow/contrib/tpu/profiler/tpu_profiler_analysis.grpc.pb.h"
#include "tensorflow/contrib/tpu/profiler/version.h"
#include "tensorflow/core/distributed_runtime/rpc/grpc_util.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/util/command_line_flags.h"

namespace tensorflow {
namespace tpu {
namespace {

using ::tensorflow::TPUProfileAnalysis;
using ::tensorflow::TPUProfiler;

constexpr uint64 kMaxEvents = 1000000;

string GetCurrentTimeStampAsString() {
  char s[128];
  std::time_t t = std::time(nullptr);
  CHECK_NE(std::strftime(s, sizeof(s), "%F_%T", std::localtime(&t)), 0);
  return s;
}

Status ValidateHostPortPair(const string& host_port) {
  uint32 port;
  std::vector<string> parts = str_util::Split(host_port, ':');
  // Must be host:port, port must be a number, host must not contain a '/',
  // host also must not be empty.
  if (parts.size() != 2 || !strings::safe_strtou32(parts[1], &port) ||
      parts[0].find("/") != string::npos || parts[0].empty()) {
    return errors::InvalidArgument("Could not interpret \"", host_port,
                                   "\" as a host-port pair.");
  }
  return Status::OK();
}

ProfileRequest PopulateProfileRequest(int duration_ms,
                                      const string& repository_root,
                                      const string& session_id,
                                      const ProfileOptions& opts) {
  ProfileRequest request;
  request.set_duration_ms(duration_ms);
  request.set_max_events(kMaxEvents);
  if (tensorflow::str_util::StartsWith(repository_root, "gs://")) {
    // For backward compatibilities, only generate tracetable etc when the
    // user provide a GCS path for model directory.
    request.set_repository_root(repository_root);
    request.set_session_id(session_id);
  }
  request.add_tools("op_profile");
  request.add_tools("input_pipeline");
  request.add_tools("memory_viewer");
  request.add_tools("overview_page");
  *request.mutable_opts() = opts;
  std::cout << "Limiting the number of trace events to " << kMaxEvents
            << std::endl;
  return request;
}

// Returns whether the returned trace is empty.
// Failure are handled by CHECK, i.e. abort()
bool Profile(const string& service_addr, const string& logdir, int duration_ms,
             const string& repository_root, const string& session_id,
             const ProfileOptions& opts) {
  ProfileRequest request =
      PopulateProfileRequest(duration_ms, repository_root, session_id, opts);

  ::grpc::ClientContext context;
  ::grpc::ChannelArguments channel_args;
  // TODO(ioeric): use `SetMaxReceiveMessageSize` instead once it's available.
  // TODO(qiuminxu): use `NewHostPortGrpcChannel` instead once their
  // `ValidateHostPortPair` checks for empty host string case.
  channel_args.SetInt(GRPC_ARG_MAX_MESSAGE_LENGTH,
                      std::numeric_limits<int32>::max());
  std::unique_ptr<TPUProfiler::Stub> stub =
      TPUProfiler::NewStub(::grpc::CreateCustomChannel(
          "dns:///" + service_addr, ::grpc::InsecureChannelCredentials(),
          channel_args));
  ProfileResponse response;
  TF_QCHECK_OK(FromGrpcStatus(stub->Profile(&context, request, &response)));

  if (!response.encoded_trace().empty()) {
    TF_CHECK_OK(tensorflow::tpu::WriteTensorboardTPUProfile(
        logdir, session_id, "", response, &std::cout));
    // Print this at the end so that it's not buried in irrelevant LOG messages.
    std::cout
        << "NOTE: using the trace duration " << duration_ms << "ms."
        << std::endl
        << "Set an appropriate duration (with --duration_ms) if you "
           "don't see a full step in your trace or the captured trace is too "
           "large."
        << std::endl;
  }

  return response.encoded_trace().empty();
}

// Start a new profiling session that include all the hosts included in
// hostnames, for the time interval of duration_ms. Possibly save the profiling
// result in the directory specified by repository_root and session_id.
bool NewSession(const string& service_addr,
                const std::vector<tensorflow::string>& hostnames,
                int duration_ms, const string& repository_root,
                const string& session_id, const ProfileOptions& opts) {
  NewProfileSessionRequest new_session_request;
  *new_session_request.mutable_request() =
      PopulateProfileRequest(duration_ms, repository_root, session_id, opts);
  new_session_request.set_repository_root(repository_root);
  new_session_request.set_session_id(session_id);
  for (const auto& hostname : hostnames) {
    new_session_request.add_hosts(hostname);
  }

  ::grpc::ClientContext context;
  ::grpc::ChannelArguments channel_args;
  // TODO(qiuminxu): use `NewHostPortGrpcChannel` instead once their
  // `ValidateHostPortPair` checks for empty host string case.
  channel_args.SetMaxReceiveMessageSize(std::numeric_limits<int32>::max());
  // TODO(jiesun): GRPC support following relevant naming scheme:
  // 1. dns:///host:port
  // 2. ipv4:host:port or ipv6:[host]:port
  // We might need to change the prefix which depends on what TPU name resolver
  // will give us.
  std::unique_ptr<TPUProfileAnalysis::Stub> stub =
      TPUProfileAnalysis::NewStub(::grpc::CreateCustomChannel(
          "dns:///" + service_addr, ::grpc::InsecureChannelCredentials(),
          channel_args));
  NewProfileSessionResponse new_session_response;
  TF_QCHECK_OK(FromGrpcStatus(
      stub->NewSession(&context, new_session_request, &new_session_response)));

  std::cout << "Profile session succeed for host(s):"
            << str_util::Join(hostnames, ",") << std::endl;
  return new_session_response.empty_trace();
}

}  // namespace
}  // namespace tpu
}  // namespace tensorflow

int main(int argc, char** argv) {
  tensorflow::string FLAGS_service_addr;
  tensorflow::string FLAGS_logdir;
  tensorflow::string FLAGS_workers_list;
  int FLAGS_duration_ms = 2000;
  int FLAGS_num_tracing_attempts = 3;
  bool FLAGS_include_dataset_ops = true;
  std::vector<tensorflow::Flag> flag_list = {
      tensorflow::Flag("service_addr", &FLAGS_service_addr,
                       "Address of TPU profiler service e.g. localhost:8466"),
      tensorflow::Flag("workers_list", &FLAGS_workers_list,
                       "The list of worker TPUs that we are about to profile "
                       "in the current session."),
      tensorflow::Flag("logdir", &FLAGS_logdir,
                       "Path of TensorBoard log directory e.g. /tmp/tb_log, "
                       "gs://tb_bucket"),
      tensorflow::Flag("duration_ms", &FLAGS_duration_ms,
                       "Duration of tracing in ms. Default is 2000ms."),
      tensorflow::Flag("num_tracing_attempts", &FLAGS_num_tracing_attempts,
                       "Automatically retry N times when no trace event "
                       "is collected. Default is 3."),
      tensorflow::Flag("include_dataset_ops", &FLAGS_include_dataset_ops,
                       "Set to false to profile longer TPU device traces."),
  };

  std::cout << "Welcome to the Cloud TPU Profiler v" << TPU_PROFILER_VERSION
            << std::endl;

  tensorflow::string usage = tensorflow::Flags::Usage(argv[0], flag_list);
  bool parse_ok = tensorflow::Flags::Parse(&argc, argv, flag_list);
  if (!parse_ok || FLAGS_service_addr.empty() || FLAGS_logdir.empty()) {
    std::cout << usage.c_str() << std::endl;
    return 2;
  }
  tensorflow::Status status =
      tensorflow::tpu::ValidateHostPortPair(FLAGS_service_addr);
  if (!status.ok()) {
    std::cout << status.error_message() << std::endl;
    std::cout << usage.c_str() << std::endl;
    return 2;
  }
  tensorflow::port::InitMain(argv[0], &argc, &argv);

  // Sets the minimum duration_ms and tracing attempts to one.
  int duration_ms = std::max(FLAGS_duration_ms, 1);
  int remaining_attempts = std::max(FLAGS_num_tracing_attempts, 1);
  tensorflow::ProfileOptions opts;
  opts.set_include_dataset_ops(FLAGS_include_dataset_ops);
  tensorflow::ProfileResponse response;

  // Use the current timestamp as the run name.
  tensorflow::string session_id =
      tensorflow::tpu::GetCurrentTimeStampAsString();
  constexpr char kProfilePluginDirectory[] = "plugins/profile/";
  tensorflow::string repository_root =
      ::tensorflow::io::JoinPath(FLAGS_logdir, kProfilePluginDirectory);
  std::vector<tensorflow::string> hostnames =
      tensorflow::str_util::Split(FLAGS_workers_list, ",");

  bool empty_trace = false;
  while (true) {
    std::cout << "Starting to profile TPU traces for " << duration_ms << " ms. "
              << "Remaining attempt(s): " << remaining_attempts-- << std::endl;
    if (hostnames.empty()) {
      empty_trace = tensorflow::tpu::Profile(FLAGS_service_addr, FLAGS_logdir,
                                             duration_ms, repository_root,
                                             session_id, opts);
    } else {
      tensorflow::string tpu_master = FLAGS_service_addr;
      empty_trace =
          tensorflow::tpu::NewSession(tpu_master, hostnames, duration_ms,
                                      repository_root, session_id, opts);
    }
    if (remaining_attempts <= 0 || !empty_trace) break;
    std::cout << "No trace event is collected. Automatically retrying."
              << std::endl
              << std::endl;
  }

  if (empty_trace) {
    std::cout << "No trace event is collected after "
              << FLAGS_num_tracing_attempts << " attempt(s). "
              << "Perhaps, you want to try again (with more attempts?)."
              << std::endl
              << "Tip: increase number of attempts with --num_tracing_attempts."
              << std::endl;
    // Don't dump profile data if no trace is collected.
    return 0;
  }

  return 0;
}


text:
export { default as CredentialPluginSelected } from './CredentialPluginSelected';
export { default as CredentialPluginField } from './CredentialPluginField';


text:
namespace System.ServiceModel.ComIntegration
{
    using System;
    using System.ServiceModel.Channels;
    using System.Runtime.InteropServices;

    [Serializable]
    [ComVisible(false)]
    enum ThreadPoolOption
    {
        None = 0,
        Inherit = 1,
        STA = 2,
        MTA = 3
    }

    [Serializable]
    [ComVisible(false)]
    enum BindingOption
    {
        NoBinding = 0,
        BindingToPoolThread = 1
    }

    [Serializable]
    [ComVisible(false)]
    enum SxsOption
    {
        Ignore = 0,
        Inherit = 1,
        New = 2
    }

    [Serializable]
    [ComVisible(false)]
    enum PartitionOption
    {
        Ignore = 0,
        Inherit = 1,
        New = 2
    }

    [Serializable]
    [ComVisible(false)]
    enum TransactionConfig
    {
        NoTransaction = 0,
        IfContainerIsTransactional = 1,
        CreateTransactionIfNecessary = 2,
        NewTransaction = 3
    }

    [Serializable]
    [ComVisible(false)]
    enum CSC_SxsConfig
    {
        CSC_NoSxs = 0,
        CSC_InheritSxs = 1,
        CSC_NewSxs = 2
    }

    [ComImport]
    [Guid("186d89bc-f277-4bcc-80d5-4df7b836ef4a")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    interface IServiceThreadPoolConfig
    {
        void SelectThreadPool(ThreadPoolOption threadPool);
        void SetBindingInfo(BindingOption binding);
    }

    [ComImport]
    [Guid("80182d03-5ea4-4831-ae97-55beffc2e590")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    interface IServicePartitionConfig
    {
        void PartitionConfig(PartitionOption partitionConfig);
        void PartitionID(
            [In, MarshalAs(UnmanagedType.LPStruct)] Guid guidPartitionID);
    }

    [ComImport]
    [Guid("33CAF1A1-FCB8-472b-B45E-967448DED6D8")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    interface IServiceSysTxnConfig
    {
        // NOTE: This is actually IServiceSysTxnConfigInternal.
        void ConfigureTransaction(TransactionConfig transactionConfig);
        void IsolationLevel(int option);
        void TransactionTimeout(uint ulTimeoutSec);
        void BringYourOwnTransaction([MarshalAs(UnmanagedType.LPWStr)] string szTipURL);
        void NewTransactionDescription([MarshalAs(UnmanagedType.LPWStr)] string szTxDesc);
        void ConfigureBYOT(IntPtr pITxByot);
        void ConfigureBYOTSysTxn(IntPtr pITxByot);
    }

    [ComImport]
    [Guid("C7CD7379-F3F2-4634-811B-703281D73E08")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    interface IServiceSxsConfig
    {
        void SxsConfig(CSC_SxsConfig sxsConfig);
        void SxsName([MarshalAs(UnmanagedType.LPWStr)] string szSxsName);
        void SxsDirectory([MarshalAs(UnmanagedType.LPWStr)] string szSxsDirectory);
    }

    [ComImport]
    [Guid("59f4c2a3-d3d7-4a31-b6e4-6ab3177c50b9")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    interface IServiceTransactionConfig
    {
        // NOTE: This is actually IServiceSysTxnConfigInternal.
        void ConfigureTransaction(TransactionConfig transactionConfig);
        void IsolationLevel(int option);
        void TransactionTimeout(uint ulTimeoutSec);
        void BringYourOwnTransaction([MarshalAs(UnmanagedType.LPWStr)] string szTipURL);
        void NewTransactionDescription([MarshalAs(UnmanagedType.LPWStr)] string szTxDesc);
        void ConfigureBYOT(IntPtr pITxByot);
    }

    [ComImport]
    [Guid("ecabb0c8-7f19-11d2-978e-0000f8757e2a")]
    class CServiceConfig { }

    [ComImport]
    [Guid("BD3E2E12-42DD-40f4-A09A-95A50C58304B")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    interface IServiceCall
    {
        void OnCall();
    }

    [ComImport]
    [Guid("67532E0C-9E2F-4450-A354-035633944E17")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    interface IServiceActivity
    {
        void SynchronousCall(IServiceCall pIServiceCall);
        void AsynchronousCall(IServiceCall pIServiceCall);
        void BindToCurrentThread();
        void UnbindFromThread();
    }

    [ComImport]
    [Guid("000001ce-0000-0000-C000-000000000046")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    interface IComThreadingInfo
    {
        void GetCurrentApartmentType(out uint aptType);
        void GetCurrentThreadType(out uint threadType);
        void GetCurrentLogicalThreadId(out Guid guidLogicalThreadID);
        void SetCurrentLogicalThreadId([In, MarshalAs(UnmanagedType.LPStruct)] Guid guidLogicalThreadID);
    };

    [ComImport,
     Guid("75B52DDB-E8ED-11D1-93AD-00AA00BA3258"),
     InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
    internal interface IObjectContextInfo
    {
        [PreserveSig]
        [return: MarshalAs(UnmanagedType.Bool)]
        bool IsInTransaction();
        [PreserveSig]
        [return: MarshalAs(UnmanagedType.Interface)]
        Object GetTransaction();
        void GetTransactionId(out Guid guid);
        void GetActivityId(out Guid guid);
        void GetContextId(out Guid guid);
    }

}


text:
Three robos, which work as 3 managers for adding new items on olx.ua, wordpress woocommerce market and vk group as product items.

Main goal is 25hours working and adding brand new items from google drive spreadsheets to 3 different traffic ways.

#1st - OLX.
Robo which calls olx_robo will track gDrive spreadsheets and when it understand that here is new item - olx_robo will add this item
in another gDrive spreadsheets, which working for autoadding new items as new product in olx.ua

To-do list for my tobowork
> 1. Connect to gDrive spreadsheets
> 2. Understand which raws I should listen and check;
> 3. Detect new items
> 4. If I find new item, I should check am I adding this one in past?
> 5. If I see this item is brand new, I'm grabbing this data...
> 6. ... and I go to my canvac (my workspace) and ask it "Hey there. Can I come in?" (log in gDrive for OLX)
> 7. After successful login I'm creating new product...
> 8. ... and adding new title inside it...
> 9. ... and adding new descr...
> 10. ... and adding new thumbnail...
> 11. ... and adding new photos...
> 12. ... and adding new categories or just adding existing category
> 13. ... and I say:"Yeah, please publish it, love"
> 13-1. Check publishing post. Does post publich: True or False.
14. If all is okey, I start from to-do #1

#2nd - Wordpress
Robo which calls wp_robo will track gDrive spreadsheets and add new item from this gDrive inside woocommerce market as a brand new prodect (with title, descr, photos and call-to-actions)

To-do list for my tobowork
1. Connect to gDrive spreadsheets
2. Understand which raws I should listen and check;
3. Detect new items
4. If I find new item, I should check am I adding this one in past?
5. If I see this item is brand new, I'm grabbing this data...
6. ... and I go to my canvac (my workspace) and ask it "Hey there. Can I come in?" (log in Wordpress admin panel)
7. After successful login I'm creating new product...
8. ... and adding new title inside it...
9. ... and adding new descr...
10. ... and adding new thumbnail...
11. ... and adding new photos...
12. ... and adding new categories or just adding existing category
13. ... and I say:"Yeah, please publish it, love"
13-1. Check publishing post. Does post publich: True or False.
14. If all is okey, I start from to-do #1

#3th - VK
Robo vk_robo will do the same, but it'll add new item in current public page. Each item - brand new product.

To-do list for my tobowork
1. Connect to gDrive spreadsheets
2. Understand which raws I should listen and check;
3. Detect new items
4. If I find new item, I should check am I adding this one in past?
5. If I see this item is brand new, I'm grabbing this data...
6. ... and I go to my canvac (my workspace) and ask it "Hey there. Can I come in?" (log in Vk.com)
7. After successful login I'm creating new product...
8. ... and adding new title inside it...
9. ... and adding new descr...
10. ... and adding new thumbnail...
11. ... and adding new photos...
12. ... and adding new categories or just adding existing category
13. ... and I say:"Yeah, please publish it, love"
13-1. Check publishing post. Does post publich: True or False.
14. If all is okey, I start from to-do #1
<<<<<<< HEAD

---
For todo #1

Google Drive API's guide and "how-to" - https://developers.google.com/api-client-library/python/?hl=ru
Google Drive on github - https://github.com/googledrive
Stack overflow for G Drive API - https://stackoverflow.com/questions/tagged/google-drive-sdk

For OLX
Unofficial OLX API - https://github.com/umayr/olx/tree/master/olx.api
=======
>>>>>>> origin/master