text:
const getUuid = require('~/plugins/utils').getUuid;

import getStats from './getStats';

const updateableDropPart = (fullComponent) => {
  let comp = fullComponent.component;
  let keyQueries = [];
  for (let sink of comp.dataSinks) {
    keyQueries.push(fetch('/apina/datasinks/getReadKey/'+sink.id, {credentials: 'include'}).then(r => r.json()));
    window.socket.on(sink.title, newData => {
      let newDataEvent = new CustomEvent('newData', { detail: { dataSink: sink, newData } });
      fullComponent.node.dispatchEvent(newDataEvent);
    });
  }
  for (let source of comp.dataSources) {
    fetch(source.url).then(r => r.json()).then(resp => {
      let newDataEvent = new CustomEvent('newData', { detail: { dataSource: source, newData: resp } });
      fullComponent.node.dispatchEvent(newDataEvent);
    });
    if (source.interval) {
      fullComponent.intervals.push({sourceTitle: source.title, timer: setInterval(() => {
        fetch(source.url).then(r => r.json()).then(resp => {
          let newDataEvent = new CustomEvent('newData', { detail: { dataSource: source, newData: resp } });
          fullComponent.node.dispatchEvent(newDataEvent);
        });
      }, source.interval) });
    }
  }
  Promise.all(keyQueries).then(keys => {
    let dataQueries = [];
    for (let key in keys) {
      comp.dataSinks[key].readKey = keys[key].readKey;
      let orderBy = '', limit = '';
      if (comp.dataSinks[key].orderBy) {
        orderBy = `orderBy=${comp.dataSinks[key].orderBy}&`;
      }
      if (comp.dataSinks[key].limit) {
        limit = `limit=${comp.dataSinks[key].limit}`;
      }
      dataQueries.push(fetch(`/d/r/${keys[key].readKey}/${comp.dataSinks[key].title}?${orderBy}${limit}`, {credentials: 'include'}).then(r => r.json()));
    }
    Promise.all(dataQueries).then(data => {
      let detail = {};
      for (let key in keys) {
        detail[keys[key].title] = data[key];
        detail[keys[key].title].stats = getStats(keys[key], data[key]);
      }
      let dataEvent = new CustomEvent('data', { detail });
      fullComponent.node.dispatchEvent(dataEvent);
    });
  });
};

const fakeDrop = (fullComponent, self, editing = false, isMobile = false) => {

    let comp = fullComponent.component;
    let c = d3.select('.canvas-container');
    let uuid = getUuid();
    let div = c.append('div')
      .attr('class', isMobile ? 'box-mobile' : 'box')
      .style('height', comp.height + 'px')
      .style('width', isMobile ? 'calc(100% - 4px)' : comp.width + 'px')
      .html(comp.content)
      .attr('offsetX', isMobile ? 0 : (parseInt(comp.offsetX) || 0))
      .attr('offsetY', isMobile ? 0 : (parseInt(comp.offsetY) || 0))
      .attr('uuid', uuid)
      .attr('id', uuid)
      .style('position', isMobile ? 'relative' : 'absolute')
      .style('transform', `translate(${isMobile ? 0 : comp.offsetX}px, ${isMobile ? 0 : comp.offsetY}px)`);
    if (!isMobile) {
      div.call(d3.drag()
        .on('drag', self.dragged)
        .on('end', () => {
          //dragging = false;
          self.clickOffsetX = false;
          self.clickOffsetY = false;
        })
      );
    }

    fullComponent.node = div.node();
    fullComponent.intervals = [];
    let tb = div.append('div')
      .attr('class', `title-bar`)
      .html(`<span id="componentTitle-${uuid}">${comp.title}</span>`);

    self.components.push(div);

    updateableDropPart(fullComponent);

    self.individualComponents.push({uuid, component: comp, node: fullComponent.node, intervals: fullComponent.intervals });
    let node = fullComponent.node;
    (() => { eval(comp.script) }).call(isMobile ? Object.assign(comp, { width: node.clientWidth }) : comp);
    let createdEvent = new CustomEvent('created', { detail: { uuid, width: parseInt(isMobile ? node.clientWidth : comp.width), height: parseInt(comp.height) } });
    setTimeout(() => fullComponent.node.dispatchEvent(createdEvent), 0);

    if (editing && !isMobile) {
      let tb = node.querySelector(`.title-bar`);
      let trashIcon = document.createElement('span');
      trashIcon.className = 'trash-icon material-icons';
      trashIcon.innerText = 'delete';
      trashIcon.onclick = window.deleteComponent.bind(self, uuid);
      tb.append(trashIcon);
      let settingsIcon = document.createElement('span');
      settingsIcon.className = 'settings-icon material-icons';
      settingsIcon.innerText = 'settings';
      settingsIcon.onclick = window.showSettings.bind(self, uuid);
      tb.append(settingsIcon);
      let resizer = document.createElement('div');
      resizer.className = 'resizer';
      node.appendChild(resizer);
      const resize = (e) => {
        if (!e.shiftKey) { return stopResize(e); }
        e.preventDefault();
        e.stopPropagation();
        let newWidth = parseInt(node.style.width) + e.movementX;
        let newHeight = parseInt(node.style.height) + e.movementY;
        let event = new CustomEvent('resized', { detail: { width: newWidth, height: newHeight } });
        node.style.width = newWidth + 'px';
        node.style.height = newHeight + 'px';
        fullComponent.component.width = newWidth;
        fullComponent.component.height = newHeight;
        node.dispatchEvent(event);
      }
      const initResize = (e) => {
        if (!e.shiftKey) return;
        e.preventDefault();
        e.stopPropagation();
        document.addEventListener('mousemove', resize, false);
        document.addEventListener('mouseup', stopResize, false);
      }
      const stopResize = (e) => {
        document.removeEventListener('mousemove', resize, false);
        document.removeEventListener('mouseup', stopResize, false);
      }
      resizer.addEventListener('mousedown', initResize, false);

    }

    if (comp.externalScripts) {
      for (let externalScript of comp.externalScripts) {
        let script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = externalScript;
        let event = new CustomEvent('externalResourceLoaded', { detail: { type: 'script', uri: externalScript } });
        script.onload = () => setTimeout(() => node.dispatchEvent(event), 0);
        document.body.append(script);
      }
    }
    if (comp.externalStyles) {
      for (let externalStyle of comp.externalStyles) {
        let link = document.createElement('link');
        link.type = 'text/css';
        link.rel = 'stylesheet';
        link.href = externalStyle;
        let event = new CustomEvent('externalResourceLoaded', { detail: { type: 'style', uri: externalStyle } });
        link.onload = () => setTimeout(() => node.dispatchEvent(event), 0);
        document.body.append(link);
      }
    }
    return fullComponent;
};

export {
  fakeDrop,
  updateableDropPart,
};


text:
package com.rxjava2.android.samples.utils;

import android.util.Log;

import com.androidnetworking.error.ANError;
import com.rxjava2.android.samples.model.ApiUser;
import com.rxjava2.android.samples.model.User;

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

/**
 * Created by amitshekhar on 27/08/16.
 */
public class Utils {

    private Utils() {
        // This class in not publicly instantiable.
    }

    public static List<User> getUserList() {

        List<User> userList = new ArrayList<>();

        User userOne = new User();
        userOne.firstname = "Amit";
        userOne.lastname = "Shekhar";
        userList.add(userOne);

        User userTwo = new User();
        userTwo.firstname = "Manish";
        userTwo.lastname = "Kumar";
        userList.add(userTwo);

        User userThree = new User();
        userThree.firstname = "Sumit";
        userThree.lastname = "Kumar";
        userList.add(userThree);

        return userList;
    }

    public static List<ApiUser> getApiUserList() {

        List<ApiUser> apiUserList = new ArrayList<>();

        ApiUser apiUserOne = new ApiUser();
        apiUserOne.firstname = "Amit";
        apiUserOne.lastname = "Shekhar";
        apiUserList.add(apiUserOne);

        ApiUser apiUserTwo = new ApiUser();
        apiUserTwo.firstname = "Manish";
        apiUserTwo.lastname = "Kumar";
        apiUserList.add(apiUserTwo);

        ApiUser apiUserThree = new ApiUser();
        apiUserThree.firstname = "Sumit";
        apiUserThree.lastname = "Kumar";
        apiUserList.add(apiUserThree);

        return apiUserList;
    }

    public static List<User> convertApiUserListToUserList(List<ApiUser> apiUserList) {

        List<User> userList = new ArrayList<>();

        for (ApiUser apiUser : apiUserList) {
            User user = new User();
            user.firstname = apiUser.firstname;
            user.lastname = apiUser.lastname;
            userList.add(user);
        }

        return userList;
    }

    public static List<User> getUserListWhoLovesCricket() {

        List<User> userList = new ArrayList<>();

        User userOne = new User();
        userOne.id = 1;
        userOne.firstname = "Amit";
        userOne.lastname = "Shekhar";
        userList.add(userOne);

        User userTwo = new User();
        userTwo.id = 2;
        userTwo.firstname = "Manish";
        userTwo.lastname = "Kumar";
        userList.add(userTwo);

        return userList;
    }

    public static List<User> getUserListWhoLovesFootball() {

        List<User> userList = new ArrayList<>();

        User userOne = new User();
        userOne.id = 1;
        userOne.firstname = "Amit";
        userOne.lastname = "Shekhar";
        userList.add(userOne);

        User userTwo = new User();
        userTwo.id = 3;
        userTwo.firstname = "Sumit";
        userTwo.lastname = "Kumar";
        userList.add(userTwo);

        return userList;
    }

    public static List<User> filterUserWhoLovesBoth(List<User> cricketFans, List<User> footballFans) {
        List<User> userWhoLovesBoth = new ArrayList<User>();
        for (User cricketFan : cricketFans) {
            for (User footballFan : footballFans) {
                if (cricketFan.id == footballFan.id) {
                    userWhoLovesBoth.add(cricketFan);
                }
            }
        }
        return userWhoLovesBoth;
    }

