text:
from django.core.exceptions import MiddlewareNotUsed
from django.conf import settings
from django.db import connection
from redis.connection import Connection
from time import time

class SqldumpMiddleware(object):
    def __init__(self):
        if not settings.DEBUG:
            raise MiddlewareNotUsed()

    def process_view(self, request, callback, callback_args, callback_kwargs):
        if settings.DEBUG:
            # save old methods
            self.orig_pack_command = \
                    Connection.pack_command
            # instrument methods to record messages
            Connection.pack_command = \
                    self._instrument(Connection.pack_command)
        return None

    def process_response(self, request, response):
        if settings.DEBUG and hasattr(self, 'orig_pack_command'):
            # remove instrumentation from redis
            Connection.pack_command = \
                    self.orig_pack_command
        return response

    def _instrument(self, original_method):
        def instrumented_method(*args, **kwargs):
            message = self.process_message(*args, **kwargs)
            if not message:
                return original_method(*args, **kwargs)
            start = time()
            result = original_method(*args, **kwargs)
            stop = time()
            duration = stop - start
            connection.queries.append({
                'redis': message,
                'time': '%.3f' % duration,
            })
            return result
        return instrumented_method

    def process_message(self, *args, **kwargs):
        query = ' '.join([str(arg) for arg in args if not isinstance(arg, Connection)])
        return { 'query': query, }


text:
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>spiral</title>
	<script src="http://microsoft.github.io/maker.js/target/js/browser.maker.js"></script>
	<script>
		var module = {};
	</script>

	<script src="index.js"></script>
</head>
<body>
	<script>
		var makerjs = require('makerjs');
		var model = new Spiral(50, 50, 1);
		document.write(makerjs.exporter.toSVG(model));
	</script>
</body>
</html>

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8" ?>
<testsuite failures="0" time="0" errors="0" skipped="0" tests="1" name="cn.jdworks.etl.executor.TimerTest">
  <properties>
    <property name="java.runtime.name" value="Java(TM) SE Runtime Environment"/>
    <property name="sun.boot.library.path" value="D:\Program Files\Java\jdk1.7\jre\bin"/>
    <property name="java.vm.version" value="24.65-b04"/>
    <property name="java.vm.vendor" value="Oracle Corporation"/>
    <property name="maven.multiModuleProjectDirectory" value="E:\MavenP\etl"/>
    <property name="java.vendor.url" value="http://java.oracle.com/"/>
    <property name="path.separator" value=";"/>
    <property name="guice.disable.misplaced.annotation.check" value="true"/>
    <property name="java.vm.name" value="Java HotSpot(TM) 64-Bit Server VM"/>
    <property name="file.encoding.pkg" value="sun.io"/>
    <property name="user.script" value=""/>
    <property name="user.country" value="CN"/>
    <property name="sun.java.launcher" value="SUN_STANDARD"/>
    <property name="sun.os.patch.level" value="Service Pack 1"/>
    <property name="java.vm.specification.name" value="Java Virtual Machine Specification"/>
    <property name="user.dir" value="E:\MavenP\etl"/>
    <property name="java.runtime.version" value="1.7.0_67-b01"/>
    <property name="java.awt.graphicsenv" value="sun.awt.Win32GraphicsEnvironment"/>
    <property name="java.endorsed.dirs" value="D:\Program Files\Java\jdk1.7\jre\lib\endorsed"/>
    <property name="os.arch" value="amd64"/>
    <property name="java.io.tmpdir" value="C:\Users\Rayleigh\AppData\Local\Temp\"/>
    <property name="line.separator" value="
"/>
    <property name="java.vm.specification.vendor" value="Oracle Corporation"/>
    <property name="user.variant" value=""/>
    <property name="os.name" value="Windows 7"/>
    <property name="classworlds.conf" value="D:\Maven\apache-maven-3.3.1\bin\..\bin\m2.conf"/>
    <property name="sun.jnu.encoding" value="GBK"/>
    <property name="java.library.path" value="D:\Program Files\Java\jdk1.7\bin;C:\windows\Sun\Java\bin;C:\windows\system32;C:\windows;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v6.5\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v6.5\libnvvp;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;D:\Program Files\Java\jdk1.7\bin;D:\Python27;D:\Python27\Scripts;D:\Python27\Lib;D:\AndroidSDK\sdk\platform-tools;D:\MinGW\bin;D:\Maven\apache-maven-3.3.1\bin;D:\Tomcat\apache-tomcat-7.0.61\lib;D:\Tomcat\apache-tomcat-7.0.61\lib\servlet-api.jar;D:\Tomcat\apache-tomcat-7.0.61\lib\jsp-api.jar;D:\Program Files\Git\bin;D:\Program Files\nodejs\;C:\Users\Rayleigh\AppData\Roaming\npm;."/>
    <property name="java.specification.name" value="Java Platform API Specification"/>
    <property name="java.class.version" value="51.0"/>
    <property name="sun.management.compiler" value="HotSpot 64-Bit Tiered Compilers"/>
    <property name="os.version" value="6.1"/>
    <property name="user.home" value="C:\Users\Rayleigh"/>
    <property name="user.timezone" value="Asia/Shanghai"/>
    <property name="java.awt.printerjob" value="sun.awt.windows.WPrinterJob"/>
    <property name="java.specification.version" value="1.7"/>
    <property name="file.encoding" value="GBK"/>
    <property name="user.name" value="Rayleigh"/>
    <property name="java.class.path" value="D:\Maven\apache-maven-3.3.1\bin\..\boot\plexus-classworlds-2.5.2.jar"/>
    <property name="java.vm.specification.version" value="1.7"/>
    <property name="sun.arch.data.model" value="64"/>
    <property name="java.home" value="D:\Program Files\Java\jdk1.7\jre"/>
    <property name="sun.java.command" value="org.codehaus.plexus.classworlds.launcher.Launcher clean install"/>
    <property name="java.specification.vendor" value="Oracle Corporation"/>
    <property name="user.language" value="zh"/>
    <property name="awt.toolkit" value="sun.awt.windows.WToolkit"/>
    <property name="java.vm.info" value="mixed mode"/>
    <property name="java.version" value="1.7.0_67"/>
    <property name="java.ext.dirs" value="D:\Program Files\Java\jdk1.7\jre\lib\ext;C:\windows\Sun\Java\lib\ext"/>
    <property name="sun.boot.class.path" value="D:\Program Files\Java\jdk1.7\jre\lib\resources.jar;D:\Program Files\Java\jdk1.7\jre\lib\rt.jar;D:\Program Files\Java\jdk1.7\jre\lib\sunrsasign.jar;D:\Program Files\Java\jdk1.7\jre\lib\jsse.jar;D:\Program Files\Java\jdk1.7\jre\lib\jce.jar;D:\Program Files\Java\jdk1.7\jre\lib\charsets.jar;D:\Program Files\Java\jdk1.7\jre\lib\jfr.jar;D:\Program Files\Java\jdk1.7\jre\classes"/>
    <property name="java.vendor" value="Oracle Corporation"/>
    <property name="maven.home" value="D:\Maven\apache-maven-3.3.1\bin\.."/>
    <property name="file.separator" value="\"/>
    <property name="java.vendor.url.bug" value="http://bugreport.sun.com/bugreport/"/>
    <property name="sun.cpu.endian" value="little"/>
    <property name="sun.io.unicode.encoding" value="UnicodeLittle"/>
    <property name="sun.desktop" value="windows"/>
    <property name="sun.cpu.isalist" value="amd64"/>
  </properties>
  <testcase time="0" classname="cn.jdworks.etl.executor.TimerTest" name="Test"/>
</testsuite>


text:
<?php

/**
 *
 * Customer reports admin controller
 *
 * @author      Magento Core Team <core@magentocommerce.com>
 */
namespace Magento\Reports\Controller\Adminhtml\Report;

abstract class Customer extends \Magento\Backend\App\Action
{
    /**
     * @var \Magento\Framework\App\Response\Http\FileFactory
     */
    protected $_fileFactory;

    /**
     * @param \Magento\Backend\App\Action\Context $context
     * @param \Magento\Framework\App\Response\Http\FileFactory $fileFactory
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\App\Response\Http\FileFactory $fileFactory
    ) {
        $this->_fileFactory = $fileFactory;
        parent::__construct($context);
    }

    /**
     * Add reports and customer breadcrumbs
     *
     * @return $this
     */
    public function _initAction()
    {
        $act = $this->getRequest()->getActionName();
        if (!$act) {
            $act = 'default';
        }

        $this->_view->loadLayout();
        $this->_addBreadcrumb(__('Reports'), __('Reports'));
        $this->_addBreadcrumb(__('Customers'), __('Customers'));
        return $this;
    }

    /**
     * Determine if action is allowed for reports module
     *
     * @return bool
     */
    protected function _isAllowed()
    {
        switch ($this->getRequest()->getActionName()) {
            case 'accounts':
                return $this->_authorization->isAllowed('Magento_Reports::accounts');
                break;
            case 'orders':
                return $this->_authorization->isAllowed('Magento_Reports::customers_orders');
                break;
            case 'totals':
                return $this->_authorization->isAllowed('Magento_Reports::totals');
                break;
            default:
                return $this->_authorization->isAllowed('Magento_Reports::customers');
                break;
        }
    }
}


text:
<!DOCTYPE html>

	<title></title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />

	%SCRIPTS%


text:
  Tabel materi untuk penyuluh. Anda dapat melakukan penambahanan, pengubahan dan penghapusan pada materi.

    	<button type="button" class="btn btn-primary" (click)="showForm(true)">Tambah Materi</button>

      <button type="button" class="btn btn-danger" (click)="showForm(false)">Batal</button>

    <ng2-smart-table [settings]="settings" [source]="source" (deleteConfirm)="onDeleteConfirm($event)" (editConfirm)="onSaveConfirm($event)"></ng2-smart-table>

<ba-card [hidden]="!add">

Tambah Materi

    Judul Materi
    <input placeholder="Tuliskan judul materi. Misal: Perawatan tanaman" [(ngModel)]="judul" [disabled]="submit" type="text" class="form-control">

        Keterangan Materi
        <textarea placeholder="Tuliskan keterangan materi" [(ngModel)]="keterangan" [disabled]="submit" type="number" min="0" class="form-control" id="harga"></textarea>

        Unggah Fail
        <input [disabled]="!judul || !keterangan" [(ngModel)]="fileupload" type="file" name="upload" (change)="fileChangeEvent($event)" class="form-control">

    <button data-dismiss="modal" [disabled]="!judul || !keterangan || !submit" (click)="upload()" type="button" class="btn btn-primary btn-lg"> Tambah</button>

</ba-card>

        <button type="button" class="close" data-dismiss="modal" (click)="childModal.hide()">×</button>

Hapus Komoditas

{{hapusText}}

        <button type="button" class="btn btn-default" data-dismiss="modal" (click)="childModal.hide()">Close</button>
        <button type="button" data-dismiss="modal" (click)="deleteMateriFunction();childModal.hide()" class="btn btn-danger">Submit</button>


text:
<?php

Route::group(['prefix' => 'zleader'], function() {
    Route::get('/', 'DashboardController@index');
    Route::get('/leads', 'LeadController@index');
    Route::get('/leads/datagrid/source', 'LeadController@datagrid');
    Route::get('/leads/{lead_id}', 'LeadController@show');
    Route::patch('/leads/{lead_id}', 'LeadController@patch');
    Route::get('/forms', 'FormController@index');
    Route::get('/forms/json', 'FormController@jsonIndex');
    Route::get('/config', 'ConfigController@index');
    Route::get('/companies', 'CompanyController@index');
    Route::get('/areas', 'AreaController@index');
    Route::get('/fields', 'FieldController@index');
});


text: These patterns are specifically concerned with communication between objects.


text:
Task.new(:release) do |task|
  task.description = "Just release it"
  task.dependencies.clear # redefine
  task.block do |*args|

  end
end