    public static void logError(String TAG, Throwable e) {
        if (e instanceof ANError) {
            ANError anError = (ANError) e;
            if (anError.getErrorCode() != 0) {
                // received ANError from server
                // error.getErrorCode() - the ANError code from server
                // error.getErrorBody() - the ANError body from server
                // error.getErrorDetail() - just a ANError detail
                Log.d(TAG, "onError errorCode : " + anError.getErrorCode());
                Log.d(TAG, "onError errorBody : " + anError.getErrorBody());
                Log.d(TAG, "onError errorDetail : " + anError.getErrorDetail());
            } else {
                // error.getErrorDetail() : connectionError, parseError, requestCancelledError
                Log.d(TAG, "onError errorDetail : " + anError.getErrorDetail());
            }
        } else {
            Log.d(TAG, "onError errorMessage : " + e.getMessage());
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace HbgEventImporter\Taxonomy;

class EventTags
{
    public function __construct()
    {
        add_action('init', array($this, 'registerEventTags'));
    }

    public function registerEventTags()
    {
        $labels = array(
            'name'                  => _x('Tags', 'Taxonomy plural name', 'event-manager'),
            'singular_name'         => _x('Tag', 'Taxonomy singular name', 'event-manager'),
            'search_items'          => __('Search tags', 'event-manager'),
            'popular_items'         => __('Popular tags', 'event-manager'),
            'all_items'             => __('All tags', 'event-manager'),
            'parent_item'           => __('Parent', 'event-manager'),
            'parent_item_colon'     => __('Parent', 'event-manager'),
            'edit_item'             => __('Edit tag', 'event-manager'),
            'update_item'           => __('Update', 'event-manager'),
            'add_new_item'          => __('Add new tag', 'event-manager'),
            'new_item_name'         => __('New tag', 'event-manager'),
            'add_or_remove_items'   => __('Add or remove tags', 'event-manager'),
            'choose_from_most_used' => __('Choose from most used tags', 'event-manager'),
            'menu_name'             => __('Tags', 'event-manager'),
        );

        $capabilities = array(
            'manage_terms' => 'edit_posts',
            'edit_terms'   => 'edit_posts',
            'delete_terms' => 'edit_posts',
            'assign_terms' => 'read',
        );

        $args = array(
            'capabilities'          => $capabilities,
            'labels'                => $labels,
            'public'                => true,
            'show_in_nav_menus'     => true,
            'show_admin_column'     => true,
            'hierarchical'          => false,
            'show_tagcloud'         => true,
            'show_ui'               => true,
            'query_var'             => true,
            'rewrite'               => true
        );

        register_taxonomy('event_tags', array('event'), $args);
    }
}


text:
FOUNDATION_EXPORT double Pods_lottie_ios_TestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_lottie_ios_TestsVersionString[];


text:
Package.describe({
  name: 'ilfrich:accounts-ldap',
  version: '1.0.0',
  summary: 'Accounts login handler for LDAP using ldapjs and allowing to search anonymously for the DN before binding.',
  git: 'https://github.com/ilfrich/meteor-accounts-ldap',
  documentation: 'README.md'
});

Npm.depends({
    'ldapjs': '1.0.0'
});

Package.onUse(function(api) {
    api.versionsFrom('1.3.1');

    api.use(['templating'], 'client');
    api.use(['accounts-base', 'check'], 'server');
    api.imply(['accounts-base', 'accounts-password']);

    api.mainModule('ldap_client.js', 'client');
    api.mainModule('ldap_server.js', 'server');

    api.export('LDAP', 'server');
    api.export('LDAP_DEFAULTS', 'server');
});


text:
layout: page
title: Knapp - Santos Wedding
date: 2016-05-24
author: Jeffrey Garza
tags: weekly links, java
status: published
summary: Donec dapibus libero ut orci semper fermentum. Suspendisse efficitur porta.
banner: images/banner/office-01.jpg
booking:
  startDate: 08/19/2016
  endDate: 08/23/2016
  ctyhocn: DSMAKHX
  groupCode: KSW
published: true
---
Nullam fringilla tellus nec volutpat blandit. Donec porta ex vehicula arcu iaculis, ut eleifend nulla lacinia. Duis id ipsum eros. Nunc molestie eros et ligula condimentum, vitae luctus mi rhoncus. Vivamus venenatis lacus nibh, id egestas ipsum fringilla nec. In sollicitudin tempor dui, a viverra mi rutrum at. Aliquam non consequat ex. Vestibulum placerat condimentum ante eu aliquet. Etiam non nisi purus. Sed fermentum ac diam a malesuada. Ut ac mauris rhoncus, commodo lacus non, vulputate risus. Pellentesque euismod pulvinar porttitor. Phasellus nec nibh viverra, volutpat mi quis, venenatis quam.

* Maecenas lobortis turpis in finibus pellentesque
* Quisque fermentum ligula eget felis consequat maximus
* Nullam ullamcorper urna sit amet lacinia placerat
* Sed quis ligula ut orci euismod posuere eu sit amet massa.

Nunc feugiat arcu sit amet neque hendrerit sagittis. Suspendisse eleifend cursus sapien. In convallis tristique velit in lobortis. Phasellus pretium leo ac tincidunt pharetra. Fusce purus dui, blandit in vestibulum at, semper a mauris. In luctus vel mi id sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam non nisl sed nibh consequat gravida eget quis quam. Quisque porttitor odio magna, et blandit nisl commodo vel. Morbi quam nibh, varius tincidunt mattis eget, consectetur eget elit. Pellentesque et elit at felis tincidunt sodales. Nulla eget fringilla enim. Nunc non justo leo.


text:
$LOAD_PATH.push('.')

status = `sh -c "cd ~; vagrant status"`
puts status

running = status.match(/default\s*running/)
unless running
  puts `sh -c "cd ~; vagrant up"`
end

puts `ssh default "source ~/.bash_profile; cd /cocos2dx/cor-client/projects/font_atlas; time ruby gen.rb"`
puts `ssh default "source ~/.bash_profile; cd /cocos2dx/cor-client/projects/font_atlas; time ruby gen_tempesta.rb"`

unless running
  puts `sh -c "cd ~; vagrant halt"`
end


text:
package org.apache.jackrabbit.oak.segment.spi.persistence.persistentcache;

import static java.lang.Thread.currentThread;
import static java.util.concurrent.TimeUnit.SECONDS;

import com.google.common.base.Stopwatch;

import org.apache.jackrabbit.oak.cache.AbstractCacheStats;
import org.apache.jackrabbit.oak.commons.Buffer;
import org.apache.jackrabbit.oak.segment.spi.RepositoryNotReachableException;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Closeable;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public abstract class AbstractPersistentCache implements PersistentCache, Closeable {
    private static final Logger logger = LoggerFactory.getLogger(AbstractPersistentCache.class);

    public static final int THREADS = Integer.getInteger("oak.segment.cache.threads", 10);

    protected ExecutorService executor;
    protected AtomicLong cacheSize = new AtomicLong(0);
    protected PersistentCache nextCache;
    protected final Set<String> writesPending;

    protected SegmentCacheStats segmentCacheStats;

    public AbstractPersistentCache() {
        executor = Executors.newFixedThreadPool(THREADS);
        writesPending = ConcurrentHashMap.newKeySet();
    }

    public PersistentCache linkWith(AbstractPersistentCache nextCache) {
        this.nextCache = nextCache;
        return nextCache;
    }

    @Override
    public Buffer readSegment(long msb, long lsb, @NotNull Callable<Buffer> loader) {
        Buffer segment = readSegmentInternal(msb, lsb);
        if (segment != null) {
            segmentCacheStats.hitCount.incrementAndGet();
            return segment;
        }
        segmentCacheStats.missCount.incrementAndGet();

        // Either use the next cache or the 'loader'
        Callable<Buffer> nextLoader = nextCache != null
                ? () -> nextCache.readSegment(msb, lsb, loader)
                : loader;

        Stopwatch stopwatch = Stopwatch.createStarted();
        try {
            segment = nextLoader.call();

            if (segment != null) {
                recordCacheLoadTimeInternal(stopwatch.elapsed(TimeUnit.NANOSECONDS), true);
                writeSegment(msb, lsb, segment);
            }

            return segment;
        } catch (RepositoryNotReachableException e) {
            recordCacheLoadTimeInternal(stopwatch.elapsed(TimeUnit.NANOSECONDS), false);

            // rethrow exception so that this condition can be distinguished from other types of errors (see OAK-9303)
            throw e;
        } catch (Exception t) {
            logger.error("Exception while loading segment {} from remote store or linked cache", new UUID(msb, lsb), t);
            recordCacheLoadTimeInternal(stopwatch.elapsed(TimeUnit.NANOSECONDS), false);
        }
        return segment;
    }

    /**
     * Reads the segment from the cache.
     * If segment is not found, this method does not query next cache that was set with {@link #linkWith(AbstractPersistentCache)}
     *
     * @param msb the most significant bits of the identifier of the segment
     * @param lsb the least significant bits of the identifier of the segment
     * @return byte buffer containing the segment data or null if the segment doesn't exist
     */
    protected abstract Buffer readSegmentInternal(long msb, long lsb);

    /**
     * Records time spent to load data from external source, after cache miss.
     *
     * @param loadTime   load time in nanoseconds
     * @param successful indicates whether loading of the segment into cache was successful
     */
    protected final void recordCacheLoadTimeInternal(long loadTime, boolean successful) {
        if (successful) {
            segmentCacheStats.loadSuccessCount.incrementAndGet();
        } else {
            segmentCacheStats.loadExceptionCount.incrementAndGet();
        }
        segmentCacheStats.loadTime.addAndGet(loadTime);
    }

    /**
     * @return Statistics for this cache.
     */
    @NotNull
    public AbstractCacheStats getCacheStats() {
        return segmentCacheStats;
    }

    @Override
    public void close() {
        try {
            executor.shutdown();
            if (executor.awaitTermination(60, SECONDS)) {
                logger.debug("The persistent cache scheduler was successfully shut down");
            } else {
                logger.warn("The persistent cache scheduler takes too long to shut down");
            }
        } catch (InterruptedException e) {
            logger.warn("Interrupt while shutting down the persistent cache scheduler", e);
            currentThread().interrupt();
        }
    }

    public int getWritesPending() {
        return writesPending.size();
    }
}


text:
#include "../../Include/RmlUi/Core/ElementText.h"
#include "ElementDefinition.h"
#include "ElementStyle.h"
#include "../../Include/RmlUi/Core/Core.h"
#include "../../Include/RmlUi/Core/Context.h"
#include "../../Include/RmlUi/Core/ElementDocument.h"
#include "../../Include/RmlUi/Core/ElementUtilities.h"
#include "../../Include/RmlUi/Core/Event.h"
#include "../../Include/RmlUi/Core/FontEngineInterface.h"
#include "../../Include/RmlUi/Core/GeometryUtilities.h"
#include "../../Include/RmlUi/Core/Property.h"
#include "../../Include/RmlUi/Core/Profiling.h"

namespace Rml {

static bool BuildToken(String& token, const char*& token_begin, const char* string_end, bool first_token, bool collapse_white_space, bool break_at_endline, Style::TextTransform text_transformation, bool decode_escape_characters);
static bool LastToken(const char* token_begin, const char* string_end, bool collapse_white_space, bool break_at_endline);

ElementText::ElementText(const String& tag) : Element(tag), colour(255, 255, 255), decoration(this)
{
	dirty_layout_on_change = true;

	generated_decoration = Style::TextDecoration::None;
	decoration_property = Style::TextDecoration::None;

	geometry_dirty = true;

	font_effects_handle = 0;
	font_effects_dirty = true;
	font_handle_version = 0;
}

ElementText::~ElementText()
{
}

void ElementText::SetText(const String& _text)
{
	if (text != _text)
	{
		text = _text;

		if (dirty_layout_on_change)
			DirtyLayout();
	}
}

const String& ElementText::GetText() const
{
	return text;
}

void ElementText::OnRender()
{
	RMLUI_ZoneScoped;

	FontFaceHandle font_face_handle = GetFontFaceHandle();
	if (font_face_handle == 0)
		return;

	// If our font effects have potentially changed, update it and force a geometry generation if necessary.
	if (font_effects_dirty && UpdateFontEffects())
		geometry_dirty = true;

	// Dirty geometry if font version has changed.
	int new_version = GetFontEngineInterface()->GetVersion(font_face_handle);
	if (new_version != font_handle_version)
	{
		font_handle_version = new_version;
		geometry_dirty = true;
	}

	// Regenerate the geometry if the colour or font configuration has altered.
	if (geometry_dirty)
		GenerateGeometry(font_face_handle);

	// Regenerate text decoration if necessary.
	if (decoration_property != generated_decoration)
	{
		decoration.Release(true);

		if (decoration_property != Style::TextDecoration::None)
			GenerateDecoration(font_face_handle);

		generated_decoration = decoration_property;
	}

	const Vector2f translation = GetAbsoluteOffset();

	bool render = true;
	Vector2i clip_origin;
	Vector2i clip_dimensions;
	if (GetContext()->GetActiveClipRegion(clip_origin, clip_dimensions))
	{
		float clip_top = (float)clip_origin.y;
		float clip_left = (float)clip_origin.x;
		float clip_right = (float)(clip_origin.x + clip_dimensions.x);
		float clip_bottom = (float)(clip_origin.y + clip_dimensions.y);
		float line_height = (float)GetFontEngineInterface()->GetLineHeight(GetFontFaceHandle());

		render = false;
		for (size_t i = 0; i < lines.size(); ++i)
		{
			const Line& line = lines[i];
			float x = translation.x + line.position.x;
			float y = translation.y + line.position.y;

			bool render_line = !(x > clip_right);
			render_line = render_line && !(x + line.width < clip_left);

			render_line = render_line && !(y - line_height > clip_bottom);
			render_line = render_line && !(y < clip_top);

			if (render_line)
			{
				render = true;
				break;
			}
		}
	}

	if (render)
	{
		for (size_t i = 0; i < geometry.size(); ++i)
			geometry[i].Render(translation);
	}

	if (decoration_property != Style::TextDecoration::None)
		decoration.Render(translation);
}

// Generates a token of text from this element, returning only the width.
bool ElementText::GenerateToken(float& token_width, int line_begin)
{
	RMLUI_ZoneScoped;

	// Bail if we don't have a valid font face.
	FontFaceHandle font_face_handle = GetFontFaceHandle();
	if (font_face_handle == 0 ||
		line_begin >= (int) text.size())
		return 0;

	// Determine how we are processing white-space while formatting the text.
	using namespace Style;
	auto& computed = GetComputedValues();
	WhiteSpace white_space_property = computed.white_space;
	bool collapse_white_space = white_space_property == WhiteSpace::Normal ||
								white_space_property == WhiteSpace::Nowrap ||
								white_space_property == WhiteSpace::Preline;
	bool break_at_endline = white_space_property == WhiteSpace::Pre ||
							white_space_property == WhiteSpace::Prewrap ||
							white_space_property == WhiteSpace::Preline;

	const char* token_begin = text.c_str() + line_begin;
	String token;

	BuildToken(token, token_begin, text.c_str() + text.size(), true, collapse_white_space, break_at_endline, computed.text_transform, true);
	token_width = (float) GetFontEngineInterface()->GetStringWidth(font_face_handle, token);

	return LastToken(token_begin, text.c_str() + text.size(), collapse_white_space, break_at_endline);
}

// Generates a line of text rendered from this element
bool ElementText::GenerateLine(String& line, int& line_length, float& line_width, int line_begin, float maximum_line_width, float right_spacing_width, bool trim_whitespace_prefix, bool decode_escape_characters)
{
	RMLUI_ZoneScoped;

	FontFaceHandle font_face_handle = GetFontFaceHandle();

	// Initialise the output variables.
	line.clear();
	line_length = 0;
	line_width = 0;

	// Bail if we don't have a valid font face.
	if (font_face_handle == 0)
		return true;

	// Determine how we are processing white-space while formatting the text.
	using namespace Style;
	auto& computed = GetComputedValues();
	WhiteSpace white_space_property = computed.white_space;
	bool collapse_white_space = white_space_property == WhiteSpace::Normal ||
								white_space_property == WhiteSpace::Nowrap ||
								white_space_property == WhiteSpace::Preline;
	bool break_at_line = (maximum_line_width >= 0) &&
		                   (white_space_property == WhiteSpace::Normal ||
							white_space_property == WhiteSpace::Prewrap ||
							white_space_property == WhiteSpace::Preline);
	bool break_at_endline = white_space_property == WhiteSpace::Pre ||
							white_space_property == WhiteSpace::Prewrap ||
							white_space_property == WhiteSpace::Preline;

	TextTransform text_transform_property = computed.text_transform;
	WordBreak word_break = computed.word_break;

	FontEngineInterface* font_engine_interface = GetFontEngineInterface();

	// Starting at the line_begin character, we generate sections of the text (we'll call them tokens) depending on the
	// white-space parsing parameters. Each section is then appended to the line if it can fit. If not, or if an
	// endline is found (and we're processing them), then the line is ended. kthxbai!
	const char* token_begin = text.c_str() + line_begin;
	const char* string_end = text.c_str() + text.size();
	while (token_begin != string_end)
	{
		String token;
		const char* next_token_begin = token_begin;
		Character previous_codepoint = Character::Null;
		if (!line.empty())
			previous_codepoint = StringUtilities::ToCharacter(StringUtilities::SeekBackwardUTF8(&line.back(), line.data()));

		// Generate the next token and determine its pixel-length.
		bool break_line = BuildToken(token, next_token_begin, string_end, line.empty() && trim_whitespace_prefix, collapse_white_space, break_at_endline, text_transform_property, decode_escape_characters);
		int token_width = font_engine_interface->GetStringWidth(font_face_handle, token, previous_codepoint);

		// If we're breaking to fit a line box, check if the token can fit on the line before we add it.
		if (break_at_line)
		{
			const bool is_last_token = LastToken(next_token_begin, string_end, collapse_white_space, break_at_endline);
			int max_token_width = int(maximum_line_width - (is_last_token ? line_width + right_spacing_width : line_width));

			if (token_width > max_token_width)
			{
				if (word_break == WordBreak::BreakAll || (word_break == WordBreak::BreakWord && line.empty()))
				{
					// Try to break up the word
					max_token_width = int(maximum_line_width - line_width);
					const int token_max_size = int(next_token_begin - token_begin);
					bool force_loop_break_after_next = false;

					// @performance: Can be made much faster. Use string width heuristics and logarithmic search.
					for (int i = token_max_size - 1; i > 0; --i)
					{
						token.clear();
						next_token_begin = token_begin;
						const char* partial_string_end = StringUtilities::SeekBackwardUTF8(token_begin + i, token_begin);
						break_line = BuildToken(token, next_token_begin, partial_string_end, line.empty() && trim_whitespace_prefix, collapse_white_space, break_at_endline, text_transform_property, decode_escape_characters);
						token_width = font_engine_interface->GetStringWidth(font_face_handle, token, previous_codepoint);

						if (force_loop_break_after_next || token_width <= max_token_width)
						{
							break;
						}
						else if (next_token_begin == token_begin)
						{
							// This means the first character of the token doesn't fit. Let it overflow into the next line if we can.
							if (!line.empty())
								return false;

							// Not even the first character of the line fits. Go back to consume the first character even though it will overflow.
							i += 2;
							force_loop_break_after_next = true;
						}
					}

					break_line = true;
				}
				else if (!line.empty())
				{
					// Let the token overflow into the next line.
					return false;
				}
			}
		}

		// The token can fit on the end of the line, so add it onto the end and increment our width and length counters.
		line += token;
		line_length += (int)(next_token_begin - token_begin);
		line_width += token_width;

		// Break out of the loop if an endline was forced.
		if (break_line)
			return false;

		// Set the beginning of the next token.
		token_begin = next_token_begin;
	}

	return true;
}

// Clears all lines of generated text and prepares the element for generating new lines.
void ElementText::ClearLines()
{
	// Clear the rendering information.
	for (size_t i = 0; i < geometry.size(); ++i)
		geometry[i].Release(true);

	lines.clear();
	generated_decoration = Style::TextDecoration::None;
	decoration.Release(true);
}

// Adds a new line into the text element.
void ElementText::AddLine(Vector2f line_position, const String& line)
{
	FontFaceHandle font_face_handle = GetFontFaceHandle();

	if (font_face_handle == 0)
		return;

	if (font_effects_dirty)
		UpdateFontEffects();

	Vector2f baseline_position = line_position + Vector2f(0.0f, (float)GetFontEngineInterface()->GetLineHeight(font_face_handle) - GetFontEngineInterface()->GetBaseline(font_face_handle));
	lines.emplace_back(line, baseline_position);

	geometry_dirty = true;
}

// Prevents the element from dirtying its document's layout when its text is changed.
void ElementText::SuppressAutoLayout()
{
	dirty_layout_on_change = false;
}

void ElementText::OnPropertyChange(const PropertyIdSet& changed_properties)
{
	RMLUI_ZoneScoped;

	Element::OnPropertyChange(changed_properties);

	bool colour_changed = false;
	bool font_face_changed = false;
	auto& computed = GetComputedValues();

	if (changed_properties.Contains(PropertyId::Color) ||
		changed_properties.Contains(PropertyId::Opacity))
	{
		// Fetch our (potentially) new colour.
		Colourb new_colour = computed.color;
		float opacity = computed.opacity;
		new_colour.alpha = byte(opacity * float(new_colour.alpha));
		colour_changed = colour != new_colour;
		if (colour_changed)
			colour = new_colour;
	}

	if (changed_properties.Contains(PropertyId::FontFamily) ||
		changed_properties.Contains(PropertyId::FontWeight) ||
		changed_properties.Contains(PropertyId::FontStyle) ||
		changed_properties.Contains(PropertyId::FontSize))
	{
		font_face_changed = true;

		geometry.clear();
		font_effects_dirty = true;
	}

	if (changed_properties.Contains(PropertyId::FontEffect))
	{
		font_effects_dirty = true;
	}

	if (changed_properties.Contains(PropertyId::TextDecoration))
	{
		decoration_property = computed.text_decoration;
	}

	if (font_face_changed)
	{
		// We have to let our document know we need to be regenerated.
		if (dirty_layout_on_change)
			DirtyLayout();
	}
	else if (colour_changed)
	{
		// Force the geometry to be regenerated.
		geometry_dirty = true;

		// Re-colour the decoration geometry.
		Vector< Vertex >& vertices = decoration.GetVertices();
		for (size_t i = 0; i < vertices.size(); ++i)
			vertices[i].colour = colour;

		decoration.Release();
	}
}

// Returns the RML of this element
void ElementText::GetRML(String& content)
{
	content += text;
}

// Updates the configuration this element uses for its font.
bool ElementText::UpdateFontEffects()
{
	RMLUI_ZoneScoped;

	if (GetFontFaceHandle() == 0)
		return false;

	font_effects_dirty = false;

	static const FontEffectList empty_font_effects;

	// Fetch the font-effect for this text element
	const FontEffectList* font_effects = &empty_font_effects;
	if (GetComputedValues().has_font_effect)
	{
		if (const Property* p = GetProperty(PropertyId::FontEffect))
			if (FontEffectsPtr effects = p->Get<FontEffectsPtr>())
				font_effects = &effects->list;
	}

	// Request a font layer configuration to match this set of effects. If this is different from
	// our old configuration, then return true to indicate we'll need to regenerate geometry.
	FontEffectsHandle new_font_effects_handle = GetFontEngineInterface()->PrepareFontEffects(GetFontFaceHandle(), *font_effects);
	if (new_font_effects_handle != font_effects_handle)
	{
		font_effects_handle = new_font_effects_handle;
		return true;
	}

	return false;
}

// Clears and regenerates all of the text's geometry.
void ElementText::GenerateGeometry(const FontFaceHandle font_face_handle)
{
	RMLUI_ZoneScopedC(0xD2691E);

	// Release the old geometry ...
	for (size_t i = 0; i < geometry.size(); ++i)
		geometry[i].Release(true);

	// ... and generate it all again!
	for (size_t i = 0; i < lines.size(); ++i)
		GenerateGeometry(font_face_handle, lines[i]);

	decoration.Release(true);
	generated_decoration = Style::TextDecoration::None;

	geometry_dirty = false;
}

void ElementText::GenerateGeometry(const FontFaceHandle font_face_handle, Line& line)
{
	line.width = GetFontEngineInterface()->GenerateString(font_face_handle, font_effects_handle, line.text, line.position, colour, geometry);
	for (size_t i = 0; i < geometry.size(); ++i)
		geometry[i].SetHostElement(this);
}

// Generates any geometry necessary for rendering a line decoration (underline, strike-through, etc).
void ElementText::GenerateDecoration(const FontFaceHandle font_face_handle)
{
	RMLUI_ZoneScopedC(0xA52A2A);

	for(const Line& line : lines)
		GeometryUtilities::GenerateLine(font_face_handle, &decoration, line.position, line.width, decoration_property, colour);
}

static bool BuildToken(String& token, const char*& token_begin, const char* string_end, bool first_token, bool collapse_white_space, bool break_at_endline, Style::TextTransform text_transformation, bool decode_escape_characters)
{
	RMLUI_ASSERT(token_begin != string_end);

	token.reserve(string_end - token_begin + token.size());

	// Check what the first character of the token is; all we need to know is if it is white-space or not.
	bool parsing_white_space = StringUtilities::IsWhitespace(*token_begin);

	// Loop through the string from the token's beginning until we find an end to the token. This can occur in various
	// places, depending on the white-space processing;
	//  - at the end of a section of non-white-space characters,
	//  - at the end of a section of white-space characters, if we're not collapsing white-space,
	//  - at an endline token, if we're breaking on endlines.
	while (token_begin != string_end)
	{
		bool force_non_whitespace = false;
		char character = *token_begin;

		const char* escape_begin = token_begin;

		// Check for an ampersand; if we find one, we've got an HTML escaped character.
		if (decode_escape_characters && character == '&')
		{
			// Find the terminating ';'.
			while (token_begin != string_end &&
				   *token_begin != ';')
				++token_begin;

			// If we couldn't find the ';', print the token like normal text.
			if (token_begin == string_end)
			{
				token_begin = escape_begin;
			}
			// We could find a ';', parse the escape code. If the escape code is recognised, set the parsed character
			// to the appropriate one. If it is a non-breaking space, prevent it being picked up as whitespace. If it
			// is not recognised, print the token like normal text.
			else
			{
				String escape_code(escape_begin + 1, token_begin);

				if (escape_code == "lt")
					character = '<';
				else if (escape_code == "gt")
					character = '>';
				else if (escape_code == "amp")
					character = '&';
				else if (escape_code == "quot")
					character = '"';
				else if (escape_code == "nbsp")
				{
					character = ' ';
					force_non_whitespace = true;
				}
				else
					token_begin = escape_begin;
			}
		}

		// Check for an endline token; if we're breaking on endlines and we find one, then return true to indicate a
		// forced break.
		if (break_at_endline &&
			character == '\n')
		{
			token += '\n';
			token_begin++;
			return true;
		}

		// If we've transitioned from white-space characters to non-white-space characters, or vice-versa, then check
		// if should terminate the token; if we're not collapsing white-space, then yes (as sections of white-space are
		// non-breaking), otherwise only if we've transitioned from characters to white-space.
		bool white_space = !force_non_whitespace && StringUtilities::IsWhitespace(character);
		if (white_space != parsing_white_space)
		{
			if (!collapse_white_space)
			{
				// Restore pointer to the beginning of the escaped token, if we processed an escape code.
				token_begin = escape_begin;
				return false;
			}

			// We're collapsing white-space; we only tokenise words, not white-space, so we're only done tokenising
			// once we've begun parsing non-white-space and then found white-space.
			if (!parsing_white_space)
			{
				// However, if we are the last non-whitespace character in the string, and there are trailing
				// whitespace characters after this token, then we need to append a single space to the end of this
				// token.
				if (token_begin != string_end &&
					LastToken(token_begin, string_end, collapse_white_space, break_at_endline))
					token += ' ';

				return false;
			}

			// We've transitioned from white-space to non-white-space, so we append a single white-space character.
			if (!first_token)
				token += ' ';

			parsing_white_space = false;
		}

		// If the current character is white-space, we'll append a space character to the token if we're not collapsing
		// sections of white-space.
		if (white_space)
		{
			if (!collapse_white_space)
				token += ' ';
		}
		else
		{
			if (text_transformation == Style::TextTransform::Uppercase)
			{
				if (character >= 'a' && character <= 'z')
					character += ('A' - 'a');
			}
			else if (text_transformation == Style::TextTransform::Lowercase)
			{
				if (character >= 'A' && character <= 'Z')
					character -= ('A' - 'a');
			}

			token += character;
		}

		++token_begin;
	}

	return false;
}

static bool LastToken(const char* token_begin, const char* string_end, bool collapse_white_space, bool break_at_endline)
{
	bool last_token = (token_begin == string_end);
	if (collapse_white_space &&
		!last_token)
	{
		last_token = true;
		const char* character = token_begin;

		while (character != string_end)
		{
			if (!StringUtilities::IsWhitespace(*character) ||
				(break_at_endline && *character == '\n'))
			{
				last_token = false;
				break;
			}

			character++;
		}
	}

	return last_token;
}

} // namespace Rml


text:
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace NDG.Helpers.Controls
{
    public class MaskedBox : Control
    {
        private TextBox startTextBox;
        private TextBox endTextBox;
        private TextBox sampleText;
        private int currentStartTextIndex;

        #region DependencyProperties

        // Full text with of control: startText + innerText + endText.
        public static readonly DependencyProperty MaskedTextProperty = DependencyProperty.Register(
            "MaskedText",
            typeof(string),
            typeof(MaskedBox),
            new PropertyMetadata(OnMaskedTextChanged));

        // Mask for start, that will be placed before enabled text box.
        public static readonly DependencyProperty StartTextProperty = DependencyProperty.Register(
            "StartText",
            typeof(string),
            typeof(MaskedBox),
            new PropertyMetadata(OnStartTextChanged));

        // Mask for end, that will be placed after enabled text box.
        public static readonly DependencyProperty EndTextProperty = DependencyProperty.Register(
            "EndText",
            typeof(string),
            typeof(MaskedBox),
            new PropertyMetadata(OnEndTextChanged));

        // List of start text, that can be changed by tap on it.
        public static readonly DependencyProperty StartTextsProperty = DependencyProperty.Register(
            "StartTexts",
            typeof(List<string>),
            typeof(MaskedBox),
            new PropertyMetadata(OnStartTextsChanged));

        #endregion DependencyProperties

        #region Properties

        public event TextChangedEventHandler MaskedTextChanged;

        public string MaskedText
        {
            get { return (string)this.GetValue(MaskedTextProperty); }
            set { this.SetValue(MaskedTextProperty, value); }
        }

        public string StartText
        {
            get { return (string)this.GetValue(StartTextProperty); }
            set { this.SetValue(StartTextProperty, value); }
        }

        public string EndText
        {
            get { return (string)this.GetValue(EndTextProperty); }
            set { this.SetValue(EndTextProperty, value); }
        }

        public List<string> StartTexts
        {
            get { return (List<string>)this.GetValue(StartTextsProperty); }
            set { this.SetValue(StartTextsProperty, value); }
        }

        #endregion Properties

        public MaskedBox()
        {
            this.DefaultStyleKey = typeof(MaskedBox);
        }

        public new void Focus()
        {
            if (this.sampleText != null)
            {
                this.sampleText.Focus();
                this.sampleText.SelectionStart = sampleText.Text != null ? this.sampleText.Text.Length : 0;
            }
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            this.startTextBox = this.GetTemplateChild("startText") as TextBox;
            this.endTextBox = this.GetTemplateChild("endText") as TextBox;
            this.sampleText = this.GetTemplateChild("sampleText") as TextBox;

            this.startTextBox.Visibility = this.endTextBox.Visibility = System.Windows.Visibility.Collapsed;
            this.sampleText.TextChanged += this.OnSampleTextChanged;
            this.startTextBox.TextChanged += this.OnSampleTextChanged;
            this.CheckForStartText();
            this.CheckForStartTexts();
            this.CheckForEndText();
            this.CheckForMaskedText();
        }

        #region PropertyChanged

        private static void OnMaskedTextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var maskedBox = sender as MaskedBox;
            maskedBox.CheckForMaskedText();
        }

        private static void OnStartTextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var maskedBox = sender as MaskedBox;
            maskedBox.CheckForStartText();
        }

        private static void OnEndTextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var maskedBox = sender as MaskedBox;
            maskedBox.CheckForEndText();
        }

        private static void OnStartTextsChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var maskedBox = sender as MaskedBox;
            maskedBox.CheckForStartTexts();
        }

        #endregion PropertyChanged

        #region Methods

        private void CheckForMaskedText()
        {
            if (this.sampleText != null)
            {
                string currentMaskedText = this.startTextBox.Text + this.sampleText.Text + this.endTextBox.Text;
                if (this.MaskedText != currentMaskedText)
                {
                    string sampleTextString = string.Empty;
                    if (!string.IsNullOrEmpty(this.StartText))
                    {
                        sampleTextString = this.MaskedText.Replace(this.StartText, string.Empty);
                    }
                    else if (this.StartTexts != null && this.StartTexts.Count > 0)
                    {
                        foreach (var item in this.StartTexts)
                        {
                            if (this.MaskedText.StartsWith(item))
                            {
                                this.startTextBox.Text = item;
                                this.currentStartTextIndex = this.StartTexts.IndexOf(item);
                                sampleTextString = this.MaskedText.Replace(item, string.Empty);
                                break;
                            }
                        }
                    }

                    sampleTextString = sampleTextString.Replace(this.endTextBox.Text, string.Empty);
                    this.sampleText.Text = sampleTextString;
                }
            }
        }

        private void CheckForEndText()
        {
            if (this.endTextBox != null)
            {
                if (string.IsNullOrEmpty(this.EndText))
                {
                    this.endTextBox.Visibility = Visibility.Collapsed;
                }
                else
                {
                    this.endTextBox.Visibility = Visibility.Visible;
                }
            }
        }