text:
struct lzma_coder_s {
	enum {
		SEQ_STREAM_HEADER,
		SEQ_BLOCK_INIT,
		SEQ_BLOCK_HEADER,
		SEQ_BLOCK_ENCODE,
		SEQ_INDEX_ENCODE,
		SEQ_STREAM_FOOTER,
	} sequence;

	/// True if Block encoder has been initialized by
	/// lzma_stream_encoder_init() or stream_encoder_update()
	/// and thus doesn't need to be initialized in stream_encode().
	bool block_encoder_is_initialized;

	/// Block
	lzma_next_coder block_encoder;

	/// Options for the Block encoder
	lzma_block block_options;

	/// The filter chain currently in use
	lzma_filter filters[LZMA_FILTERS_MAX + 1];

	/// Index encoder. This is separate from Block encoder, because this
	/// doesn't take much memory, and when encoding multiple Streams
	/// with the same encoding options we avoid reallocating memory.
	lzma_next_coder index_encoder;

	/// Index to hold sizes of the Blocks
	lzma_index *index;

	/// Read position in buffer[]
	size_t buffer_pos;

	/// Total number of bytes in buffer[]
	size_t buffer_size;

	/// Buffer to hold Stream Header, Block Header, and Stream Footer.
	/// Block Header has biggest maximum size.
	uint8_t buffer[LZMA_BLOCK_HEADER_SIZE_MAX];
};

static lzma_ret
block_encoder_init(lzma_coder *coder, lzma_allocator *allocator)
{
	// Prepare the Block options. Even though Block encoder doesn't need
	// compressed_size, uncompressed_size, and header_size to be
	// initialized, it is a good idea to do it here, because this way
	// we catch if someone gave us Filter ID that cannot be used in
	// Blocks/Streams.
	coder->block_options.compressed_size = LZMA_VLI_UNKNOWN;
	coder->block_options.uncompressed_size = LZMA_VLI_UNKNOWN;

	return_if_error(lzma_block_header_size(&coder->block_options));

	// Initialize the actual Block encoder.
	return lzma_block_encoder_init(&coder->block_encoder, allocator,
			&coder->block_options);
}

static lzma_ret
stream_encode(lzma_coder *coder, lzma_allocator *allocator,
		const uint8_t *LZMA_RESTRICT in, size_t *LZMA_RESTRICT in_pos,
		size_t in_size, uint8_t *LZMA_RESTRICT out,
		size_t *LZMA_RESTRICT out_pos, size_t out_size, lzma_action action)
{
	// Main loop
	while (*out_pos < out_size)
	switch (coder->sequence) {
	case SEQ_STREAM_HEADER:
	case SEQ_BLOCK_HEADER:
	case SEQ_STREAM_FOOTER:
		lzma_bufcpy(coder->buffer, &coder->buffer_pos,
				coder->buffer_size, out, out_pos, out_size);
		if (coder->buffer_pos < coder->buffer_size)
			return LZMA_OK;

		if (coder->sequence == SEQ_STREAM_FOOTER)
			return LZMA_STREAM_END;

		coder->buffer_pos = 0;
		++coder->sequence;
		break;

	case SEQ_BLOCK_INIT: {
		if (*in_pos == in_size) {
			// If we are requested to flush or finish the current
			// Block, return LZMA_STREAM_END immediately since
			// there's nothing to do.
			if (action != LZMA_FINISH)
				return action == LZMA_RUN
						? LZMA_OK : LZMA_STREAM_END;

			// The application had used LZMA_FULL_FLUSH to finish
			// the previous Block, but now wants to finish without
			// encoding new data, or it is simply creating an
			// empty Stream with no Blocks.
			//
			// Initialize the Index encoder, and continue to
			// actually encoding the Index.
			return_if_error(lzma_index_encoder_init(
					&coder->index_encoder, allocator,
					coder->index));
			coder->sequence = SEQ_INDEX_ENCODE;
			break;
		}

		// Initialize the Block encoder unless it was already
		// initialized by lzma_stream_encoder_init() or
		// stream_encoder_update().
		if (!coder->block_encoder_is_initialized)
			return_if_error(block_encoder_init(coder, allocator));

		// Make it false so that we don't skip the initialization
		// with the next Block.
		coder->block_encoder_is_initialized = false;

		// Encode the Block Header. This shouldn't fail since we have
		// already initialized the Block encoder.
		if (lzma_block_header_encode(&coder->block_options,
				coder->buffer) != LZMA_OK)
			return LZMA_PROG_ERROR;

		coder->buffer_size = coder->block_options.header_size;
		coder->sequence = SEQ_BLOCK_HEADER;
		break;
	}

	case SEQ_BLOCK_ENCODE: {
		lzma_vli unpadded_size;

		static const lzma_action convert[4] = {
			LZMA_RUN,
			LZMA_SYNC_FLUSH,
			LZMA_FINISH,
			LZMA_FINISH,
		};

		const lzma_ret ret = coder->block_encoder.code(
				coder->block_encoder.coder, allocator,
				in, in_pos, in_size,
				out, out_pos, out_size, convert[action]);
		if (ret != LZMA_STREAM_END || action == LZMA_SYNC_FLUSH)
			return ret;

		// Add a new Index Record.
		unpadded_size = lzma_block_unpadded_size(
				&coder->block_options);
		assert(unpadded_size != 0);
		return_if_error(lzma_index_append(coder->index, allocator,
				unpadded_size,
				coder->block_options.uncompressed_size));

		coder->sequence = SEQ_BLOCK_INIT;
		break;
	}

	case SEQ_INDEX_ENCODE: {
		const lzma_stream_flags stream_flags = {
			0,
			lzma_index_size(coder->index),
			coder->block_options.check,
		};

		// Call the Index encoder. It doesn't take any input, so
		// those pointers can be NULL.
		const lzma_ret ret = coder->index_encoder.code(
				coder->index_encoder.coder, allocator,
				NULL, NULL, 0,
				out, out_pos, out_size, LZMA_RUN);
		if (ret != LZMA_STREAM_END)
			return ret;

		// Encode the Stream Footer into coder->buffer.

		if (lzma_stream_footer_encode(&stream_flags, coder->buffer)
				!= LZMA_OK)
			return LZMA_PROG_ERROR;

		coder->buffer_size = LZMA_STREAM_HEADER_SIZE;
		coder->sequence = SEQ_STREAM_FOOTER;
		break;
	}

	default:
		assert(0);
		return LZMA_PROG_ERROR;
	}

	return LZMA_OK;
}

static void
stream_encoder_end(lzma_coder *coder, lzma_allocator *allocator)
{
	size_t i;

	lzma_next_end(&coder->block_encoder, allocator);
	lzma_next_end(&coder->index_encoder, allocator);
	lzma_index_end(coder->index, allocator);

	for (i = 0; coder->filters[i].id != LZMA_VLI_UNKNOWN; ++i)
		lzma_free(coder->filters[i].options, allocator);

	lzma_free(coder, allocator);
	return;
}

static lzma_ret
stream_encoder_update(lzma_coder *coder, lzma_allocator *allocator,
		const lzma_filter *filters,
		const lzma_filter *reversed_filters)
{
	size_t i;

	if (coder->sequence <= SEQ_BLOCK_INIT) {
		lzma_ret ret;

		// There is no incomplete Block waiting to be finished,
		// thus we can change the whole filter chain. Start by
		// trying to initialize the Block encoder with the new
		// chain. This way we detect if the chain is valid.
		coder->block_encoder_is_initialized = false;
		coder->block_options.filters = (lzma_filter *)(filters);
		ret = block_encoder_init(coder, allocator);
		coder->block_options.filters = coder->filters;
		if (ret != LZMA_OK)
			return ret;

		coder->block_encoder_is_initialized = true;

	} else if (coder->sequence <= SEQ_BLOCK_ENCODE) {
		// We are in the middle of a Block. Try to update only
		// the filter-specific options.
		return_if_error(coder->block_encoder.update(
				coder->block_encoder.coder, allocator,
				filters, reversed_filters));
	} else {
		// Trying to update the filter chain when we are already
		// encoding Index or Stream Footer.
		return LZMA_PROG_ERROR;
	}

	// Free the copy of the old chain and make a copy of the new chain.
	for (i = 0; coder->filters[i].id != LZMA_VLI_UNKNOWN; ++i)
		lzma_free(coder->filters[i].options, allocator);

	return lzma_filters_copy(filters, coder->filters, allocator);
}

extern lzma_ret
lzma_stream_encoder_init(lzma_next_coder *next, lzma_allocator *allocator,
		const lzma_filter *filters, lzma_check check)
{
	lzma_stream_flags stream_flags = { 0, 0, check };

	lzma_next_coder_init(&lzma_stream_encoder_init, next, allocator);

	if (filters == NULL)
		return LZMA_PROG_ERROR;

	if (next->coder == NULL) {
		next->coder = lzma_alloc(sizeof(lzma_coder), allocator);
		if (next->coder == NULL)
			return LZMA_MEM_ERROR;

		next->code = &stream_encode;
		next->end = &stream_encoder_end;
		next->update = &stream_encoder_update;

		next->coder->filters[0].id = LZMA_VLI_UNKNOWN;
		next->coder->block_encoder = LZMA_NEXT_CODER_INIT;
		next->coder->index_encoder = LZMA_NEXT_CODER_INIT;
		next->coder->index = NULL;
	}

	// Basic initializations
	next->coder->sequence = SEQ_STREAM_HEADER;
	next->coder->block_options.version = 0;
	next->coder->block_options.check = check;

	// Initialize the Index
	lzma_index_end(next->coder->index, allocator);
	next->coder->index = lzma_index_init(allocator);
	if (next->coder->index == NULL)
		return LZMA_MEM_ERROR;

	// Encode the Stream Header
	return_if_error(lzma_stream_header_encode(
			&stream_flags, next->coder->buffer));

	next->coder->buffer_pos = 0;
	next->coder->buffer_size = LZMA_STREAM_HEADER_SIZE;

	// Initialize the Block encoder. This way we detect unsupported
	// filter chains when initializing the Stream encoder instead of
	// giving an error after Stream Header has already written out.
	return stream_encoder_update(
			next->coder, allocator, filters, NULL);
}

extern LZMA_API(lzma_ret)
lzma_stream_encoder(lzma_stream *strm,
		const lzma_filter *filters, lzma_check check)
{
	lzma_next_strm_init2(lzma_stream_encoder_init, strm, filters, check);

	strm->internal->supported_actions[LZMA_RUN] = true;
	strm->internal->supported_actions[LZMA_SYNC_FLUSH] = true;
	strm->internal->supported_actions[LZMA_FULL_FLUSH] = true;
	strm->internal->supported_actions[LZMA_FINISH] = true;

	return LZMA_OK;
}


text:
{% extends 'main/main_base.html' %}
{% set front_page = (events.number == 1) %}

{% block body_class %}with-sidebar{% endblock %}

{% block site_css %}
{{ super() }}

{% endblock %}

{% block sidebar_inner %}
{% include "main/_sidebar_inner.html" %}
{% endblock %}

{% block content_main %}
  {% if front_page %}
    {% for live in live_events %}
    {% set href=url('main:event', live.slug) %}

        <hgroup>

{{ _('Streaming Live Now') }}

            {{ live.title }}

          {% set event = live %}
          {% set curated_groups = get_curated_groups(event) %}
          {% include "main/_event_privacy.html" %}
        </hgroup>