        private void CheckForStartText()
        {
            if (this.startTextBox != null)
            {
                if (string.IsNullOrEmpty(this.StartText))
                {
                    this.startTextBox.Visibility = Visibility.Collapsed;
                }
                else
                {
                    this.startTextBox.Visibility = Visibility.Visible;
                }

                this.startTextBox.Tap -= this.OnStartTextTap;
            }
        }

        private void CheckForStartTexts()
        {
            if (this.startTextBox != null)
            {
                if (this.StartTexts != null && this.StartTexts.Count > 0)
                {
                    this.currentStartTextIndex = 0;
                    this.startTextBox.Text = this.StartTexts[this.currentStartTextIndex];
                    this.startTextBox.Visibility = Visibility.Visible;
                    this.startTextBox.Tap += this.OnStartTextTap;
                }
                else if (string.IsNullOrEmpty(this.StartText))
                {
                    this.startTextBox.Visibility = Visibility.Collapsed;
                }
            }
        }

        #endregion Methods

        private void OnStartTextTap(object sender, GestureEventArgs e)
        {
            this.currentStartTextIndex++;
            if (this.currentStartTextIndex == this.StartTexts.Count)
            {
                this.currentStartTextIndex = 0;
            }

            this.startTextBox.Text = this.StartTexts[this.currentStartTextIndex];
            this.sampleText.Focus();
            this.sampleText.SelectionStart = !string.IsNullOrEmpty(sampleText.Text) ? this.sampleText.Text.Length : 0;
        }

        private void OnSampleTextChanged(object sender, TextChangedEventArgs e)
        {
            if (!string.IsNullOrEmpty(this.sampleText.Text) && !string.IsNullOrEmpty(this.sampleText.Text.Trim()))
            {
                this.MaskedText = this.startTextBox.Text + this.sampleText.Text + this.endTextBox.Text;
                if (this.MaskedTextChanged != null)
                {
                    this.MaskedTextChanged(this, e);
                }
            }
        }
    }
}


text:
package com.nileshk;

import com.stripe.model.Charge;

import java.io.Serializable;

public class ChargeResult implements Serializable {

	private static final long serialVersionUID = 1397303362248480911L;

	private Long amount;
	private String email;
	private boolean error = false;
	private String errorMessage;

	public ChargeResult() {
	}

	public ChargeResult(Charge charge) {
		if (charge != null) {
			amount = charge.getAmount();
			email = charge.getDescription();
		}
	}

	public static ChargeResult error(String errorMessage) {
		ChargeResult result = new ChargeResult();
		result.setError(true);
		result.setErrorMessage(errorMessage);
		return result;
	}

	public Long getAmount() {
		return amount;
	}

	public void setAmount(Long amount) {
		this.amount = amount;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public boolean isError() {
		return error;
	}

	public void setError(boolean error) {
		this.error = error;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}
}


text:
<?php
/*
+--------------------------------------------------------------------------
|   WeCenter [#RELEASE_VERSION#]
|   ========================================
|   by WeCenter Software
|   © 2011 - 2014 WeCenter. All Rights Reserved
|   http://www.wecenter.com
|   ========================================
|   Support: WeCenter@qq.com
|
+---------------------------------------------------------------------------
*/

if (! defined('IN_ANWSION'))
{
	die();
}

class question extends AWS_ADMIN_CONTROLLER
{
	public function setup()
	{
		TPL::assign('menu_list', $this->model('admin')->fetch_menu_list(301));
	}

	public function question_list_action()
	{
		if ($this->is_post())
		{
			foreach ($_POST as $key => $val)
			{
				if ($key == 'start_date' OR $key == 'end_date')
				{
					$val = base64_encode($val);
				}

				if ($key == 'keyword' OR $key == 'user_name')
				{
					$val = rawurlencode($val);
				}

				$param[] = $key . '-' . $val;
			}

			H::ajax_json_output(AWS_APP::RSM(array(
				'url' => get_js_url('/admin/question/question_list/' . implode('__', $param))
			), 1, null));
		}

		$where = array();

		if ($_GET['keyword'])
		{
			$where[] = "(MATCH(question_content_fulltext) AGAINST('" . $this->model('question')->quote($this->model('search_fulltext')->encode_search_code($this->model('system')->analysis_keyword($_GET['keyword']))) . "' IN BOOLEAN MODE))";
		}

		if ($_GET['category_id'])
		{
			if ($category_ids = $this->model('system')->get_category_with_child_ids('question', $_GET['category_id']))
			{
				$where[] = 'category_id IN (' . implode(',', $category_ids) . ')';
			}
			else
			{
				$where[] = 'category_id = ' . intval($category_id);
			}
		}

		if (base64_decode($_GET['start_date']))
		{
			$where[] = 'add_time >= ' . strtotime(base64_decode($_GET['start_date']));
		}

		if (base64_decode($_GET['end_date']))
		{
			$where[] = 'add_time <= ' . strtotime('+1 day', strtotime(base64_decode($_GET['end_date'])));
		}

		if ($_GET['user_name'])
		{
			$user_info = $this->model('account')->get_user_info_by_username($_GET['user_name']);

			$where[] = 'published_uid = ' . intval($user_info['uid']);
		}

		if ($_GET['answer_count_min'])
		{
			$where[] = 'answer_count >= ' . intval($_GET['answer_count_min']);
		}

		if ($_GET['answer_count_max'])
		{
			$where[] = 'answer_count <= ' . intval($_GET['answer_count_max']);
		}

		if ($_GET['best_answer'])
		{
			$where[] = 'best_answer > 0';
		}

		if ($question_list = $this->model('question')->fetch_page('question', implode(' AND ', $where), 'question_id DESC', $_GET['page'], $this->per_page))
		{
			$total_rows = $this->model('question')->found_rows();

			foreach ($question_list AS $key => $val)
			{
				$question_list_uids[$val['published_uid']] = $val['published_uid'];
			}

			if ($question_list_uids)
			{
				$question_list_user_infos = $this->model('account')->get_user_info_by_uids($question_list_uids);
			}

			foreach ($question_list AS $key => $val)
			{
				$question_list[$key]['user_info'] = $question_list_user_infos[$val['published_uid']];
			}
		}

		$url_param = array();

		foreach($_GET as $key => $val)
		{
			if (!in_array($key, array('app', 'c', 'act', 'page')))
			{
				$url_param[] = $key . '-' . $val;
			}
		}

		TPL::assign('pagination', AWS_APP::pagination()->initialize(array(
			'base_url' => get_js_url('/admin/question/question_list/') . implode('__', $url_param),
			'total_rows' => $total_rows,
			'per_page' => $this->per_page
		))->create_links());

		$this->crumb(AWS_APP::lang()->_t('问题管理'), 'admin/question/question_list/');

		TPL::assign('question_count', $total_rows);
		TPL::assign('category_list', $this->model('system')->build_category_html('question', 0, 0, null, true));
		TPL::assign('keyword', $_GET['keyword']);
		TPL::assign('list', $question_list);

		TPL::output('admin/question/question_list');
	}

	public function report_list_action()
	{
		if ($report_list = $this->model('question')->get_report_list('status = ' . intval($_GET['status']), $_GET['page'], $this->per_page))
		{
			$report_total = $this->model('question')->found_rows();

			$userinfos = $this->model('account')->get_user_info_by_uids(fetch_array_value($report_list, 'uid'));

			foreach ($report_list as $key => $val)
			{
				$report_list[$key]['user'] = $userinfos[$val['uid']];
			}
		}

		$this->crumb(AWS_APP::lang()->_t('用户举报'), 'admin/question/report_list/');

		TPL::assign('list', $report_list);
		TPL::assign('menu_list', $this->model('admin')->fetch_menu_list(306));

		TPL::assign('pagination', AWS_APP::pagination()->initialize(array(
			'base_url' => get_js_url('/admin/question/report_list/status-' . intval($_GET['status'])),
			'total_rows' => $report_total,
			'per_page' => $this->per_page
		))->create_links());

		TPL::output('admin/question/report_list');
	}
}


text:
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Scanner;

public class placeOrder {
	public placeOrder(String username, String password) throws ClassNotFoundException, SQLException{
		// Setup scanner for inputs
		Scanner input = new Scanner(System.in);
		String choose = "";
		commandLine.startSession();
		String sql = "INSERT INTO `customers`.`transaction` (`date`, `totalPrice`, `tid`, `username`, `methodOfPayment`) VALUES (NOW(), '0', NULL, '"+username+"', 'nothing');";
		commandLine.executeSession(sql, 2);
		sql = "select tid from transaction where username = '"+username+"';";
		ArrayList<String> gtid = commandLine.executeSession(sql, 1);
		String tid = gtid.get(gtid.size()-1);
		commandLine.endSession();
		while (! choose.equals("6")){
			String fillers = "================================";
			System.out.println("1, Add Pizza");
			System.out.println("2, Add Side dishes and drinks");
			System.out.println("3, View Cart");
			System.out.println("4, Proceed to checkout");
			System.out.println("5, Request Standing Order");
			System.out.println("6, Cancel");
			choose = input.nextLine();
	        switch (choose) {
	            case "1":  {
	            	tid = pizza.pizzaa(username);
	            }
	                     break;
	            case "2":  {
	            	tid = sideOrder.sideOrderr(username);
	            }
	                     break;
	            case "3":  new viewCart(tid);
	                     break;
	            case "4":{
	            	new payment(tid,"0",username, password);
	            }
	                     break;
	            case "5":{
	            	System.out.println("1, daily");
	            	System.out.println("2, weekely");
	            	choose = input.nextLine();
	            	System.out.println(choose);
	            	if (choose.equals("1")){
	            		sql = "update transaction set standingOrder = 1 where tid = '"+tid+"';";
	            	}
	            	if (choose.equals("2")){
	            		sql = "update transaction set standingOrder = 2 where tid = '"+tid+"';";
	            	}
	            	commandLine.startSession();
	            	commandLine.executeSession(sql, 2);
	            	commandLine.endSession();

	            }
	            break;
	            case "6":  {
	            	sql = "DELETE from `order` where tid = '"+tid+"'";
	            	commandLine.startSession();
	            	commandLine.executeSession(sql, 2);
	            	sql = "DELETE from `pizzaorder` where tid = '"+tid+"'";
	            	commandLine.executeSession(sql, 2);
	            	sql = "DELETE from `toppingorder` where tid = '"+tid+"'";
	            	commandLine.executeSession(sql, 2);
	            	sql = "DELETE from `transaction` where tid = '"+tid+"'";
	            	commandLine.executeSession(sql, 2);
	            	return;
	            }
	        }
		}

	}
}


text:
package com.fruit.core.web.utils;

/**
 * 发送邮件需要使用的基本信息
 */
import java.util.Properties;

public class MailSenderInfo {

	public MailSenderInfo(String fromAddress, String toAddress, String userName, String password, String subject,
			String content, String path) {
		super();
		this.fromAddress = fromAddress;
		this.toAddress = toAddress;
		this.userName = userName;
		this.password = password;
		this.subject = subject;
		this.content = content;
		this.path = path;
	}

	// 发送邮件的服务器的IP和端口
    private String mailServerHost;
    private String mailServerPort = "25";
    // 邮件发送者的地址
    private String fromAddress;
    // 邮件接收者的地址
    private String toAddress;
    // 登陆邮件发送服务器的用户名和密码
    private String userName;
    private String password;
    // 是否需要身份验证
    private boolean validate = false;
    // 邮件主题
    private String subject;
    // 邮件的文本内容
    private String content;
    // 邮件附件的文件名
    private String[] attachFileNames;
    private String path;

    public String getPath() {
		return path;
	}
    public void setPath(String path) {
		this.path = path;
	}

    /**
     * 获得邮件会话属性
     */
    public Properties getProperties() {
        Properties p = new Properties();
        p.put("mail.smtp.host", this.mailServerHost);
        p.put("mail.smtp.port", this.mailServerPort);
        p.put("mail.smtp.auth", validate ? "true" : "false");
        return p;
    }

    public String getMailServerHost() {
        return mailServerHost;
    }

    public void setMailServerHost(String mailServerHost) {
        this.mailServerHost = mailServerHost;
    }

    public String getMailServerPort() {
        return mailServerPort;
    }

    public void setMailServerPort(String mailServerPort) {
        this.mailServerPort = mailServerPort;
    }

    public boolean isValidate() {
        return validate;
    }

    public void setValidate(boolean validate) {
        this.validate = validate;
    }

    public String[] getAttachFileNames() {
        return attachFileNames;
    }

    public void setAttachFileNames(String[] fileNames) {
        this.attachFileNames = fileNames;
    }

    public String getFromAddress() {
        return fromAddress;
    }

    public void setFromAddress(String fromAddress) {
        this.fromAddress = fromAddress;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getToAddress() {
        return toAddress;
    }

    public void setToAddress(String toAddress) {
        this.toAddress = toAddress;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String textContent) {
        this.content = textContent;
    }
}


text:
'use strict';

const BaseHandler = require('./BaseHandler');
const File = require('../models/File');
const Uid = require('../models/Uid');
const RequestValidator = require('../validators/RequestValidator');
const { EVENTS, ERRORS } = require('../constants');
const debug = require('debug');
const log = debug('tus-node-server:handlers:post');
class PostHandler extends BaseHandler {

    constructor(store, options) {
        if (options.namingFunction && typeof options.namingFunction !== 'function') {
            throw new Error('\'namingFunction\' must be a function');
        }

        if (!options.namingFunction) {
            options.namingFunction = Uid.rand;
        }

        super(store, options);
    }