{{ _('Start time:') }} {{ live.start_time|js_date }}

          {# setting live=True here will prevent the thumbnail rotating effect #}
          {{ show_thumbnail(live, '160x90', live=True) }}

        {{ star_tag(event.id, 'live') }}

{{ short_desc(live, 16) | safe_html }}
        {{_('See more') }}

          {{ _('Watch Now') }}

    {% endfor %}
    {% if not tags %}
      {% if channel.slug == 'main' %}

{{ _('Recent Events') }}

      {% else %}
        {% if channel.image and channel.image_is_banner %}
          {% set thumb = thumbnail(channel.image, '650') %}

Feed

        {% else %}

Feed

          {% if channel.image %}
            {% set thumb = thumbnail(channel.image, '100x100') %}

          {% endif %}

{{ channel.name }}

        {% endif %}
        {% if channel.description %}

        {{ channel.description|safe }}

        {% endif %}
        {% for child, count in channel_children %}
          {% if loop.first %}

Sub channels:

          {% endif %}

Feed

{{ child.name }}

          {% if count == 1 %}1 archived event{% else %}{{ count }} archived events{% endif %}

          {% if loop.last %}

          {% endif %}
        {% endfor %}
      {% endif %}
    {% endif %}
  {% endif %}

  {% if tags %}

    {{ _('Videos by tags') }} -
    {% for tag in tags %}
    {{ tag.name }}{% if not loop.last %}, {% endif %}
    {% endfor %}

  {% endif %}

  {% include "main/_events.html" %}
  {% include "main/_paginate.html" %}

{% endblock %}


text:
Pixi Renderer
=============

![pixi.js logo](http://www.goodboydigital.com/pixijs/logo_small.png)

#### JavaScript 2D Renderer ####

The aim of this project is to provide a fast lightweight 2D library that works
across all devices. The Pixi renderer allows everyone to enjoy the power of
hardware acceleration without prior knowledge of webGL. Also its fast.

If you're interested in pixi.js then feel free to follow me on twitter
([@doormat23](https://twitter.com/doormat23)) and I will keep you posted!  And of course check back on our
[site](<http://www.goodboydigital.com/blog/>) as any breakthroughs will be
posted up there too!

### Demos ###

-[Run pixi run](<http://www.goodboydigital.com/runpixierun/>)

-[Bunny Demo](<http://www.goodboydigital.com/pixijs/bunnymark>)

-[photonstorm Balls Demo](<http://gametest.mobi/pixi/balls/>)

-[photonstorm Morph Demo](<http://gametest.mobi/pixi/morph/>)

Thanks to [@photonstorm](https://twitter.com/photonstorm) for providing that last 2 examples and allowing us to share the source code :)

### Current features ###

- WebGL renderer (with automatic smart batching allowing for REALLY fast performance)
- Canvas renderer
- Full scene graph
- Super easy to use API (similar to the flash display list API)
- Support for texture atlas's
- Asset loader / sprite sheet loader
- Auto detect which renderer should be used

### Coming soon ###

- Filters
- Render Texture
- Text
- Interactivity

### Coming later ###

-   Awesome Post processing effects

### Usage ###

```javascript

	/*
		you can use either PIXI.WebGLRenderer or PIXI.CanvasRenderer
	*/
	var renderer = new PIXI.WebGLRenderer(800, 600);

	document.body.appendChild(renderer.view);

	var stage = new PIXI.Stage;

	var bunnyTexture = PIXI.Texture.fromImage("bunny.png");
	var bunny = new PIXI.Sprite(bunnyTexture);

	bunny.position.x = 400;
	bunny.position.y = 300;

	bunny.scale.x = 2;
	bunny.scale.y = 2;

	stage.addChild(bunny);

	requestAnimationFrame( animate );

	function animate() {

		requestAnimationFrame( animate );

		bunny.rotation += 0.01;

		renderer.render(stage);
	}
```

This content is released under the (http://opensource.org/licenses/MIT) MIT License.


text:
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1.0">
  <title>how to use #ID</title>
  <link href="http://fonts.googleapis.com/css?family=Open+Sans:300,400" rel="stylesheet" type="text/css">
  <link rel="stylesheet" href="css/standardize.css">
  <link rel="stylesheet" href="css/index.css">

        link #green

        link #blue

        link #red

#GREEN

    ⬆ top

#BLUE

    ⬆ top

#RED

    ⬆ top

#RED

    ⬆ top


text:
// Adapted from ExtensionOrderer in Roslyn
using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.CodeAnalysis;

namespace OmniSharp.Utilities
{
    static partial class ExtensionOrderer
    {
        internal class Node<TNode>
        {
            public string Name { get; set; }
            public List<string> Before { get; set; }
            public List<string> After { get; set; }
            public TNode Extension { get; set; }
            public HashSet<Node<TNode>> NodesBeforeMeSet { get; set; }

            public static Node<TNode> From<TNodeAttribute>(TNode extension, Func<TNodeAttribute, string> nameExtractor) where TNodeAttribute : Attribute
            {
                string name = string.Empty;
                var attribute = extension.GetType().GetCustomAttribute<TNodeAttribute>();
                if (attribute is TNodeAttribute && !string.IsNullOrEmpty(nameExtractor(attribute)))
                {
                    name = nameExtractor(attribute);
                }
                var orderAttributes = extension.GetType().GetCustomAttributes<ExtensionOrderAttribute>(true);
                return new Node<TNode>(extension, name, orderAttributes);
            }

            private Node(TNode extension, string name, IEnumerable<ExtensionOrderAttribute> orderAttributes)
            {
                Extension = extension;
                Name = name;
                Before = new List<string>();
                After = new List<string>();
                NodesBeforeMeSet = new HashSet<Node<TNode>>();
                foreach (var attribute in orderAttributes)
                {
                    AddAttribute(attribute);
                }
            }

            private void AddAttribute(ExtensionOrderAttribute attribute)
            {
                if (attribute.Before != null)
                    Before.Add(attribute.Before);
                if (attribute.After != null)
                    After.Add(attribute.After);
            }

            internal bool CheckForCycles()
            {
                return CheckForCycles(new HashSet<Node<TNode>>());
            }

            private bool CheckForCycles(HashSet<Node<TNode>> seenNodes)
            {
                if (!seenNodes.Add(this))
                {
                    //Cycle detected
                    return true;
                }

                foreach (var before in this.NodesBeforeMeSet)
                {
                    if (before.CheckForCycles(seenNodes))
                        return true;
                }

                seenNodes.Remove(this);
                return false;
            }
        }
    }
}


text:
package requestbetaseries;

import org.apache.log4j.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import factory.FacEpisodes;
import factory.FacShow;
import factory.FacShowCenter;
import requestbetaseries.networkconnection.BetaSeriesConnection;
import utils.ConvertJSON;
import utils.ConvertString;
import utils.LoggerUtils;
import DB.DbSetUp;
import bom.Episode;
import bom.Member;
import bom.Show;
import bom.ShowCenter;

public class BetaseriesRequest {

	final static Logger logger = LoggerUtils.getLogger(BetaseriesRequest.class);

	public void getUserConnectionInfos(Member member) throws Exception{
		BetaSeriesConnection bsReq = new BetaSeriesConnection();
		String response = bsReq.connectBetaseriesAPI(member);
		JSONParser parserJSON = new JSONParser();
		Object jsonRes = parserJSON.parse(response);
		if (jsonRes.getClass() == JSONObject.class)
		{
			JSONObject objRes = ((JSONObject) jsonRes);
			String token = ConvertJSON.extractString(objRes,"token");
			logger.debug("token : "+token);
			member.setToken(token);
			JSONObject objUser = ConvertJSON.extractJSONObject(objRes, "user");
			long userId = ConvertJSON.extractLong(objUser, "id");
			logger.debug("userId : "+userId);
			member.setUserId(userId);
		}
	}

	public void getUserRemainingEpisodes(Member member) throws Exception{
		BetaSeriesConnection bsReq = new BetaSeriesConnection();
		String response = bsReq.getUsersEpisodesList(member);
		JSONParser parserJSON = new JSONParser();
		Object jsonRes = parserJSON.parse(response);
		if (jsonRes.getClass() == JSONObject.class)
		{
			JSONObject objRes = ((JSONObject) jsonRes);
			JSONArray shows = ConvertJSON.extractArray(objRes,"shows");
			logger.info("There are "+shows.size()+" shows");
			for(int itShows = 0; itShows < shows.size(); itShows++){
				JSONObject show = ((JSONObject) shows.get(itShows));
				//logger.debug("Dump JSON Show -- "+show.toString());
				Show bomShow = FacShow.INSTANCE.getNewShow();
				bomShow.setId(ConvertJSON.extractLong(show, "id"));
				bomShow.setImdbId(ConvertJSON.extractLong(show, "thetvdb_id"));
				bomShow.setTitle(ConvertString.replaceBackToLine(ConvertJSON.extractString(show, "title")));
				JSONArray unseen = ConvertJSON.extractArray(show,"unseen");
				if (unseen != null){
					logger.info("There are "+unseen.size()+" unseen epsiodes for the show \""+ConvertJSON.extractString(show, "title")+"\"");
					for (int itUnseen = 0; itUnseen < unseen.size(); itUnseen++){
						JSONObject episode = ((JSONObject) unseen.get(itUnseen));
						Episode bomEpisode = FacEpisodes.INSTANCE.getNewEpisode();
						bomEpisode.setId(ConvertJSON.extractLong(episode, "id"));
						bomEpisode.setTheTvDbId(ConvertJSON.extractLong(episode, "thetvdb_id"));
						bomEpisode.setTitle(ConvertString.replaceBackToLine(ConvertJSON.extractString(episode, "title")));
						bomEpisode.setSeason(ConvertJSON.extractLong(episode, "season"));
						bomEpisode.setEpisode(ConvertJSON.extractLong(episode, "episode"));
						bomEpisode.setIdShow(ConvertJSON.extractLong(episode, "show_id"));
						bomEpisode.setCode(ConvertString.replaceBackToLine(ConvertJSON.extractString(episode, "code")));
						bomEpisode.setGlobalNumber(ConvertJSON.extractLong(episode, "global"));
						bomEpisode.setDescription(ConvertString.replaceBackToLine(ConvertJSON.extractString(episode, "description")));
						bomEpisode.setDate(ConvertString.replaceBackToLine(ConvertJSON.extractString(episode, "date")));
						bomShow.addEpisode(bomEpisode);
					}
				}
				FacShowCenter.INSTANCE.getShowCenter().addShow(bomShow);
			}
		}
	}

}


text:
layout: archive
permalink: /tag-cloud/
---

Cuisines & Courses

  {% capture site_tags %}{% for tag in site.tags %}{{ tag | first }}{% unless forloop.last %},{% endunless %}{% endfor %}{% endcapture %}
  {% assign tags = site_tags | split:',' | sort %}
  {% include tagcloud.html %}


text:
"""Starter script for Nova Compute."""

import sys
import traceback

from oslo.config import cfg

from nova.conductor import rpcapi as conductor_rpcapi
from nova import config
import nova.db.api
from nova import exception
from nova.i18n import _
from nova import objects
from nova.objects import base as objects_base
from nova.openstack.common import log as logging
from nova.openstack.common.report import guru_meditation_report as gmr
from nova.fusioncompute import service
from nova import utils
from nova import version

CONF = cfg.CONF
CONF.import_opt('compute_topic', 'nova.compute.rpcapi')
CONF.import_opt('use_local', 'nova.conductor.api', group='conductor')

def block_db_access():
    class NoDB(object):
        def __getattr__(self, attr):
            return self

        def __call__(self, *args, **kwargs):
            stacktrace = "".join(traceback.format_stack())
            LOG = logging.getLogger('nova.compute')
            LOG.error(_('No db access allowed in nova-compute: %s'),
                      stacktrace)
            raise exception.DBNotAllowed('nova-compute')

    nova.db.api.IMPL = NoDB()

def main():
    config.parse_args(sys.argv)
    logging.setup('nova')
    utils.monkey_patch()
    objects.register_all()

    gmr.TextGuruMeditation.setup_autorun(version)

    if not CONF.conductor.use_local:
        block_db_access()
        objects_base.NovaObject.indirection_api = \
            conductor_rpcapi.ConductorAPI()

    server = service.Service.create(binary='nova-compute',
                                    topic=CONF.compute_topic,
                                    db_allowed=CONF.conductor.use_local)
    workers = CONF.fusioncompute.workers or 1
    service.serve(server, workers=workers)
    service.wait()


text:
'use strict';
const readPkgUp = require('read-pkg-up');

exports.readPkg = () => {
	const pkg = readPkgUp.sync().pkg;

	if (!pkg) {
		throw new Error(`No package.json found. Make sure you're in the correct project.`);
	}

	return pkg;
};


text:
function info()
{
    echo -e "\e[00;32m$*\e[00m" >&2 #green
}

function warn()
{
    echo -e "\e[00;35m$*\e[00m" >&2 #purple
}

function error()
{
    echo -e "\e[00;31m$*\e[00m" >&2 #green
    exit 1
}

# workspace setup
root=$(pwd)
tools=$root/../tools

# check the machine architecture
arch=$(uname --machine)
if [ $arch == "x86_64" ]; then
    info "you are using x86 ($arch) architecture"
    info "do you want to setup the cross compiler?"
    read -p "[y/n]" -n 1 -r
    echo    # new line
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo
        # get cross-compile tools
        if [ ! -d $tools ]; then
            cd $root/..

            info "clone tools..."
            git clone https://github.com/raspberrypi/tools
            if [ "$?" -ne "0" ]; then
                error "failed to get tools"
            fi

            info "checkout old but stable version..."
            cd $tools
            git checkout 3a413ca2b23fd275e8ddcc34f3f9fc3a4dbc723f
            if [ "$?" -ne "0" ]; then
                error "failed to checkout"
            fi
        else
            info "tools already in place, skipping..."
        fi

        info "create makefile.prefix ..."
        cd $root
        echo "PREFIX = $tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin/arm-linux-gnueabihf-" > Makefile.prefix
    else
        echo "PREFIX = " > Makefile.prefix
    fi
fi

echo
info "process wiringPi ..."
cd wiringPi/wiringPi
make clean
make static
cd $root

echo
info "process pws ..."
make clean
make


text:
package org.pentaho.di.trans.steps.zendesk;

import org.pentaho.di.core.row.RowMetaInterface;

public class ZendeskInputIncrementalData extends ZendeskInputData {

  RowMetaInterface rowMeta;
}


text:
import React from 'react';
import './index.scss';

import Switch from '../../../packages/switch';

class SelectTest extends React.Component<{}, {}> {
  render() {
    return (

        <Switch />
        <Switch checked />
        <Switch disabled />

          <Switch />
          <Switch checked />
          <Switch disabled />

        <Switch
          className='custom-switch'
          nativeControlId='custom-switch-input'
          checked
        />
        Custom switch with label

    );
  }
}
export default SelectTest;


text:
if Rails.env.test?
  Gibbon::Export.api_key = "fake"
  Gibbon::Export.throws_exceptions = false
end
Gibbon::API.api_key = "35b67fc98e8508fca88e64c945f273cd"
Gibbon::API.timeout = 15
Gibbon::API.throws_exceptions = false
Rails.configuration.mailchimp = Gibbon::API.new


text:
namespace cast_util {

using media_router::CastInternalMessage;

template <>
const EnumTable<CastInternalMessage::Type>&
EnumTable<CastInternalMessage::Type>::GetInstance() {
  static const EnumTable<CastInternalMessage::Type> kInstance(
      {
          {CastInternalMessage::Type::kClientConnect, "client_connect"},
          {CastInternalMessage::Type::kAppMessage, "app_message"},
          {CastInternalMessage::Type::kV2Message, "v2_message"},
          {CastInternalMessage::Type::kLeaveSession, "leave_session"},
          {CastInternalMessage::Type::kReceiverAction, "receiver_action"},
          {CastInternalMessage::Type::kNewSession, "new_session"},
          {CastInternalMessage::Type::kUpdateSession, "update_session"},
          {CastInternalMessage::Type::kError, "error"},
          {CastInternalMessage::Type::kOther},
      },
      CastInternalMessage::Type::kMaxValue);
  return kInstance;
}

template <>
const EnumTable<CastInternalMessage::ErrorCode>&
EnumTable<CastInternalMessage::ErrorCode>::GetInstance() {
  static const EnumTable<CastInternalMessage::ErrorCode> kInstance(
      {
          {CastInternalMessage::ErrorCode::kInternalError, "internal_error"},
          {CastInternalMessage::ErrorCode::kCancel, "cancel"},
          {CastInternalMessage::ErrorCode::kTimeout, "timeout"},
          {CastInternalMessage::ErrorCode::kApiNotInitialized,
           "api_not_initialized"},
          {CastInternalMessage::ErrorCode::kInvalidParameter,
           "invalid_parameter"},
          {CastInternalMessage::ErrorCode::kExtensionNotCompatible,
           "extension_not_compatible"},
          {CastInternalMessage::ErrorCode::kReceiverUnavailable,
           "receiver_unavailable"},
          {CastInternalMessage::ErrorCode::kSessionError, "session_error"},
          {CastInternalMessage::ErrorCode::kChannelError, "channel_error"},
          {CastInternalMessage::ErrorCode::kLoadMediaFailed,
           "load_media_failed"},
      },
      CastInternalMessage::ErrorCode::kMaxValue);
  return kInstance;
}

}  // namespace cast_util

namespace media_router {

namespace {

// The ID for the backdrop app. Cast devices running the backdrop app is
// considered idle, and an active session should not be reported.
constexpr char kBackdropAppId[] = "E8C28D3C";

bool GetString(const base::Value& value,
               const std::string& key,
               std::string* out) {
  const base::Value* string_value =
      value.FindKeyOfType(key, base::Value::Type::STRING);
  if (!string_value)
    return false;

  *out = string_value->GetString();
  return !out->empty();
}

void CopyValueWithDefault(const base::Value& from,
                          const std::string& key,
                          base::Value default_value,
                          base::Value* to) {
  const base::Value* value = from.FindKey(key);
  to->SetKey(key, value ? value->Clone() : std::move(default_value));
}

void CopyValue(const base::Value& from,
               const std::string& key,
               base::Value* to) {
  const base::Value* value = from.FindKey(key);
  if (value)
    to->SetKey(key, value->Clone());
}

CastInternalMessage::Type CastInternalMessageTypeFromString(
    const std::string& type) {
  return cast_util::StringToEnum<CastInternalMessage::Type>(type).value_or(
      CastInternalMessage::Type::kOther);
}

std::string CastInternalMessageTypeToString(CastInternalMessage::Type type) {
  auto found = cast_util::EnumToString(type);
  DCHECK(found);
  return std::string(found.value_or(base::StringPiece()));
}

// Possible types in a receiver_action message.
constexpr char kReceiverActionTypeCast[] = "cast";
constexpr char kReceiverActionTypeStop[] = "stop";

base::ListValue CapabilitiesToListValue(uint8_t capabilities) {
  base::ListValue value;
  if (capabilities & cast_channel::VIDEO_OUT)
    value.Append("video_out");
  if (capabilities & cast_channel::VIDEO_IN)
    value.Append("video_in");
  if (capabilities & cast_channel::AUDIO_OUT)
    value.Append("audio_out");
  if (capabilities & cast_channel::AUDIO_IN)
    value.Append("audio_in");
  if (capabilities & cast_channel::MULTIZONE_GROUP)
    value.Append("multizone_group");
  return value;
}

std::string GetReceiverLabel(const MediaSinkInternal& sink,
                             const std::string& hash_token) {
  std::string label = base::SHA1HashString(sink.sink().id() + hash_token);
  base::Base64UrlEncode(label, base::Base64UrlEncodePolicy::OMIT_PADDING,
                        &label);
  return label;
}

base::Value CreateReceiver(const MediaSinkInternal& sink,
                           const std::string& hash_token) {
  base::Value receiver(base::Value::Type::DICTIONARY);

  if (!hash_token.empty()) {
    receiver.SetKey("label", base::Value(GetReceiverLabel(sink, hash_token)));
  }

  receiver.SetKey("friendlyName",
                  base::Value(net::EscapeForHTML(sink.sink().name())));
  receiver.SetKey("capabilities",
                  CapabilitiesToListValue(sink.cast_data().capabilities));
  receiver.SetKey("volume", base::Value());
  receiver.SetKey("isActiveInput", base::Value());
  receiver.SetKey("displayStatus", base::Value());

  receiver.SetKey("receiverType", base::Value("cast"));
  return receiver;
}

blink::mojom::PresentationConnectionMessagePtr CreateMessageCommon(
    CastInternalMessage::Type type,
    base::Value payload,
    const std::string& client_id,
    absl::optional<int> sequence_number = absl::nullopt) {
  base::Value message(base::Value::Type::DICTIONARY);
  message.SetKey("type", base::Value(CastInternalMessageTypeToString(type)));
  message.SetKey("message", std::move(payload));
  if (sequence_number) {
    message.SetKey("sequenceNumber", base::Value(*sequence_number));
  }
  message.SetKey("timeoutMillis", base::Value(0));
  message.SetKey("clientId", base::Value(client_id));

  std::string str;
  CHECK(base::JSONWriter::Write(message, &str));
  return blink::mojom::PresentationConnectionMessage::NewMessage(str);
}

blink::mojom::PresentationConnectionMessagePtr CreateReceiverActionMessage(
    const std::string& client_id,
    const MediaSinkInternal& sink,
    const std::string& hash_token,
    const char* action_type) {
  base::Value message(base::Value::Type::DICTIONARY);
  message.SetKey("receiver", CreateReceiver(sink, hash_token));
  message.SetKey("action", base::Value(action_type));

  return CreateMessageCommon(CastInternalMessage::Type::kReceiverAction,
                             std::move(message), client_id);
}

base::Value CreateAppMessageBody(
    const std::string& session_id,
    const cast::channel::CastMessage& cast_message) {
  // TODO(https://crbug.com/862532): Investigate whether it is possible to move
  // instead of copying the contents of |cast_message|. Right now copying is
  // done because the message is passed as a const ref at the
  // CastSocket::Observer level.
  base::Value message(base::Value::Type::DICTIONARY);
  message.SetKey("sessionId", base::Value(session_id));
  message.SetKey("namespaceName", base::Value(cast_message.namespace_()));
  switch (cast_message.payload_type()) {
    case cast::channel::CastMessage_PayloadType_STRING:
      message.SetKey("message", base::Value(cast_message.payload_utf8()));
      break;
    case cast::channel::CastMessage_PayloadType_BINARY: {
      const auto& payload = cast_message.payload_binary();
      message.SetKey("message",
                     base::Value(base::Value::BlobStorage(
                         payload.front(), payload.front() + payload.size())));
      break;
    }
    default:
      NOTREACHED();
      break;
  }
  return message;
}

// Creates a message with a session value in the "message" field. |type| must
// be either kNewSession or kUpdateSession.
blink::mojom::PresentationConnectionMessagePtr CreateSessionMessage(
    const CastSession& session,
    const std::string& client_id,
    const MediaSinkInternal& sink,
    const std::string& hash_token,
    CastInternalMessage::Type type) {
  DCHECK(type == CastInternalMessage::Type::kNewSession ||
         type == CastInternalMessage::Type::kUpdateSession);
  base::Value session_with_receiver_label = session.value().Clone();
  DCHECK(!session_with_receiver_label.FindPath({"receiver", "label"}));
  session_with_receiver_label.SetPath(
      {"receiver", "label"}, base::Value(GetReceiverLabel(sink, hash_token)));
  return CreateMessageCommon(type, std::move(session_with_receiver_label),
                             client_id);
}

}  // namespace

// static
std::unique_ptr<CastInternalMessage> CastInternalMessage::From(
    base::Value message) {
  if (!message.is_dict()) {
    DVLOG(2) << "Failed to read JSON message: " << message;
    return nullptr;
  }

  std::string str_type;
  if (!GetString(message, "type", &str_type)) {
    DVLOG(2) << "Missing type value, message: " << message;
    return nullptr;
  }

  CastInternalMessage::Type message_type =
      CastInternalMessageTypeFromString(str_type);
  if (message_type == CastInternalMessage::Type::kOther) {
    DVLOG(2) << __func__ << ": Unsupported message type: " << str_type
             << ", message: " << message;
    return nullptr;
  }

  std::string client_id;

  if (!GetString(message, "clientId", &client_id)) {
    DVLOG(2) << "Missing clientId, message: " << message;
    return nullptr;
  }

  base::Value* message_body_value = message.FindKey("message");
  if (!message_body_value ||
      (!message_body_value->is_dict() && !message_body_value->is_string())) {
    DVLOG(2) << "Missing message body, message: " << message;
    return nullptr;
  }

  base::Value* sequence_number_value =
      message.FindKeyOfType("sequenceNumber", base::Value::Type::INTEGER);

  std::string session_id;
  std::string namespace_or_v2_type;
  base::Value new_message_body;

  if (message_type == Type::kAppMessage || message_type == Type::kV2Message) {
    if (!GetString(*message_body_value, "sessionId", &session_id)) {
      DVLOG(2) << "Missing sessionId, message: " << message;
      return nullptr;
    }

    if (!message_body_value->is_dict()) {
      DVLOG(2) << "Message body is not a dict: " << message;
      return nullptr;
    }

    if (message_type == Type::kAppMessage) {
      if (!GetString(*message_body_value, "namespaceName",
                     &namespace_or_v2_type)) {
        DVLOG(2) << "Missing namespace, message: " << message;
        return nullptr;
      }

      base::Value* app_message_value = message_body_value->FindKey("message");
      if (!app_message_value ||
          (!app_message_value->is_dict() && !app_message_value->is_string())) {
        DVLOG(2) << "Missing app message, message: " << message;
        return nullptr;
      }
      new_message_body = std::move(*app_message_value);
    } else if (message_type == CastInternalMessage::Type::kV2Message) {
      if (!GetString(*message_body_value, "type", &namespace_or_v2_type)) {
        DVLOG(2) << "Missing v2 type, message: " << message;
        return nullptr;
      }
      new_message_body = std::move(*message_body_value);
    }
  }

  return base::WrapUnique(new CastInternalMessage(
      message_type, client_id,
      sequence_number_value ? sequence_number_value->GetInt()
                            : absl::optional<int>(),
      session_id, namespace_or_v2_type, std::move(new_message_body)));
}

CastInternalMessage::~CastInternalMessage() = default;

CastInternalMessage::CastInternalMessage(
    Type type,
    const std::string& client_id,
    absl::optional<int> sequence_number,
    const std::string& session_id,
    const std::string& namespace_or_v2_type,
    base::Value message_body)
    : type_(type),
      client_id_(client_id),
      sequence_number_(sequence_number),
      session_id_(session_id),
      namespace_or_v2_type_(namespace_or_v2_type),
      message_body_(std::move(message_body)) {}

// static
std::unique_ptr<CastSession> CastSession::From(
    const MediaSinkInternal& sink,
    const base::Value& receiver_status) {
  // There should be only 1 app on |receiver_status|.
  const base::Value* app_list_value =
      receiver_status.FindKeyOfType("applications", base::Value::Type::LIST);
  if (!app_list_value || app_list_value->GetList().size() != 1) {
    DVLOG(2) << "receiver_status does not contain exactly one app: "
             << receiver_status;
    return nullptr;
  }

  auto session = std::make_unique<CastSession>();

  // Fill in mandatory Session fields.
  const base::Value& app_value = app_list_value->GetList()[0];
  if (!GetString(app_value, "sessionId", &session->session_id_) ||
      !GetString(app_value, "appId", &session->app_id_) ||
      !GetString(app_value, "transportId", &session->transport_id_) ||
      !GetString(app_value, "displayName", &session->display_name_)) {
    DVLOG(2) << "app_value missing mandatory fields: " << app_value;
    return nullptr;
  }

  if (session->app_id_ == kBackdropAppId) {
    DVLOG(2) << sink.sink().id() << " is running the backdrop app";
    return nullptr;
  }

  // Optional Session fields.
  GetString(app_value, "statusText", &session->status_);

  // The receiver label will be populated by each profile using
  // |session->value|.
  base::Value receiver_value = CreateReceiver(sink, std::string());
  CopyValue(receiver_status, "volume", &receiver_value);
  CopyValue(receiver_status, "isActiveInput", &receiver_value);

  // Create |session->value|.
  session->value_ = base::Value(base::Value::Type::DICTIONARY);
  auto& session_value = session->value_;
  session_value.SetKey("sessionId", base::Value(session->session_id()));
  session_value.SetKey("appId", base::Value(session->app_id()));
  session_value.SetKey("transportId", base::Value(session->transport_id()));
  session_value.SetKey("receiver", std::move(receiver_value));

  CopyValueWithDefault(app_value, "displayName", base::Value(""),
                       &session_value);
  CopyValueWithDefault(app_value, "senderApps", base::ListValue(),
                       &session_value);
  CopyValueWithDefault(app_value, "statusText", base::Value(), &session_value);
  CopyValueWithDefault(app_value, "appImages", base::ListValue(),
                       &session_value);
  // Optional fields
  CopyValue(app_value, "appType", &session_value);
  CopyValue(app_value, "universalAppId", &session_value);

  const base::Value* namespaces_value =
      app_value.FindKeyOfType("namespaces", base::Value::Type::LIST);
  if (!namespaces_value || namespaces_value->GetList().empty()) {
    // A session without namespaces is invalid, except for a multizone leader.
    if (session->app_id() != kMultizoneLeaderAppId) {
      DVLOG(2) << "Message is missing namespaces.";
      return nullptr;
    }
  } else {
    for (const auto& namespace_value : namespaces_value->GetList()) {
      std::string message_namespace;
      if (!namespace_value.is_dict() ||
          !GetString(namespace_value, "name", &message_namespace)) {
        DVLOG(2) << "Missing namespace name.";
        return nullptr;
      }

      session->message_namespaces_.insert(std::move(message_namespace));
    }
  }
  session_value.SetKey("namespaces",
                       namespaces_value ? namespaces_value->Clone()
                                        : base::Value(base::Value::Type::LIST));
  return session;
}

CastSession::CastSession() = default;
CastSession::~CastSession() = default;

std::string CastSession::GetRouteDescription() const {
  return !status_.empty() ? status_ : display_name_;
}

void CastSession::UpdateSession(std::unique_ptr<CastSession> from) {
  status_ = std::move(from->status_);
  message_namespaces_ = std::move(from->message_namespaces_);

  auto* status_text_value = from->value_.FindKey("statusText");
  DCHECK(status_text_value);
  value_.SetKey("statusText", std::move(*status_text_value));
  auto* namespaces_value = from->value_.FindKey("namespaces");
  DCHECK(namespaces_value);
  value_.SetKey("namespaces", std::move(*namespaces_value));
  auto* receiver_volume_value = from->value_.FindPath({"receiver", "volume"});
  DCHECK(receiver_volume_value);
  value_.SetPath({"receiver", "volume"}, std::move(*receiver_volume_value));
}

void CastSession::UpdateMedia(const base::Value& media) {
  value_.SetKey("media", media.Clone());
}

blink::mojom::PresentationConnectionMessagePtr CreateReceiverActionCastMessage(
    const std::string& client_id,
    const MediaSinkInternal& sink,
    const std::string& hash_token) {
  return CreateReceiverActionMessage(client_id, sink, hash_token,
                                     kReceiverActionTypeCast);
}

blink::mojom::PresentationConnectionMessagePtr CreateReceiverActionStopMessage(
    const std::string& client_id,
    const MediaSinkInternal& sink,
    const std::string& hash_token) {
  return CreateReceiverActionMessage(client_id, sink, hash_token,
                                     kReceiverActionTypeStop);
}

blink::mojom::PresentationConnectionMessagePtr CreateNewSessionMessage(
    const CastSession& session,
    const std::string& client_id,
    const MediaSinkInternal& sink,
    const std::string& hash_token) {
  return CreateSessionMessage(session, client_id, sink, hash_token,
                              CastInternalMessage::Type::kNewSession);
}

blink::mojom::PresentationConnectionMessagePtr CreateUpdateSessionMessage(
    const CastSession& session,
    const std::string& client_id,
    const MediaSinkInternal& sink,
    const std::string& hash_token) {
  return CreateSessionMessage(session, client_id, sink, hash_token,
                              CastInternalMessage::Type::kUpdateSession);
}

blink::mojom::PresentationConnectionMessagePtr CreateAppMessageAck(
    const std::string& client_id,
    int sequence_number) {
  return CreateMessageCommon(CastInternalMessage::Type::kAppMessage,
                             base::Value(), client_id, sequence_number);
}

blink::mojom::PresentationConnectionMessagePtr CreateAppMessage(
    const std::string& session_id,
    const std::string& client_id,
    const cast::channel::CastMessage& cast_message) {
  return CreateMessageCommon(CastInternalMessage::Type::kAppMessage,
                             CreateAppMessageBody(session_id, cast_message),
                             client_id);
}

blink::mojom::PresentationConnectionMessagePtr CreateV2Message(
    const std::string& client_id,
    const base::Value& payload,
    absl::optional<int> sequence_number) {
  return CreateMessageCommon(CastInternalMessage::Type::kV2Message,
                             payload.Clone(), client_id, sequence_number);
}

blink::mojom::PresentationConnectionMessagePtr CreateLeaveSessionAckMessage(
    const std::string& client_id,
    absl::optional<int> sequence_number) {
  return CreateMessageCommon(CastInternalMessage::Type::kLeaveSession,
                             base::Value(), client_id, sequence_number);
}

blink::mojom::PresentationConnectionMessagePtr CreateErrorMessage(
    const std::string& client_id,
    base::Value error,
    absl::optional<int> sequence_number) {
  return CreateMessageCommon(CastInternalMessage::Type::kError,
                             std::move(error), client_id, sequence_number);
}

base::Value SupportedMediaCommandsToListValue(int media_commands) {
  base::Value value(base::Value::Type::LIST);
  if (media_commands & static_cast<int>(MediaCommand::kPause))
    value.Append(kMediaCommandPause);
  if (media_commands & static_cast<int>(MediaCommand::kSeek))
    value.Append(kMediaCommandSeek);
  if (media_commands & static_cast<int>(MediaCommand::kStreamVolume))
    value.Append(kMediaCommandStreamVolume);
  if (media_commands & static_cast<int>(MediaCommand::kStreamMute))
    value.Append(kMediaCommandStreamMute);
  if (media_commands & static_cast<int>(MediaCommand::kQueueNext))
    value.Append(kMediaCommandQueueNext);
  if (media_commands & static_cast<int>(MediaCommand::kQueuePrev))
    value.Append(kMediaCommandQueuePrev);
  return value;
}

}  // namespace media_router


text:
define(['marionette',
    'modules/blstats/views/robotavgs',
    'modules/blstats/collections/roboterrors',
    'modules/blstats/collections/robottotals',
    'modules/blstats/views/roboterrors',
    'modules/blstats/views/robottotals',
    'modules/blstats/views/robottotalplot',
    'utils'

    ], function(Marionette, RobotAveragesView, RobotErrors, RobotTotals, RobotErrorsView, RobotTotalsView, RobotTotalsPlot, utils) {

    return Marionette.LayoutView.extend({
        className: 'content',
        template: _.template('
Robot Averages

 Download

Totals

'),

        regions: {
            wrap: '.wrapper',
            tot: '.totals',
        },

        ui: {
            plot: '#avg_time',
            tot: '#tots',
        },

        events: {
            'click .legend table tr': 'filterBL',
            'plotclick #avg_time': 'filterRun',
            'click a.download': 'downloadData',
        },

        downloadData: function(e) {
            e.preventDefault()
            var url = app.apiurl+'/robot/averages?download=1'
            utils.sign({
                url: url,
                callback: function(resp) {
                    window.location = url+'&token='+resp.token
                }
            })
        },

        filterRun: function (e, pos, item) {
            var rx = item.datapoint[0]
            var run = item.series.xaxis.ticks[rx].label
            var runid = this.plot.getrids()[run]

            this.roboterrors.queryParams.bl = item.series.label
            this.roboterrors.fetch()

            this.robottotals.queryParams.bl = item.series.label
            this.robottotals.queryParams.run = runid
            this.robottotals.fetch()
        },

        filterBL: function(e) {
            var bl = $(e.currentTarget).children('td.legendLabel').html()
            console.log(bl, e)

            this.roboterrors.queryParams.bl = bl
            this.roboterrors.fetch()

            this.robottotals.queryParams.bl = bl
            this.robottotals.fetch()
        },

        initialize: function(options) {
            this.roboterrors = new RobotErrors()
            this.roboterrors.fetch()

            this.robottotals = new RobotTotals()
            this.robottotals.fetch()
        },

        onShow: function() {
            this.plot = new RobotAveragesView({ el : this.ui.plot })
            this.wrap.show(new RobotErrorsView({ collection: this.roboterrors }))

            this.plot2 = new RobotTotalsPlot({ el: this.ui.tot, collection: this.robottotals })
            this.plot2.render()
            this.tot.show(new RobotTotalsView({ collection: this.robottotals }))
        },

    })

})


text:
"""
Constants for the grades app
"""

COURSE_GRADE_WEIGHT = 0.4
EXAM_GRADE_WEIGHT = 0.6

class FinalGradeStatus:
    """
    Possible statuses for the Final Grades
    """
    PENDING = 'pending'
    COMPLETE = 'complete'
    ALL_STATUSES = [PENDING, COMPLETE]


text:
from __future__ import unicode_literals

from django.test import TestCase, RequestFactory
from django.core.urlresolvers import reverse
from django.template import Template, Context
from django.core.cache import cache

from djconfig import config

from ...core.tests import utils
from .models import CommentBookmark
from .forms import BookmarkForm

class CommentBookmarkViewTest(TestCase):

    def setUp(self):
        cache.clear()
        self.user = utils.create_user()
        self.category = utils.create_category()
        self.topic = utils.create_topic(category=self.category, user=self.user)
        self.comment = utils.create_comment(topic=self.topic)

    def test_bookmark_create(self):
        """
        create comment
        """
        utils.login(self)
        form_data = {'comment_number': 999, }
        response = self.client.post(reverse('spirit:comment:bookmark:create', kwargs={'topic_id': self.topic.pk, }),
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest',
                                    data=form_data)
        self.assertEqual(response.status_code, 200)

class CommentBookmarkModelsTest(TestCase):

    def setUp(self):
        cache.clear()
        self.user = utils.create_user()
        self.category = utils.create_category()
        self.topic = utils.create_topic(category=self.category, user=self.user)

        for _ in range(config.comments_per_page * 4):  # 4 pages
            utils.create_comment(user=self.user, topic=self.topic)

    def test_comment_bookmark_get_new_comment_url(self):
        """
        Should return the new comment url (current comment + 1)
        """
        bookmark = CommentBookmark.objects.create(topic=self.topic, user=self.user, comment_number=1)
        self.assertTrue(bookmark.get_absolute_url().endswith('1'))
        self.assertTrue(bookmark.get_new_comment_url().endswith('2'))

    def test_comment_bookmark_update_or_create(self):
        """
        Should update or create the comment number
        """
        page = 2
        CommentBookmark.update_or_create(
            user=self.user,
            topic=self.topic,
            comment_number=CommentBookmark.page_to_comment_number(page)
        )
        comment_bookmark = CommentBookmark.objects.get(user=self.user, topic=self.topic)
        self.assertEqual(comment_bookmark.comment_number, config.comments_per_page * (page - 1) + 1)

    def test_comment_bookmark_update_or_create_invalid_page(self):
        """
        Should do nothing when receiving an invalid page
        """
        page = 'im_a_string'
        CommentBookmark.update_or_create(
            user=self.user,
            topic=self.topic,
            comment_number=CommentBookmark.page_to_comment_number(page)
        )
        self.assertEqual(len(CommentBookmark.objects.all()), 0)

class CommentBookmarkFormTest(TestCase):

    def test_form(self):
        form_data = {'comment_number': 999, }
        form = BookmarkForm(data=form_data)
        self.assertEqual(form.is_valid(), True)

class CommentBookmarkTemplateTagsTest(TestCase):

    def setUp(self):
        cache.clear()
        self.user = utils.create_user()
        self.category = utils.create_category()
        self.topic = utils.create_topic(self.category)
        self.comment = utils.create_comment(topic=self.topic)

    def populate_bookmarks(self):
        """
        should populate the topic's bookmark
        """
        bookmark = CommentBookmark.objects.create(user=self.user, topic=self.topic, comment_number=10)
        out = Template(
            "{% load comment_bookmark %}"
            "{% populate_bookmarks topics=topics user=user %}"
            "{{ topics.0.bookmark.get_absolute_url }}"
        ).render(Context({'topics': [self.topic, ], 'user': self.user}))
        self.assertEqual(out, bookmark.get_absolute_url())


text:
var b = require('ast-types').builders;
module.exports = function(scope) {
  return b.functionExpression(
  null,
  [
    b.identifier('iterator'),
    b.identifier('index'),
    b.identifier('begin'),
    b.identifier('len')
  ],
  b.blockStatement([
    b.ifStatement(
      b.binaryExpression(
        '>',
        b.identifier('index'),
        b.identifier('begin')
      ),
      b.blockStatement([
        b.throwStatement(
          b.newExpression(
            b.identifier('RangeError'),
            []
          )
        )
      ]),
      null
    ),
    b.ifStatement(
      b.binaryExpression(
        '===',
        b.unaryExpression(
          'typeof',
          b.identifier('len'),
          true
        ),
        b.literal('undefined')
      ),
      b.blockStatement([
        b.expressionStatement(
          b.assignmentExpression(
            '=',
            b.identifier('len'),
            b.identifier('Infinity')
          )
        )
      ]),
      null
    ),
    b.variableDeclaration(
      'var',
      [
        b.variableDeclarator(
          b.identifier('range'),
          b.arrayExpression([])
        ),
        b.variableDeclarator(
          b.identifier('end'),
          b.binaryExpression(
            '+',
            b.identifier('begin'),
            b.identifier('len')
          )
        )
      ]
    ),
    b.whileStatement(
      b.binaryExpression(
        '<',
        b.identifier('index'),
        b.identifier('end')
      ),
      b.blockStatement([
        b.variableDeclaration(
          'var',
          [
            b.variableDeclarator(
              b.identifier('next'),
              b.callExpression(
                b.memberExpression(
                  b.identifier('iterator'),
                  b.identifier('next'),
                  false
                ),
                []
              )
            )
          ]
        ),
        b.ifStatement(
          b.memberExpression(
            b.identifier('next'),
            b.identifier('done'),
            false
          ),
          b.blockStatement([b.breakStatement()]),
          null
        ),
        b.ifStatement(
          b.binaryExpression(
            '>=',
            b.identifier('index'),
            b.identifier('begin')
          ),
          b.blockStatement([
            b.expressionStatement(
              b.callExpression(
                b.memberExpression(
                  b.identifier('range'),
                  b.identifier('push'),
                  false
                ),
                [
                  b.memberExpression(
                    b.identifier('next'),
                    b.identifier('value'),
                    false
                  )
                ]
              )
            )
          ]),
          null
        ),
        b.expressionStatement(
          b.updateExpression(
            '++',
            b.identifier('index'),
            false
          )
        )
      ])
    ),
    b.returnStatement(
      b.objectExpression([
        b.property(
          'init',
          b.identifier('range'),
          b.identifier('range')
        ),
        b.property(
          'init',
          b.identifier('index'),
          b.identifier('index')
        )
      ])
    )
  ]),
  false,
  false
)};


text:
<!DOCTYPE html>

  <meta charset="utf-8" />

  <title>Cortes de Luz en Buenos Aires y alrededores - #AcaNoHayLuz</title>
  <meta name="robots" content="noindex, follow" />
  <meta name="description" content="Si volvió o se fue la luz en tu cuadra o barrio ¡cargalo en el mapa! Armemos entre todos un reporte de los cortes de energía :)" />

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
  <link rel="stylesheet" href="static/css/styles_embed.css?201312270400" />

  <meta property="og:title" content="Cortes de Luz en Buenos Aires y alrededores - #AcáNoHayLuz" />
  <meta property="og:description" content="#AcáNoHayLuz muestra los cortes de energía veraniegos. ¿Hay luz en tu casa? Chequealo en acanohayluz.com.ar" />
  <meta property="og:image" content="http://acanohayluz.com.ar/static/icons/facebook-share.png" />

  <link rel="shortcut icon" href="static/icons/favicon.ico" />
  <link rel="icon" href="static/icons/favicon.ico" />

  <link rel="apple-touch-icon" href="static/icons/apple-touch-icon.png">
  <link rel="apple-touch-icon" sizes="72x72" href="static/icons/apple-touch-icon-72x72.png">
  <link rel="apple-touch-icon" sizes="114x114" href="static/icons/apple-touch-icon-114x114.png">

<?php if( strpos($_SERVER['SERVER_NAME'], 'acanohayluz.com.ar') !== FALSE ): ?>

<?php else: ?>

<?php endif; ?>

<?php if( strpos($_SERVER['SERVER_NAME'], 'acanohayluz.com.ar') !== FALSE ): ?>

<?php else: ?>

<?php endif; ?>

 #AcaNoHayLuz

Construyamos un reporte de los cortes de luz :)

        <form method="post" class="form" novalidate>

              <input name="direccion" type="text" value="" placeholder="Ingresá Tu Dirección" required />

              x

              Hay luz en mi cuadra!
              <input type="radio" name="estado" value="hay-luz" />

              Se cortó en
mi cuadra
              <input type="radio" name="estado" value="corte-cuadra" checked="checked" />

              Se cortó en
varias cuadras
              <input type="radio" name="estado" value="corte-amplio" />

              <input type="number" name="horas" value="" step="1" min="0" max="720" placeholder="Cuántas horas llevás sin luz?" required />

            <input type="hidden" name="direccion_completa" value="" />
            <input type="hidden" name="direccion_id" value="" />
            <input type="hidden" name="zona_nombre" value="" />
            <input type="hidden" name="lat" value="" />
            <input type="hidden" name="long" value="" />
            <input type="hidden" name="zona_id" value="" />

            <button class="btn disabled">Completa el formulario</button>

        </form>

Gracias por tu
 colaboración!

Compartilo en las redes

            Facebook
            Twitter
            Google+

          ¿Volvió la luz? Seguinos en twitter

        Tweet

        Creado por aerolab y tiny brain


text:
package org.springframework.mock.web;

import java.io.IOException;
import java.io.InputStream;

import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;

import org.springframework.util.Assert;

/**
 * Delegating implementation of {@link jakarta.servlet.ServletInputStream}.
 *
 * <p>Used by {@link MockHttpServletRequest}; typically not directly
 * used for testing application controllers.
 *
 * @author Juergen Hoeller
 * @since 1.0.2
 * @see MockHttpServletRequest
 */
public class DelegatingServletInputStream extends ServletInputStream {

	private final InputStream sourceStream;

	private boolean finished = false;

	/**
	 * Create a DelegatingServletInputStream for the given source stream.
	 * @param sourceStream the source stream (never {@code null})
	 */
	public DelegatingServletInputStream(InputStream sourceStream) {
		Assert.notNull(sourceStream, "Source InputStream must not be null");
		this.sourceStream = sourceStream;
	}

	/**
	 * Return the underlying source stream (never {@code null}).
	 */
	public final InputStream getSourceStream() {
		return this.sourceStream;
	}

	@Override
	public int read() throws IOException {
		int data = this.sourceStream.read();
		if (data == -1) {
			this.finished = true;
		}
		return data;
	}

	@Override
	public int available() throws IOException {
		return this.sourceStream.available();
	}

	@Override
	public void close() throws IOException {
		super.close();
		this.sourceStream.close();
	}

	@Override
	public boolean isFinished() {
		return this.finished;
	}

	@Override
	public boolean isReady() {
		return true;
	}

	@Override
	public void setReadListener(ReadListener readListener) {
		throw new UnsupportedOperationException();
	}

}


text:
package com.siberiadante.androidutil.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.siberiadante.androidutil.SDAndroidLib;

import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * Created by SiberiaDante on 2017/5/4.
 *

 * UpDate: 2017-09-12
 *
 * @Describe can use
 */

public class SDNetWorkUtil {

    /**
     * 判断网络是否连接
     */
    public static boolean isNetWorkConnected() {
        return getNetworkInfo() != null && getNetworkInfo().isConnected();
    }

    /**
     * 获取活动网络信息
     * {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}
     *
     * @return
     */
    private static NetworkInfo getNetworkInfo() {
        return getConnectivityManager().getActiveNetworkInfo();
    }

    private static ConnectivityManager getConnectivityManager() {
        return (ConnectivityManager) SDAndroidLib.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    /**
     * 判断wifi数据是否可用
     *
需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>}

     *
需添加权限 {@code <uses-permission android:name="android.permission.INTERNET"/>}

     *
     * @return {@code true}: 是
{@code false}: 否
     */
    @Deprecated
    public static boolean isWifiAvailable() {
        return getWifiEnabled() && isAvailableByPing();
    }

    /**
     * 判断wifi是否打开
     *
需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>}

     *
     * @return {@code true}: 是
{@code false}: 否
     */
    public static boolean getWifiEnabled() {
        return getWifiManager().isWifiEnabled();
    }

    /**
     * 打开或关闭wifi
     *
需添加权限 {@code <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>}

     *
     * @param enabled {@code true}: 打开
{@code false}: 关闭
     */
    public static void setWifiEnabled(final boolean enabled) {
        if (enabled) {
            if (!getWifiManager().isWifiEnabled()) {
                getWifiManager().setWifiEnabled(true);
            }
        } else {
            if (getWifiManager().isWifiEnabled()) {
                getWifiManager().setWifiEnabled(false);
            }
        }
    }

    /**
     * 判断网络是否可用
     *
需添加权限 {@code <uses-permission android:name="android.permission.INTERNET"/>}

     *
需要异步ping,如果ping不通就说明网络不可用

     *
ping的ip为阿里巴巴公共ip:223.5.5.5

     *
     * @return {@code true}: 可用
{@code false}: 不可用
     */
    public static boolean isAvailableByPing() {
        return isAvailableByPing(null);
    }

    private static WifiManager getWifiManager() {
        return (WifiManager) SDAndroidLib.getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    }

    /**
     * 判断网络是否可用
     *
需添加权限 {@code <uses-permission android:name="android.permission.INTERNET"/>}

     *
需要异步ping,如果ping不通就说明网络不可用

     *
     * @param ip ip地址(自己服务器ip),如果为空,ip为阿里巴巴公共ip
     * @return {@code true}: 可用
{@code false}: 不可用
     */
    public static boolean isAvailableByPing(String ip) {
        if (ip == null || ip.length() <= 0) {
            ip = "223.5.5.5";// 阿里巴巴公共ip
        }
        SDShellUtil.CommandResult result = SDShellUtil.execCmd(String.format("ping -c 1 %s", ip), false);
        boolean ret = result.result == 0;
        if (result.errorMsg != null) {
            Log.d("NetworkUtils", "isAvailableByPing() called" + result.errorMsg);
        }
        if (result.successMsg != null) {
            Log.d("NetworkUtils", "isAvailableByPing() called" + result.successMsg);
        }
        return ret;
    }

    /**
     * 判断是否4G连接
     */
    @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
    public static boolean is4GConnected() {
        return getNetworkInfo() != null && getNetworkInfo().getType() == TelephonyManager.NETWORK_TYPE_LTE;
    }

    /**
     * 判断移动数据是否打开
     *
     * @return {@code true}: 是
{@code false}: 否
     */
    public static boolean getDataEnabled() {
        try {
            Method getMobileDataEnabledMethod = getTelephoneManager().getClass().getDeclaredMethod("getDataEnabled");
            if (null != getMobileDataEnabledMethod) {
                return (boolean) getMobileDataEnabledMethod.invoke(getTelephoneManager());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private static TelephonyManager getTelephoneManager() {
        return (TelephonyManager) SDAndroidLib.getContext().getSystemService(Context.TELEPHONY_SERVICE);
    }

    /**
     * 打开或关闭移动数据
     *
需系统应用 需添加权限{@code <uses-permission android:name="android.permission.MODIFY_PHONE_STATE"/>}

     *
     * @param enabled {@code true}: 打开
{@code false}: 关闭
     */
    public static void setDataEnabled(boolean enabled) {
        try {
            Method setMobileDataEnabledMethod = getTelephoneManager().getClass().getDeclaredMethod("setDataEnabled", boolean.class);
            if (null != setMobileDataEnabledMethod) {
                setMobileDataEnabledMethod.invoke(getTelephoneManager(), enabled);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断网络类型
     *
     * @return {@code int}手机网络数据连接类型

     *

     *
{@link SDNetWorkUtil.NetworkType#NETWORK_2G}

     *
{@link SDNetWorkUtil.NetworkType#NETWORK_3G}

     *
{@link SDNetWorkUtil.NetworkType#NETWORK_4G}

     *
{@link SDNetWorkUtil.NetworkType#NETWORK_MOBILE}

     *

     */
    public static NetworkType getNetWorkType() {
        //如果当前没有网络
        if (null == getConnectivityManager()) {
            return NetworkType.NETWORK_NONE;
        }
        //获取当前网络类型,如果为空,返回无网络
        NetworkInfo networkInfo = getNetworkInfo();
        if (networkInfo == null || !networkInfo.isAvailable()) {
            return NetworkType.NETWORK_NONE;
        }
        // 判断是不是连接的是不是wifi
        if (isWifiConnected()) {
            return NetworkType.NETWORK_WIFI;
        }

        // 如果不是wifi,则判断当前连接的是运营商的哪种网络2g、3g、4g等
        NetworkInfo.State state = networkInfo.getState();
        String strSubTypeName = networkInfo.getSubtypeName();
        if (null != state)
            if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
                switch (networkInfo.getSubtype()) {
                    //如果是2g类型
                    case TelephonyManager.NETWORK_TYPE_GPRS: // 联通2g
                    case TelephonyManager.NETWORK_TYPE_CDMA: // 电信2g
                    case TelephonyManager.NETWORK_TYPE_EDGE: // 移动2g
                    case TelephonyManager.NETWORK_TYPE_1xRTT:
                    case TelephonyManager.NETWORK_TYPE_IDEN:
                        return NetworkType.NETWORK_2G;
                    //如果是3g类型
                    case TelephonyManager.NETWORK_TYPE_EVDO_A: // 电信3g
                    case TelephonyManager.NETWORK_TYPE_UMTS:
                    case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    case TelephonyManager.NETWORK_TYPE_HSDPA:
                    case TelephonyManager.NETWORK_TYPE_HSUPA:
                    case TelephonyManager.NETWORK_TYPE_HSPA:
                    case TelephonyManager.NETWORK_TYPE_EVDO_B:
                    case TelephonyManager.NETWORK_TYPE_EHRPD:
                    case TelephonyManager.NETWORK_TYPE_HSPAP:
                        return NetworkType.NETWORK_3G;
                    //如果是4g类型
                    case TelephonyManager.NETWORK_TYPE_LTE:
                        return NetworkType.NETWORK_4G;
                    default:
                        //中国移动 联通 电信 三种3G制式
                        if (strSubTypeName.equalsIgnoreCase("TD-SCDMA")
                                || strSubTypeName.equalsIgnoreCase("WCDMA")
                                || strSubTypeName.equalsIgnoreCase("CDMA2000")) {
                            return NetworkType.NETWORK_3G;
                        } else {
                            return NetworkType.NETWORK_MOBILE;
                        }
                }
            }
        return NetworkType.NETWORK_NONE;
    }

    /**
     * 判断是否是无线连接
     */
    public static boolean isWifiConnected() {
        return getNetworkInfo() != null && getNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;
    }

    /**
     * 打开无线和网络控制面板
     */
    public static void openNetworkSettings() {
        SDJumpUtil.openNetWorkSetting();
    }

    /**
     * 打开网络控制面板
     */
    public static void openWifiSettings() {
        SDJumpUtil.openWifiSetting();
    }

    /**
     * 获取网络运营商名称
     *
中国移动、如中国联通、中国电信

     *
     * @return 运营商名称
     */
    public static String getNetworkOperatorName() {
        return getTelephoneManager() != null ? getTelephoneManager().getNetworkOperatorName() : null;
    }

    /**
     * 获取IP地址
     *
需添加权限 {@code <uses-permission android:name="android.permission.INTERNET"/>}

     *
     * @param useIPv4 是否用IPv4
     * @return IP地址
     */
    public static String getIPAddress(final boolean useIPv4) {
        try {
            for (Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); nis.hasMoreElements(); ) {
                NetworkInterface ni = nis.nextElement();
                // 防止小米手机返回10.0.2.15
                if (!ni.isUp()) continue;
                for (Enumeration<InetAddress> addresses = ni.getInetAddresses(); addresses.hasMoreElements(); ) {
                    InetAddress inetAddress = addresses.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        String hostAddress = inetAddress.getHostAddress();
                        boolean isIPv4 = hostAddress.indexOf(':') < 0;
                        if (useIPv4) {
                            if (isIPv4) return hostAddress;
                        } else {
                            if (!isIPv4) {
                                int index = hostAddress.indexOf('%');
                                return index < 0 ? hostAddress.toUpperCase() : hostAddress.substring(0, index).toUpperCase();
                            }
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取域名ip地址
     *
需添加权限 {@code <uses-permission android:name="android.permission.INTERNET"/>}

     *
     * @param domain 域名
     * @return ip地址
     */
    public static String getDomainAddress(final String domain) {
        InetAddress inetAddress;
        try {
            inetAddress = InetAddress.getByName(domain);
            return inetAddress.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return null;
        }
    }

    public enum NetworkType {
        //没有网络连接
        NETWORK_NONE,
        //wifi连接
        NETWORK_WIFI,
        //手机网络数据连接类型
        NETWORK_2G,
        NETWORK_3G,
        NETWORK_4G,
        NETWORK_MOBILE
    }
}


text: <!DOCTYPE html>


text:
#ifndef BMHARNESS_HPP__
#define BMHARNESS_HPP__

#include <cstdlib>
#include <iostream>
#include <signal.h>
#include <pthread.h>
#include <api/api.hpp>
#include <common/platform.hpp>
#include <common/locks.hpp>
#include "bmconfig.hpp"

using std::string;
using std::cout;

Config::Config() :
    bmname(""),
    duration(1),
    execute(0),
    threads(1),
    nops_after_tx(0),
    elements(256),
    lookpct(34),
    inspct(66),
    sets(1),
    ops(1),
    time(0),
    running(true),
    txcount(0)
{
}

Config CFG TM_ALIGN(64);

namespace
{

  /**
   * Print benchmark configuration output
   */
  void dump_csv()
  {
      // csv output
      std::cout << "csv"
                << ", ALG=" << TM_GET_ALGNAME()
                << ", B=" << CFG.bmname     << ", R=" << CFG.lookpct
                << ", d=" << CFG.duration   << ", p=" << CFG.threads
                << ", X=" << CFG.execute    << ", m=" << CFG.elements
                << ", S=" << CFG.sets       << ", O=" << CFG.ops
                << ", txns=" << CFG.txcount << ", time=" << CFG.time
                << ", throughput="
                << (1000000000LL * CFG.txcount) / (CFG.time)
                << std::endl;
  }

  /**
   *  Print usage
   */
  void usage()
  {
      std::cerr << "Usage: CounterBench -C <stm algorithm> [flags]\n";
      std::cerr << "    -d: number of seconds to time (default 1)\n";
      std::cerr << "    -X: execute fixed tx count, not for a duration\n";
      std::cerr << "    -p: number of threads (default 1)\n";
      std::cerr << "    -N: nops between transactions (default 0)\n";
      std::cerr << "    -R: % lookup txns (remainder split ins/rmv)\n";
      std::cerr << "    -m: range of keys in data set\n";
      std::cerr << "    -B: name of benchmark\n";
      std::cerr << "    -S: number of sets to build (default 1)\n";
      std::cerr << "    -O: operations per transaction (default 1)\n";
      std::cerr << "    -h: print help (this message)\n\n";
  }

/**
 *  Parse command line arguments
 */
void
parseargs(int argc, char** argv)
{
    // parse the command-line options
    int opt;
    while ((opt = getopt(argc, argv, "N:d:p:hX:B:m:R:S:O:")) != -1) {
        switch(opt) {
          case 'd': CFG.duration      = strtol(optarg, NULL, 10); break;
          case 'p': CFG.threads       = strtol(optarg, NULL, 10); break;
          case 'N': CFG.nops_after_tx = strtol(optarg, NULL, 10); break;
          case 'X': CFG.execute       = strtol(optarg, NULL, 10); break;
          case 'B': CFG.bmname        = std::string(optarg); break;
          case 'm': CFG.elements      = strtol(optarg, NULL, 10); break;
          case 'S': CFG.sets          = strtol(optarg, NULL, 10); break;
          case 'O': CFG.ops           = strtol(optarg, NULL, 10); break;
          case 'R':
            CFG.lookpct = strtol(optarg, NULL, 10);
            CFG.inspct = (100 - CFG.lookpct)/2 + strtol(optarg, NULL, 10);
            break;
          case 'h':
            usage();
        }
    }
}

/**
 *  Run some nops between transactions, to simulate some time being spent on
 *  computation
 */
void
nontxnwork()
{
    if (CFG.nops_after_tx)
        for (uint32_t i = 0; i < CFG.nops_after_tx; i++)
            spin64();
}

/*** Signal handler to end a test */
extern "C" void catch_SIGALRM(int) {
    CFG.running = false;
}

/**
 *  Support a few lightweight barriers
 */
void
barrier(uint32_t which)
{
    static volatile uint32_t barriers[16] = {0};
    CFENCE;
    fai32(&barriers[which]);
    while (barriers[which] != CFG.threads) { }
    CFENCE;
}

/*** Run a timed or fixed-count experiment */
void
run(uintptr_t id)
{
    // create a transactional context (repeat calls from thread 0 are OK)
    TM_THREAD_INIT();

    // wait until all threads created, then set alarm and read timer
    barrier(0);
    if (id == 0) {
        if (!CFG.execute) {
            signal(SIGALRM, catch_SIGALRM);
            alarm(CFG.duration);
        }
        CFG.time = getElapsedTime();
    }

    // wait until read of start timer finishes, then start transactios
    barrier(1);

    uint32_t count = 0;
    uint32_t seed = id; // not everyone needs a seed, but we have to support it
    if (!CFG.execute) {
        // run txns until alarm fires
        while (CFG.running) {
            bench_test(id, &seed);
            ++count;
            nontxnwork(); // some nontx work between txns?
        }
    }
    else {
        // run fixed number of txns
        for (uint32_t e = 0; e < CFG.execute; e++) {
            bench_test(id, &seed);
            ++count;
            nontxnwork(); // some nontx work between txns?
        }
    }

    // wait until all txns finish, then get time
    barrier(2);
    if (id == 0)
        CFG.time = getElapsedTime() - CFG.time;

    // add this thread's count to an accumulator
    faa32(&CFG.txcount, count);
}

/**
 *  pthread wrapper for running the experiments
 *
 *  NB: noinline prevents this from getting inlined into main (and prevents
 *      run from being inlined there as well. This eliminates an
 *      _ITM_initializeProcess ordering problem if there's a transaction
 *      lexically scoped inside of main.
 */
NOINLINE
void*
run_wrapper(void* i)
{
    run((uintptr_t)i);
    TM_THREAD_SHUTDOWN();
    return NULL;
}
}

/**
 *  Main routine: parse args, set up the TM system, prep the benchmark, run
 *  the experiments, verify results, print results, and shut down the system
 */
int main(int argc, char** argv) {
    parseargs(argc, argv);
    bench_reparse();
    TM_SYS_INIT();
    TM_THREAD_INIT();
    bench_init();

    void* args[256];
    pthread_t tid[256];

    // set up configuration structs for the threads we'll create
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
    for (uintptr_t i = 0; i < CFG.threads; i++)
        args[i] = reinterpret_cast<void*>(i);

    // actually create the threads
    for (uint32_t j = 1; j < CFG.threads; j++)
        pthread_create(&tid[j], &attr, &run_wrapper, args[j]);

    // all of the other threads should be queued up, waiting to run the
    // benchmark, but they can't until this thread starts the benchmark
    // too...
    run_wrapper(args[0]);

    // Don't call any more transactional functions, because run_wrapper called
    // shutdown.

    // everyone should be done.  Join all threads so we don't leave anything
    // hanging around
    for (uint32_t k = 1; k < CFG.threads; k++)
        pthread_join(tid[k], NULL);

    bool v = bench_verify();
    std::cout << "Verification: " << (v ? "Passed" : "Failed") << "\n";

    dump_csv();

    // And call sys shutdown stuff
    TM_SYS_SHUTDOWN();
    return 0;
}

#endif // BMHARNESS_HPP__


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

angular.module('mm.core')

.constant('mmCoreConfigStore', 'config')

.config(function($mmAppProvider, mmCoreConfigStore) {
    var stores = [
        {
            name: mmCoreConfigStore,
            keyPath: 'name'
        }
    ];
    $mmAppProvider.registerStores(stores);
})

/**
 * Factory to provide access to app config and settings. It should not be abused into a temporary storage.
 *
 * @module mm.core
 * @ngdoc service
 * @name $mmConfig
 * @description
 * Provides access to the app settings.
 */
.factory('$mmConfig', function($http, $q, $log, $mmApp, mmCoreConfigStore) {

    $log = $log.getInstance('$mmConfig');

    var initialized = false,
        self = {
            config: {}
        };

    function init() {
        var deferred = $q.defer();

        $http.get('config.json').then(function(response) {
            var data = response.data;
            for (var name in data) {
                self.config[name] = data[name];
            }
            initialized = true;
            deferred.resolve();
        }, deferred.reject);

        return deferred.promise;
    };

    /**
     * Get an app setting.
     *
     * @module mm.core
     * @ngdoc method
     * @name $mmConfig#get
     * @param {String} name           The config name.
     * @param {Mixed}  [defaultValue] Default value to use if the entry is not found.
     * @return {Promise}              Resolves upon success along with the config data. Reject on failure.
     * @description
     * Get an app setting.
     */
    self.get = function(name, defaultValue) {

        if (!initialized) {
            return init().then(function() {
                return getConfig(name);
            }, function() {
                $log.error('Failed to initialize $mmConfig.');
                return $q.reject();
            });
        }

        return getConfig(name);

        function getConfig(name) {
            var deferred = $q.defer(),
                value = self.config[name];

            if (typeof value == 'undefined') {
                $mmApp.getDB().get(mmCoreConfigStore, name).then(function(entry) {
                    deferred.resolve(entry.value);
                }, function() {
                    if (typeof defaultValue != 'undefined') {
                        deferred.resolve(defaultValue);
                    } else {
                        deferred.reject();
                    }
                });
            } else {
                deferred.resolve(value);
            }

            return deferred.promise;
        }
    };

    /**
     * Set an app setting.
     *
     * @module mm.core
     * @ngdoc service
     * @name $mmConfig#set
     * @param {String} name The config name.
     * @param {Mixed} value The config value.
     * @return {Promise}    Promise which resolves on success, providing no data.
     * @description
     * Set an app setting.
     */
    self.set = function(name, value) {

        if (!initialized) {
            return init().then(function() {
                return setConfig(name, value);
            }, function() {
                $log.error('Failed to initialize $mmConfig.');
                return $q.reject();
            });
        }

        return setConfig(name, value);

        function setConfig(name, value) {
            var deferred,
                fromStatic = self.config[name];

            if (typeof(fromStatic) === 'undefined') {
                return $mmApp.getDB().insert(mmCoreConfigStore, {name: name, value: value});
            }

            $log.error('Cannot save static config setting \'' + name + '\'.');
            deferred = $q.defer()
            deferred.reject();
            return deferred.promise;
        }
    };

    /**
     * Deletes an app setting.
     *
     * @module mm.core
     * @ngdoc method
     * @name $mmConfig#delete
     * @param {String} name The config name.
     * @return {Promise}    Promise which resolves on success, providing no data.
     * @description
     * Delete an app setting.
     */
    self.delete = function(name) {

        if (!initialized) {
            return init().then(function() {
                return deleteConfig(name);
            }, function() {
                $log.error('Failed to initialize $mmConfig.');
                return $q.reject();
            });
        }

        return deleteConfig(name);

        function deleteConfig(name) {
            var deferred,
                fromStatic = self.config[name];

            if (typeof(fromStatic) === 'undefined') {
                return $mmApp.getDB().remove(mmCoreConfigStore, name);
            }

            $log.error('Cannot delete static config setting \'' + name + '\'.');
            deferred = $q.defer()
            deferred.reject();
            return deferred.promise;
        }
    };

    return self;
});


text:
require 'capistrano/framework'
require 'capistrano/file-permissions'

# load all tasks
# Dir.glob('./tasks/*.rake').each { |task| load File.expand_path(task)}
load File.expand_path('../tasks/composer.rake', __FILE__)
load File.expand_path('../tasks/phpfpm.rake', __FILE__)
load File.expand_path('../tasks/react.rake', __FILE__)
load File.expand_path('../tasks/permissions.rake', __FILE__)
load File.expand_path('../tasks/supervisor.rake', __FILE__)
load File.expand_path('../tasks/migrate.rake', __FILE__)
load File.expand_path('../tasks/db_scripts.rake', __FILE__)
load File.expand_path('../tasks/goose_migrate.rake', __FILE__)


text:
slug: Shrek-Cat
template_id: 434
title: Shrek Cat
---


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecania erysibe var. cinereofusca Mudd

### Remarks
null


text:
using System.IO;

namespace Mailgun.Attachments
{
    /// <summary>
    /// A generic email attachment from a stream. Can be extended to provide mroe specific attachment types or used as-is.
    /// </summary>
    public class MailgunAttachment
    {
        /// <summary>
        /// Gets or sets the name of the attachment.
        /// </summary>
        public string FileName { get; set; }

        /// <summary>
        /// Gets or sets the stream containing the attachment contents.
        /// </summary>
        public Stream FileContentStream { get; set; }

        /// <summary>
        /// Constructs a new MailgunAttachment with the specified name and content stream.
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="fileContentStream"></param>
        public MailgunAttachment(string filename, Stream fileContentStream)
        {
            FileName = filename;
            FileContentStream = fileContentStream;
        }
    }
}


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   demo script for mesh generation from binarized volumetric image
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% preparation
% user must add the path of iso2mesh to matlab path list
% addpath('../');

% user need to add the full path to .../iso2mesh/bin directory
% to windows/Linux/Unix PATH environment variable

%% load the sample data
load rat_head.mat

% volimage is a volumetric image such as an X-ray or MRI image
% A,b are registration matrix and vector, respectively
%% perform mesh generation

%% use the alternative 'simplify' method: first create voxel-based
% surface mesh, and then resample it to desired density.
% this method does not guarantee to be free of self-intersecting
% element, as 'cgalsurf' promises.

[node,elem,face]=vol2mesh(volimage>0.05,1:size(volimage,1),1:size(volimage,2),...
                          1:size(volimage,3),0.1,2,1,'simplify');

%% visualize the resulting mesh

plotmesh(node,face);
axis equal;