    /**
     * Create a file in the DataStore.
     *
     * @param  {object} req http.incomingMessage
     * @param  {object} res http.ServerResponse
     * @return {function}
     */
    async send(req, res) {
        if ('upload-concat' in req.headers && !this.store.hasExtension('concatentation')) {
            throw ERRORS.UNSUPPORTED_CONCATENATION_EXTENSION;
        }

        const upload_length = req.headers['upload-length'];
        const upload_defer_length = req.headers['upload-defer-length'];
        const upload_metadata = req.headers['upload-metadata'];

        if (upload_defer_length !== undefined) {
            // Throw error if extension is not supported
            if (!this.store.hasExtension('creation-defer-length')) {
                throw ERRORS.UNSUPPORTED_CREATION_DEFER_LENGTH_EXTENSION;
            }
        }

        if ((upload_length === undefined) === (upload_defer_length === undefined)) {
            throw ERRORS.INVALID_LENGTH;
        }

        let file_id;

        try {
            file_id = this.options.namingFunction(req);
        }
        catch (err) {
            log('create: check your `namingFunction`. Error', err);
            throw ERRORS.FILE_WRITE_ERROR;
        }

        const file = new File(file_id, upload_length, upload_defer_length, upload_metadata);

        const obj = await this.store.create(file);
        this.emit(EVENTS.EVENT_FILE_CREATED, { file: obj });

        const url = this.generateUrl(req, file.id);
        this.emit(EVENTS.EVENT_ENDPOINT_CREATED, { url });

        const optional_headers = {};

        // The request MIGHT include a Content-Type header when using creation-with-upload extension
        if (!RequestValidator.isInvalidHeader('content-type', req.headers['content-type'])) {
            const new_offset = await this.store.write(req, file.id, 0);
            optional_headers['Upload-Offset'] = new_offset;

            if (new_offset === parseInt(upload_length, 10)) {
                this.emit(EVENTS.EVENT_UPLOAD_COMPLETE, { file: new File(file_id, file.upload_length, file.upload_defer_length, file.upload_metadata) });
            }
        }

        return this.write(res, 201, { Location: url, ...optional_headers });
    }
}

module.exports = PostHandler;


text:
<?php

namespace Tekkl\Bundle\MediaBundle\DataFixtures\ORM;

use Tekkl\Bundle\AppBundle\Tests\DataFixtures\TestEnvDataFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Tekkl\Bundle\MediaBundle\Entity\Directory;

class TestDirectoryData extends TestEnvDataFixture {
	public function doLoad(ObjectManager $manager){
		$this->createDirectories($manager);
	}
	protected function getEnvironments(){
		return array('dev', 'test');
	}
	private function createDirectories(ObjectManager $manager){
		$dirRepo = $manager->getRepository(Directory::class);
		$root = $dirRepo->createRootNode();
	}
}


text:
<?php

namespace SphinxSearch\Tool\Source\Writer;

use SphinxSearch\Tool\Source\Exception\NotValidDocumentException;
use SphinxSearch\Tool\Source\Writer\AttributesAwareTrait;
use SphinxSearch\Tool\Source\Writer\FieldsAwareTrait;

/**
 * Class XML2
 * Generate an XML data source suitable for xmlpipe2 driver
 */
class XML2 extends \XMLWriter implements SourceInterface
{
    use FieldsAwareTrait;
    use AttributesAwareTrait;

    protected $options;
    protected $defaultOptions = ['indent' => false, 'indent_string' => "\t"];

    /**
     * Constructor
     * @param array $options
     */
    public function __construct(array $options = [])
    {
        // Store the xml tree in memory
        $this->openMemory();
        // Set options
        $this->setOptions($options);
    }

    /**
     * @return array
     */
    public function getOptions()
    {
        return $this->options;
    }

    /**
     * @param array $options
     * @return $this
     */
    public function setOptions(array $options)
    {
        $this->options = array_merge($this->defaultOptions, $options);
        $this->setIndent((bool)$this->options['indent']);
        $this->setIndentString((string)$this->options['indent_string']);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function beginOutput()
    {
        $this->startDocument('1.0', 'UTF-8');
        $this->startElement('sphinx:docset');
        $this->startElement('sphinx:schema');
        // Add fields to the schema
        foreach ($this->fields as $fields) {
            $this->startElement('sphinx:field');
            foreach ($fields as $key => $value) {
                $this->writeAttribute($key, $value);
            }
            $this->endElement();
        }
        // Add attributes to the schema
        foreach ($this->attributes as $attributes) {
            $this->startElement('sphinx:attr');
            foreach ($attributes as $key => $value) {
                $this->writeAttribute($key, $value);
            }
            $this->endElement();
        }
        // End sphinx:schema
        $this->endElement();
        $return = $this->outputMemory();
        $this->flush();
        return $return;
    }

    /**
     * {@inheritdoc}
     */
    public function addDocument(array $doc)
    {
        $this->startElement('sphinx:document');
        if (!isset($doc['id'])) {
            throw new NotValidDocumentException('Document array must have an element with "id" key');
        }
        $this->writeAttribute('id', $doc['id']);
        foreach ($doc as $key => $value) {
            // Skip the id key since that is an element attribute
            if ($key == 'id') {
                continue;
            }
            $this->startElement($key);
            $this->text($value);
            $this->endElement();
        }
        $this->endElement();
        $return = $this->outputMemory();
        $this->flush();
        return $return;
    }

    /**
     * {@inheritdoc}
     */
    public function endOutput()
    {
        // End sphinx:docset
        $this->endElement();
        $return = $this->outputMemory();
        $this->flush();
        return $return;
    }
}


text:
namespace spvtools {
namespace fuzz {

FuzzerPassExpandVectorReductions::FuzzerPassExpandVectorReductions(
    opt::IRContext* ir_context, TransformationContext* transformation_context,
    FuzzerContext* fuzzer_context,
    protobufs::TransformationSequence* transformations,
    bool ignore_inapplicable_transformations)
    : FuzzerPass(ir_context, transformation_context, fuzzer_context,
                 transformations, ignore_inapplicable_transformations) {}

void FuzzerPassExpandVectorReductions::Apply() {
  for (auto& function : *GetIRContext()->module()) {
    for (auto& block : function) {
      for (auto& instruction : block) {
        // Randomly decides whether the transformation will be applied.
        if (!GetFuzzerContext()->ChoosePercentage(
                GetFuzzerContext()->GetChanceOfExpandingVectorReduction())) {
          continue;
        }

        // |instruction| must be OpAny or OpAll.
        if (instruction.opcode() != spv::Op::OpAny &&
            instruction.opcode() != spv::Op::OpAll) {
          continue;
        }

        // It must be able to make a synonym of |instruction|.
        if (!fuzzerutil::CanMakeSynonymOf(
                GetIRContext(), *GetTransformationContext(), instruction)) {
          continue;
        }

        // Applies the expand vector reduction transformation.
        ApplyTransformation(TransformationExpandVectorReduction(
            instruction.result_id(),
            GetFuzzerContext()->GetFreshIds(
                TransformationExpandVectorReduction::GetRequiredFreshIdCount(
                    GetIRContext(), &instruction))));
      }
    }
  }
}

}  // namespace fuzz
}  // namespace spvtools


text:
from setuptools import setup
from sys import argv, version_info as python_version
from pathlib import Path

if python_version < (3, 6):
	raise SystemExit("Python 3.6 or later is required.")

here = Path(__file__).resolve().parent
version = description = url = author = None  # Populated by the next line.
exec((here / "web" / "dispatch" / "object" / "release.py").read_text('utf-8'))

tests_require = [
		'pytest',  # test collector and extensible runner
		'pytest-cov',  # coverage reporting
		'pytest-flakes',  # syntax validation
		'pytest-isort',  # import ordering
	]

setup(
	name = "web.dispatch.object",
	version = version,

	description = description,
	long_description = (here / 'README.rst').read_text('utf-8'),
	url = url,
	download_url = 'https://pypi.org/project/web.dispatch.object/releases',

	author = author.name,
	author_email = author.email,

	license = 'MIT',
	keywords = [
			'marrow',
			'dispatch',
			'web.dispatch',
			'object dispatch',
			'endpoint discovery',
			'WebCore'
		],
	classifiers = [
			"Development Status :: 5 - Production/Stable",
			"Environment :: Console",
			"Environment :: Web Environment",
			"Intended Audience :: Developers",
			"License :: OSI Approved :: MIT License",
			"Operating System :: OS Independent",
			"Programming Language :: Python",
			"Programming Language :: Python :: 3",
			"Programming Language :: Python :: 3.6",
			"Programming Language :: Python :: 3.7",
			"Programming Language :: Python :: 3.8",
			"Programming Language :: Python :: Implementation :: CPython",
			"Programming Language :: Python :: Implementation :: PyPy",
			"Topic :: Software Development :: Libraries :: Python Modules",
		],

	project_urls = {
			"Repository": "https://github.com/marrow/web.dispatch.object/",
			"Documentation": "https://github.com/marrow/web.dispatch.object/#readme",
			"Issue Tracker": "https://github.com/marrow/web.dispatch.object/issues",
			"Funding": "https://www.patreon.com/GothAlice",
		},

	packages = ('web.dispatch.object', ),
	include_package_data = True,
	package_data = {'': ['README.rst', 'LICENSE.txt']},
	zip_safe = False,

	python_requires = '~=3.6',

	setup_requires = [
			'pytest-runner',
		] if {'pytest', 'test', 'ptr'}.intersection(argv) else [],

	install_requires = [
			'web.dispatch~=3.0.1',  # Core dispatch helpers.
		],

	extras_require = dict(
			development = tests_require + ['pre-commit'],  # Development-time dependencies.
		),

	tests_require = tests_require,

	# Plugin Registration

	entry_points = {
			'web.dispatch': [
					'object = web.dispatch.object:ObjectDispatch',
				],
		},
)


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>web2py.gluon.html.CODE</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

web2py Web Framework

        Package web2py ::
        Package gluon ::
        Module html ::
        Class CODE

[hide private]

[frames] | no frames]

Class CODE
source code

  object --+
           |
XmlComponent --+
               |
             DIV --+
                   |
                  CODE

displays code in HTML with syntax highlighting.

  :param attributes: optional attributes:

      language: indicates the language, otherwise PYTHON is assumed

      link: can provide a link

      styles: for styles

  Example:

   {{=CODE("print 'hello world'", language='python', link=None,
       counter=1, styles={}, highlight_line=None)}}

supported languages are "python", "html_plain",
  "c", "cpp", "web2py", "html". The
  "html" language interprets {{ and }} tags as "web2py"
  code, "html_plain" doesn't.

if a link='/examples/global/vars/' is provided web2py keywords are
  linked to the online docs.

  the counter is used for line numbering, counter can be None or a
  prompt string.

        Instance Methods
        [hide private]

          xml(self)

      generates the xml for this component.

            source code

Inherited from DIV:
      __delitem__,
      __getitem__,
      __init__,
      __len__,
      __nonzero__,
      __setitem__,
      __str__,
      append,
      element,
      elements,
      flatten,
      insert,
      sibling,
      siblings,
      update

Inherited from DIV (private):
      _fixup,
      _postprocessing,
      _setnode,
      _traverse,
      _validate,
      _wrap_components,
      _xml

Inherited from XmlComponent:
      __add__,
      __mul__,
      add_class,
      remove_class

Inherited from object:
      __delattr__,
      __getattribute__,
      __hash__,
      __new__,
      __reduce__,
      __reduce_ex__,
      __repr__,
      __setattr__

        Class Variables
        [hide private]

Inherited from DIV:
      regex_attr,
      regex_class,
      regex_id,
      regex_tag,
      tag

        Properties
        [hide private]

Inherited from object:
      __class__

        Method Details
        [hide private]

xml(self)

  	source code

  generates the xml for this component.

Overrides:
      DIV.xml

(inherited documentation)

         Home

         Trees

         Indices

         Help

web2py Web Framework

    Generated by Epydoc 3.0beta1 on Sun Oct 21 16:56:51 2012

      http://epydoc.sourceforge.net


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Article = mongoose.model('Article'),
	_ = require('lodash');

/**
 * Create a article
 */
exports.create = function(req, res) {
	var article = new Article(req.body);
	article.user = req.user;

	article.save(function(err) {
		if (err) {
			return res.send('users/signup', {
				errors: err.errors,
				article: article
			});
		} else {
			res.jsonp(article);
		}
	});
};

/**
 * Show the current article
 */
exports.read = function(req, res) {
	res.jsonp(req.article);
};

/**
 * Update a article
 */
exports.update = function(req, res) {
	var article = req.article;

	article = _.extend(article, req.body);

	article.save(function(err) {
		if (err) {
			res.render('error', {
				status: 500
			});
		} else {
			res.jsonp(article);
		}
	});
};

/**
 * Delete an article
 */
exports.delete = function(req, res) {
	var article = req.article;

	article.remove(function(err) {
		if (err) {
			res.render('error', {
				status: 500
			});
		} else {
			res.jsonp(article);
		}
	});
};

/**
 * List of Articles
 */
exports.list = function(req, res) {
	Article.find().sort('-created').populate('user', 'displayName').exec(function(err, articles) {
		if (err) {
			res.render('error', {
				status: 500
			});
		} else {
			res.jsonp(articles);
		}
	});
};

/**
 * Article middleware
 */
exports.articleByID = function(req, res, next, id) {
	Article.load(id, function(err, article) {
		if (err) return next(err);
		if (!article) return next(new Error('Failed to load article ' + id));
		req.article = article;
		next();
	});
};

/**
 * Article authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.article.user.id !== req.user.id) {
		return res.send(403, 'User is not authorized');
	}
	next();
};


text:
/*
 * wdbind.c - code to allow the watchdog to bind to server ports
 *
 *
 */

#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "wdbind.h"
#include "wdlog.h"

int
watchdog_bind(server_socket_t *sock, int num_sock)
{
    int sfd;                    /* next contiguous file descriptor */
    int tfd;                    /* socket temporary file descriptor */
    int ns;                     /* number of sockets bound so far */
    int rv;                     /* result value */
    struct sockaddr saddr;      /* socket address for bind */
    struct sockaddr_in *sa;     /* pointer to TCP/IP socket address */
    char *ipstr;                /* pointer to IP address string */
    int port;                   /* TCP port number */
    int one = 1;                    /* optval for setsockopt */

    sa = (struct sockaddr_in *)&saddr;

    /* Loop on the number of sockets to be bound */
    for (ns = 0, sfd = DEFAULT_WDOG_BASE_FD;
         ns < num_sock; ++sfd) {

        ipstr = sock[ns].ip;
        port = sock[ns].port;

        tfd = socket(AF_INET, SOCK_STREAM, 0);
        if (tfd < 0) {
            /* Failed to get socket */
            rv = -1;
            break;
        }

        /* Dup the socket on the next contiguous file descriptor */
        if (tfd != sfd) {

            rv = dup2(tfd, sfd);
            close(tfd);

            if (rv < 0) {
                /* Failed to dup socket to contiguous fd */
                rv = -2;
                break;
            }
        }

        /* Count number of open contiguous sockets */
        ++ns;

	if ( setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR,
	    (const void *)&one, sizeof(one) ) < 0) {
            rv = -4;
            break;
	}

        /* Bind socket address */
        memset((void *)sa, 0, sizeof(struct sockaddr));
        sa->sin_family = AF_INET;
        sa->sin_addr.s_addr = (ipstr ? inet_addr(ipstr) : htonl(INADDR_ANY));
        sa->sin_port = htons(port);

        rv = bind(sfd, &saddr, sizeof(struct sockaddr_in));
        if (rv < 0) {
            /* Failed to bind socket to desired address */
            rv = -3;
            break;
        }
    }

    if (rv < 0) {
        char *oserr = strerror(errno);

        if (ipstr) {
            if (guse_stderr) {
                fprintf(stderr,
                "startup failure: could not bind to IP address %s port %d (%s)\n",
                     ipstr, port, oserr);
            }
	    watchdog_log(LOG_ERR,
			 "startup failure: could not bind to IP address %s port %d (%m)",
			 ipstr, port);

        }
        else {
            if (guse_stderr) {
                fprintf(stderr,
                "startup failure: could not bind to port %d (%s)\n",
                     port, oserr);
            }
            watchdog_log(LOG_ERR,
			 "startup failure: could not bind to port %d (%m)",
			 port);
        }

        /* Close any open sockets on error */
        watchdog_unbind(ns, DEFAULT_WDOG_BASE_FD);
    }

    return rv;
}

void
watchdog_unbind(int num_sock, int base_fd)
{
    int i;

    for (i = 0; i < num_sock; ++i, ++base_fd) {
        close(base_fd);
    }
}


text:
using namespace IECoreMaya;
using namespace boost::python;

class CustomTagReader
{
	public :
		CustomTagReader( object hasFn, object readFn ) : m_has( hasFn ), m_read( readFn )
		{
		}

		bool operator() ( const MDagPath &dagPath, const IECore::SceneInterface::Name &tag, int filter )
		{
			MString p = dagPath.fullPathName();
			IECorePython::ScopedGILLock gilLock;
			try
			{
				return m_has( p.asChar(), tag, filter );
			}
			catch ( error_already_set )
			{
				PyErr_Print();
				throw IECore::Exception( std::string( "Python exception while checking IECoreMaya::LiveScene tag " + tag.string() ) );
			}
		}

		void operator() ( const MDagPath &dagPath, IECore::SceneInterface::NameList &tags, int filter )
		{
			MString p = dagPath.fullPathName();
			IECorePython::ScopedGILLock gilLock;
			object o;
			try
			{
				o = m_read( p.asChar(), filter );
			}
			catch ( error_already_set )
			{
				PyErr_Print();
				throw IECore::Exception( std::string( "Python exception while evaluating IECoreMaya::LiveScene tags" ) );
			}
			extract<list> l( o );
			if ( !l.check() )
			{
				throw IECore::InvalidArgumentException( std::string( "Invalid value! Expecting a list of strings." ) );
			}

			IECorePython::listToSceneInterfaceNameList( l(), tags );
		}

		object m_has;
		object m_read;
};

void registerCustomTags( object hasFn, object readFn )
{
	CustomTagReader reader( hasFn, readFn );
	LiveScene::registerCustomTags( reader, reader );
}

class CustomAttributeReader
{
	public :
		CustomAttributeReader( object namesFn, object readFn ) : m_names( namesFn ), m_read( readFn )
		{
		}

		IECore::ConstObjectPtr operator() ( const MDagPath &dagPath, const IECore::SceneInterface::Name &attr )
		{
			MString p = dagPath.fullPathName();
			IECorePython::ScopedGILLock gilLock;
			try
			{
				return extract<IECore::ConstObjectPtr>(m_read( p.asChar(), attr ));
			}
			catch ( error_already_set )
			{
				PyErr_Print();
				throw IECore::Exception( std::string( "Python exception while evaluating IECoreMaya::LiveScene attribute " + attr.string() ) );
			}
		}

		void operator() ( const MDagPath &dagPath, IECore::SceneInterface::NameList &attributes )
		{
			MString p = dagPath.fullPathName();
			IECorePython::ScopedGILLock gilLock;
			object o;
			try
			{
				o = m_names( p.asChar() );
			}
			catch ( error_already_set )
			{
				PyErr_Print();
				throw IECore::Exception( std::string( "Python exception while evaluating attribute names for IECoreMaya::LiveScene." ) );
			}

			extract<list> l( o );
			if ( !l.check() )
			{
				throw IECore::InvalidArgumentException( std::string( "Invalid value! Expecting a list of strings." ) );
			}

			IECorePython::listToSceneInterfaceNameList( l(), attributes );
		}

		object m_names;
		object m_read;
};

class CustomAttributeReaderMightHave
{
	public :
		CustomAttributeReaderMightHave( object mightHaveFn ) : m_mightHave( mightHaveFn )
		{
		}

		bool operator() ( const MDagPath &dagPath, const IECore::SceneInterface::Name &attr )
		{
			// Use with care when registering a Python function.
			// MDagPath::fullPathName() is a slow API. We allow registering the "might have" callback from Python
			// for compatibility with IECoreMaya C++ API but registering a Python "might have" function may spoil the efficiency.
			MString p = dagPath.fullPathName();
			IECorePython::ScopedGILLock gilLock;
			try
			{
				return m_mightHave( p.asChar(), attr );
			}
			catch ( error_already_set )
			{
				PyErr_Print();
				throw IECore::Exception( std::string( "Python exception while evaluating IECoreMaya::LiveScene attribute  " + attr.string() ) );
			}
		}

		object m_mightHave;
};

void registerCustomAttributes( object namesFn, object readFn, object mightHaveFn )
{
	CustomAttributeReader reader( namesFn, readFn );

	if ( mightHaveFn == object() )
	{
		LiveScene::registerCustomAttributes( reader, reader );
	}
	else
	{
		CustomAttributeReaderMightHave readerm( mightHaveFn );
		LiveScene::registerCustomAttributes( reader, reader, readerm );
	}
}

void IECoreMaya::bindLiveScene()
{
	IECorePython::RunTimeTypedClass<LiveScene>()
		.def( init<>() )
		.def( "registerCustomTags", registerCustomTags, ( arg_( "hasFn" ), arg_( "readFn" ) ) ).staticmethod( "registerCustomTags" )
		.def( "registerCustomAttributes", registerCustomAttributes, (  arg_( "namesFn" ), arg_( "readFn" ), arg_( "mightHaveFn" ) = object() ) ).staticmethod( "registerCustomAttributes" )
	;
}


text:
FROM ruby:2.3-slim

RUN apt-get update && \
	apt-get install -yq \
	build-essential && \
	mkdir -p /usr/src/app

WORKDIR /usr/src/app
COPY Gemfile .
COPY Gemfile.lock .
RUN bundle install
ENTRYPOINT ["/usr/local/bin/bundle", "exec", "jekyll"]


text:
<!DOCTYPE html>

 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
 <title>MarkerWithLabel Mouse Events</title>

Try interacting with the marker (mouseover, mouseout, click, double-click, mouse down, mouse up, drag) to see a log of events that are fired. Events are fired whether you are interacting with the marker portion or the label portion.


text:
comments: true
date: 2010-05-05 19:16:12
layout: post
slug: finding-great-new-sites-to-follow
title: Finding Great New Sites to Follow
wordpress_id: 356
categories:
- tech
tags:
- google
- hack
- reader
---

I discovered today, much to my delight, that in [Google Reader](http://reader.google.com), when I'm reading a news feed of a blog I like, that when I click "Feed settings", then "More like this" and voila, you get a list of similar news feeds.

It's a great way to discover new sites! Very cool.

(It's also interesting to see which feeds are on the recommended list from multiple source feeds).


text:
from .utils import validator

@validator
def ipv4(value):
    """
    Return whether a given value is a valid IP version 4 address.

    This validator is based on `WTForms IPAddress validator`_

    .. _WTForms IPAddress validator:
       https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py

    Examples::

        >>> ipv4('123.0.0.7')
        True

        >>> ipv4('900.80.70.11')
        ValidationFailure(func=ipv4, args={'value': '900.80.70.11'})

    .. versionadded:: 0.2

    :param value: IP address string to validate
    """
    groups = value.split(".")
    if (
        len(groups) != 4
        or any(not x.isdigit() for x in groups)
        or any(len(x) > 3 for x in groups)
    ):
        return False
    return all(0 <= int(part) < 256 for part in groups)

@validator
def ipv4_cidr(value):
    """
    Return whether a given value is a valid CIDR-notated IP version 4
    address range.

    This validator is based on RFC4632 3.1.

    Examples::

        >>> ipv4_cidr('1.1.1.1/8')
        True

        >>> ipv4_cidr('1.1.1.1')
        ValidationFailure(func=ipv4_cidr, args={'value': '1.1.1.1'})
    """
    try:
        prefix, suffix = value.split('/', 2)
    except ValueError:
        return False
    if not ipv4(prefix) or not suffix.isdigit():
        return False
    return 0 <= int(suffix) <= 32

@validator
def ipv6(value):
    """
    Return whether a given value is a valid IP version 6 address
    (including IPv4-mapped IPv6 addresses).

    This validator is based on `WTForms IPAddress validator`_.

    .. _WTForms IPAddress validator:
       https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py

    Examples::

        >>> ipv6('abcd:ef::42:1')
        True

        >>> ipv6('::ffff:192.0.2.128')
        True

        >>> ipv6('::192.0.2.128')
        True

        >>> ipv6('abc.0.0.1')
        ValidationFailure(func=ipv6, args={'value': 'abc.0.0.1'})

    .. versionadded:: 0.2

    :param value: IP address string to validate
    """
    ipv6_groups = value.split(':')
    if len(ipv6_groups) == 1:
        return False
    ipv4_groups = ipv6_groups[-1].split('.')

    if len(ipv4_groups) > 1:
        if not ipv4(ipv6_groups[-1]):
            return False
        ipv6_groups = ipv6_groups[:-1]
    else:
        ipv4_groups = []

    count_blank = 0
    for part in ipv6_groups:
        if not part:
            count_blank += 1
            continue
        try:
            num = int(part, 16)
        except ValueError:
            return False
        else:
            if not 0 <= num <= 65536 or len(part) > 4:
                return False

    max_groups = 6 if ipv4_groups else 8
    part_count = len(ipv6_groups) - count_blank
    if count_blank == 0 and part_count == max_groups:
        # no :: -> must have size of max_groups
        return True
    elif count_blank == 1 and ipv6_groups[-1] and ipv6_groups[0] and part_count < max_groups:
        # one :: inside the address or prefix or suffix : -> filter least two cases
        return True
    elif count_blank == 2 and part_count < max_groups and (
            ((ipv6_groups[0] and not ipv6_groups[-1]) or (not ipv6_groups[0] and ipv6_groups[-1])) or ipv4_groups):
        # leading or trailing :: or : at end and begin -> filter last case
        # Check if it has ipv4 groups because they get removed from the ipv6_groups
        return True
    elif count_blank == 3 and part_count == 0:
        # :: is the address -> filter everything else
        return True
    return False

@validator
def ipv6_cidr(value):
    """
    Returns whether a given value is a valid CIDR-notated IP version 6
    address range.

    This validator is based on RFC4632 3.1.

    Examples::

        >>> ipv6_cidr('::1/128')
        True

        >>> ipv6_cidr('::1')
        ValidationFailure(func=ipv6_cidr, args={'value': '::1'})
    """
    try:
        prefix, suffix = value.split('/', 2)
    except ValueError:
        return False
    if not ipv6(prefix) or not suffix.isdigit():
        return False
    return 0 <= int(suffix) <= 128


text:
/**
 *
 * App.js
 *
 * This component is the skeleton around the actual pages, and should only
 * contain code that should be seen on all pages. (e.g. navigation bar)
 *
 * NOTE: while this component should technically be a stateless functional
 * component (SFC), hot reloading does not currently support SFCs. If hot
 * reloading is not a necessity for you then you can refactor it and remove
 * the linting exception.
 */

import React from 'react';
import { Switch, Route } from 'react-router-dom';

import HomePage from 'containers/HomePage/Loadable';
import NotFoundPage from 'containers/NotFoundPage/Loadable';
import './index.css';

export default function App() {
  return (
    <div>
      <Switch>
        <Route exact path="/" component={HomePage} />
        <Route component={NotFoundPage} />
      </Switch>
    </div>
  );
}


text:
/home/ksandom/.config/google-chrome/Default/User StyleSheets/Custom.css
/usr/share/opera/user.css


text:
    {{article.updatedAt | date:'medium'}}/
    {{article.User.name}}

{{article.title}}

        	Edit

            Delete

{{article.content}}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>vincr</title>
    <link rel="stylesheet" type="text/css" href="csound.css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.78.1" />
    <link rel="home" href="index.html" title="Manuel de référence canonique de Csound" />
    <link rel="up" href="OpcodesTop.html" title="Opcodes et opérateurs de l'orchestre" />
    <link rel="prev" href="vibrato.html" title="vibrato" />
    <link rel="next" href="vlimit.html" title="vlimit" />

          vincr

          Précédent
          Opcodes et opérateurs de l'orchestre
           Suivant

          vincr

vincr —
      Accumule des signaux audio.

Description

      vincr incrémente une variable audio avec un autre signal,
      c-à-d qu'il accumule les valeurs dans sa sortie.

Syntaxe

vincr accum, aincr

Exécution

      accum -- variable accumulateur de taux-a à incrémenter

      aincr -- signal d'incrémentation

      vincr (variable increment) et
      clear sont prévus pour être
      utilisés ensemble. vincr stocke la somme de deux variables
      audio dans la première variable (qui joue ainsi le rôle d'un accumulateur en
      polyphonie). L'accumulateur est habituellement une variable globale qui est
      utilisée pour combiner des signaux provenant de plusieurs sources (différents
      instruments ou instances d'intruments) pour un traitement ultérieur (par
      exemple via un effet global qui lit l'accumulateur) ou pour sortir le signal
      composé par un autre moyen que les opcodes out (par exemple
      via l'opcode fout). Après
      son utilisation, la variable accumulateur doit être remise à zéro au moyen de
      l'opcode clear (sinon elle sera saturée).

Exemples

      Voici un exemple de l'opcode vincr. Il utilise le fichier
      vincr.csd.

            Exemple 1037. Exemple de l'opcode vincr.

Voir les sections Audio en Temps Réel
        et Options de la Ligne de Commande pour plus
        d'information sur l'utilisation des options de la ligne de commande.

<CsoundSynthesizer>
<CsOptions>
; Select audio/midi flags here according to platform
-odac     ;;;realtime audio out
;-iadc    ;;;uncomment -iadc if RT audio input is needed too
; For Non-realtime ouput leave only the line below:
; -o vincr.wav -W ;;; for file output any platform
</CsOptions>
<CsInstruments>

sr = 44100
ksmps = 32
nchnls = 2
0dbfs  = 1

gaReverb init 0

instr 1

idur	= p3
kpitch	= p4
a1	diskin2	"fox.wav", kpitch
a1	= a1*.5			;reduce volume
	vincr	gaReverb, a1
endin

instr 99 ; global reverb
al, ar	reverbsc gaReverb, gaReverb, .8, 10000
	outs	gaReverb+al, gaReverb+ar

clear	gaReverb

endin

</CsInstruments>
<CsScore>

i1  0 3 1
i99 0 5
e

</CsScore>
</CsoundSynthesizer>

      Voici un autre exemple de l'opcode vincr. Il utilise le fichier
      vincr-complex.csd.

            Exemple 1038.

<CsoundSynthesizer>
<CsOptions>
; Select audio/midi flags here according to platform
-odac     ;;;realtime audio out
;-iadc    ;;;uncomment -iadc if RT audio input is needed too
; For Non-realtime ouput leave only the line below:
; -o vincr-complex.wav -W ;;; for file output any platform
</CsOptions>
<CsInstruments>

sr = 44100
ksmps = 32
nchnls = 2
0dbfs  = 1

gaReverbSend init 0

instr 1

iamp   = p4
ifreq  = p5
aenv   linseg  0.0, 0.1*p3, iamp, 0.6*p3, iamp, 0.3*p3, 0.0
aosc   poscil aenv, ifreq, 1
       vincr   gaReverbSend, aosc
endin

instr 2	; global reverb instrument

al, ar reverbsc gaReverbSend, gaReverbSend, 0.85, 12000
       outs     gaReverbSend+al, gaReverbSend+ar
       clear    gaReverbSend
endin

</CsInstruments>
<CsScore>
f1 0 4096 10 1

{ 4 CNT
  { 8 PARTIAL
      ;   start time     duration            amplitude          frequency
      i1  [0.5 * $CNT.]  [1 + ($CNT * 0.2)]  [.04 + (~ * .02)]  [800 + (200 * $CNT.) + ($PARTIAL. * 20)]
  }
}

i2 0 6
e
</CsScore>
</CsoundSynthesizer>

Voir aussi

      clear

Crédits

            Auteur : Gabriel Maldonado

            Italie

            1999

Nouveau dans la version 3.56 de Csound

          Précédent

            Niveau supérieur

           Suivant

          vibrato

            Sommaire

           vlimit


text:
//
//  XRRegisterViewController.m
//  XinranReadingGroup
//
//  Created by Xiao Du on 15/4/7.
//  Copyright (c) 2015年 SnowWolf. All rights reserved.
//

#import "XRRegisterViewController.h"
#import "XRLoginBiz.h"
#import <ZYCoreDefine.h>
#import <UIViewController+ZYCore.h>
#import <ZYCoreHintAssistant.h>
#import "XRUser.h"

@interface XRRegisterViewController ()

@property (weak, nonatomic) IBOutlet UITextField *userName;
@property (weak, nonatomic) IBOutlet UITextField *password;
@property (weak, nonatomic) IBOutlet UITextField *confirmPassword;
@property (weak, nonatomic) IBOutlet UIButton *registerButton;
@property (weak, nonatomic) IBOutlet UITextField *nickName;

@end

@implementation XRRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)registerButtonTapped:(UIButton *)sender {
    if (![self.password.text isEqualToString:self.confirmPassword.text]) {
        [ZYCoreHintAssistant showAlertViewWithTitle:LOCALSTRING(@"确认密码的内容与密码不一致哟")];
        return;
    }
    self.registerButton.enabled = NO;
    [XRLoginBiz registerUser:self.userName.text password:self.password.text nickName:self.nickName.text success:^{
        //跳到主页
        self.registerButton.enabled = YES;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self presentViewControllerWithStoryboardName:@"Main" viewController:@"XRTabbarController" animation:NO completion:^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.navigationController popToRootViewControllerAnimated:NO];
                });
            }];
        });
    } failure:^(NSError *error) {
        DLog(@"注册失败,失败原因:%@",error.description);
        self.registerButton.enabled = YES;
        dispatch_async(dispatch_get_main_queue(), ^{
            [ZYCoreHintAssistant showAlertViewWithTitle:LOCALSTRING(@"注册失败啦")];
        });
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
const fs = require("fs");
const path = require('path');
const util = require('util')
const readdir = util.promisify(fs.readdir);
const readFile = util.promisify(fs.readFile);
const writeFile = util.promisify(fs.writeFile)
//joining path of directory
const directoryPath = path.join(__dirname, '_posts');
(async () => {
    const files = await readdir(directoryPath);
    const mdFiles = await Promise.all(files
    .filter(file=> file.endsWith(".md"))
    .map(async (file)=>{
        const content = await readFile(`_posts/${file}`, 'utf8');
        let contentAsArray = content.split("\n");
        const hasRedirect = contentAsArray[7].startsWith("redirect_from:");
        if(!hasRedirect){
         const redirect = `redirect_from: "/${file.substring(0,4)}/${file.substring(11, file.length-3).replace(/ /g, "-")}/"`;
          contentAsArray.splice(7,0, redirect);
        }
        return {
            file,
            content: contentAsArray,

        }
    }));
    console.log("DOOOOING IT");
    await Promise.all(mdFiles.map(async f => {
        const content = f.content.join("\n");
        await writeFile(`_posts/${f.file}`, content);
        console.log(`Writing redirect to ${f.file}`);
    }));
})()