text
stringlengths 4
5.48M
| meta
stringlengths 14
6.54k
|
---|---|
#import "NSObject.h"
@class NSMutableArray, NSSet, NSString;
@interface IBCustomClassSuggestionsProvider : NSObject
{
NSString *currentAutoCompletingComboBoxDataSourceBaseClassName;
unsigned int dataSourceQueryGeneration;
NSMutableArray *pendingHandlers;
NSSet *validResults;
BOOL queriesAreInFlight;
id <IBCustomClassSuggestionsProviderDelegate> _delegate;
}
@property __weak id <IBCustomClassSuggestionsProviderDelegate> delegate; // @synthesize delegate=_delegate;
- (void).cxx_destruct;
- (void)suggestCompletionsForBaseclass:(id)arg1 fromDocument:(id)arg2 completionHandler:(id)arg3;
- (void)setQueriesAreInFlight:(BOOL)arg1;
- (void)notifyHandlersOfResults:(id)arg1;
- (id)init;
@end
| {'content_hash': 'a52712f6bc9b173e28216d7df956d0b6', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 107, 'avg_line_length': 28.84, 'alnum_prop': 0.7891816920943134, 'repo_name': 'liyong03/YLCleaner', 'id': '0e7231d1821f292f99867f6e352557909784987b', 'size': '861', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'YLCleaner/Xcode-RuntimeHeaders/IDEInterfaceBuilderKit/IBCustomClassSuggestionsProvider.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '158958'}, {'name': 'C++', 'bytes': '612673'}, {'name': 'Objective-C', 'bytes': '10594281'}, {'name': 'Ruby', 'bytes': '675'}]} |
package com.consol.citrus.simulator.endpoint;
import com.consol.citrus.context.TestContext;
import com.consol.citrus.context.TestContextFactory;
import com.consol.citrus.endpoint.Endpoint;
import com.consol.citrus.endpoint.EndpointAdapter;
import com.consol.citrus.exceptions.ActionTimeoutException;
import com.consol.citrus.exceptions.CitrusRuntimeException;
import com.consol.citrus.message.Message;
import com.consol.citrus.messaging.Producer;
import com.consol.citrus.messaging.ReplyProducer;
import com.consol.citrus.simulator.exception.SimulatorException;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import java.util.concurrent.*;
/**
* @author Christoph Deppisch
*/
public class SimulatorEndpointPoller implements InitializingBean, Runnable, DisposableBean, ApplicationListener<ContextClosedEvent> {
/**
* Logger
*/
private static final Logger LOG = LoggerFactory.getLogger(SimulatorEndpointPoller.class);
@Autowired
private TestContextFactory testContextFactory;
/**
* Endpoint destination that is constantly polled for new messages.
*/
private Endpoint inboundEndpoint;
private final ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat("endpoint-poller-thread-%d")
.build();
/**
* Thread running the server
*/
private ExecutorService taskExecutor = Executors.newSingleThreadExecutor(threadFactory);
/**
* Message handler for incoming simulator request messages
*/
private EndpointAdapter endpointAdapter;
/**
* Running flag
*/
private CompletableFuture<Boolean> running = new CompletableFuture<>();
/**
* Should automatically start on system load
*/
private boolean autoStart = true;
/**
* Polling delay after uncategorized exception occurred.
*/
private long exceptionDelay = 10000L;
@Override
public void run() {
LOG.info("Simulator endpoint waiting for requests on endpoint '{}'", inboundEndpoint.getName());
long delay = 0L;
while (running.getNow(true)) {
try {
if (delay > 0) {
try {
if (!running.get(delay, TimeUnit.MILLISECONDS)) {
continue;
}
} catch (TimeoutException e) {
LOG.info("Continue simulator endpoint polling after uncategorized exception");
} finally {
delay = 0;
}
}
TestContext context = testContextFactory.getObject();
Message message = inboundEndpoint.createConsumer().receive(context, inboundEndpoint.getEndpointConfiguration().getTimeout());
if (message != null) {
LOG.debug("Processing inbound message '{}'", message.getId());
Message response = endpointAdapter.handleMessage(processRequestMessage(message));
if (response != null) {
Producer producer = inboundEndpoint.createProducer();
if (producer instanceof ReplyProducer) {
LOG.debug("Sending response message for inbound message '{}'", message.getId());
producer.send(processResponseMessage(response), context);
}
}
}
} catch (ActionTimeoutException e) {
// ignore timeout and continue listening for request messages.
} catch (SimulatorException | CitrusRuntimeException e) {
LOG.error("Failed to process message: {}", e.getMessage());
if (LOG.isDebugEnabled()) {
LOG.debug(e.getMessage(), e);
}
} catch (Exception e) {
delay = exceptionDelay;
LOG.error("Unexpected error while processing: {}", e.getMessage());
if (LOG.isDebugEnabled()) {
LOG.debug(e.getMessage(), e);
}
}
}
}
/**
* Process response message before sending back to client. This gives subclasses
* the opportunity to manipulate the response.
*
* @param response
* @return
*/
protected Message processResponseMessage(Message response) {
return response;
}
/**
* Process request message before handling. This gives subclasses the opportunity
* to manipulate the request before execution.
*
* @param request
* @return
*/
protected Message processRequestMessage(Message request) {
return request;
}
/**
* Start up runnable in separate thread.
*/
public void start() {
taskExecutor.execute(this);
}
/**
* Stop runnable execution.
*/
public void stop() {
LOG.info("Simulator endpoint poller terminating ...");
running.complete(false);
try {
taskExecutor.awaitTermination(exceptionDelay, TimeUnit.MILLISECONDS);
LOG.info("Simulator endpoint poller termination complete");
} catch (InterruptedException e) {
LOG.error("Error while waiting termination of endpoint poller", e);
Thread.currentThread().interrupt();
throw new SimulatorException(e);
} finally {
taskExecutor.shutdownNow();
}
}
@Override
public void afterPropertiesSet() throws Exception {
if (autoStart) {
start();
}
}
@Override
public void destroy() throws Exception {
stop();
}
/**
* Sets the target inbound endpoint to read messages from.
*
* @param inboundEndpoint
*/
public void setInboundEndpoint(Endpoint inboundEndpoint) {
this.inboundEndpoint = inboundEndpoint;
}
/**
* Sets the endpoint adapter to delegate messages to.
*
* @param endpointAdapter
*/
public void setEndpointAdapter(EndpointAdapter endpointAdapter) {
this.endpointAdapter = endpointAdapter;
}
/**
* Enable/disable auto start.
*
* @param autoStart
*/
public void setAutoStart(boolean autoStart) {
this.autoStart = autoStart;
}
/**
* Sets the exceptionDelay.
*
* @param exceptionDelay
*/
public void setExceptionDelay(long exceptionDelay) {
this.exceptionDelay = exceptionDelay;
}
/**
* Gets the exceptionDelay.
*
* @return
*/
public long getExceptionDelay() {
return exceptionDelay;
}
@Override
public void onApplicationEvent(ContextClosedEvent event) {
stop();
}
}
| {'content_hash': '20c211cb9c3949d6e2867181d6c2f351', 'timestamp': '', 'source': 'github', 'line_count': 235, 'max_line_length': 141, 'avg_line_length': 30.642553191489363, 'alnum_prop': 0.6140813775864463, 'repo_name': 'christophd/citrus-simulator', 'id': 'bcdf1156601011ba1da47142be0e1c670260fa8a', 'size': '7820', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'simulator-starter/src/main/java/com/consol/citrus/simulator/endpoint/SimulatorEndpointPoller.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '4957'}, {'name': 'HTML', 'bytes': '27422'}, {'name': 'Java', 'bytes': '642737'}, {'name': 'JavaScript', 'bytes': '1771'}, {'name': 'TypeScript', 'bytes': '47129'}]} |
/* **********************************************
Begin Embed.CDN.js
********************************************** */
/* Embed.CDN
Extend the basic 'embed' functionality with Google Analytics tracking and url parsing to support URLs created with the Timeline generator form.
*/
/* CodeKit Import
https://incident57.com/codekit/
================================================== */
// @codekit-append "Embed.js";
/* REPLACE THIS WITH YOUR GOOGLE ANALYTICS ACCOUNT
================================================== */
var embed_analytics = "UA-537357-20";
/* REPLACE THIS WITH YOUR BASE PATH FOR TIMELINE
================================================== */
//var embed_path = "https://cdn.knightlab.com/libs/timeline3/latest/embed/";
/* LOAD TIMER
================================================== */
var load_time_start = new Date().getTime(), the_load_time = 0;
/* GOOGLE ANALYTICS
================================================== */
var _gaq = _gaq || [];
(function() {
var ga = document.createElement('script'), s = document.getElementsByTagName('script')[0];
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
s.parentNode.insertBefore(ga, s);
_gaq.push(['_setAccount', embed_analytics]);
_gaq.push(['_trackPageview']);
})();
/* TIMELINE CDN SPECIFIC
================================================== */
var getUrlVars = function() {
var varobj = {}, url_vars = [], uv ;
//url_vars = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
url_vars = window.location.href.slice(window.location.href.indexOf('?') + 1);
if (url_vars.match('#')) {
url_vars = url_vars.split('#')[0];
}
url_vars = url_vars.split('&');
for(var i = 0; i < url_vars.length; i++) {
uv = url_vars[i].split('=');
varobj[uv[0]] = uv[1];
}
return varobj;
};
var onHeadline = function(e, headline) {
var the_page_title = "/" + headline,
the_page_url = location.href;
document.title = headline;
the_load_time = Math.floor((new Date().getTime() - load_time_start)/100)/10;
_gaq.push(['_trackEvent', 'Timeline', headline, the_page_url, the_load_time]);
};
var url_config = getUrlVars();
/* **********************************************
Begin LazyLoad.js
********************************************** */
/*jslint browser: true, eqeqeq: true, bitwise: true, newcap: true, immed: true, regexp: false */
/*
LazyLoad makes it easy and painless to lazily load one or more external
JavaScript or CSS files on demand either during or after the rendering of a web
page.
Supported browsers include Firefox 2+, IE6+, Safari 3+ (including Mobile
Safari), Google Chrome, and Opera 9+. Other browsers may or may not work and
are not officially supported.
Visit https://github.com/rgrove/lazyload/ for more info.
Copyright (c) 2011 Ryan Grove <[email protected]>
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the 'Software'), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@module lazyload
@class LazyLoad
@static
@version 2.0.3 (git)
*/
LazyLoad = (function (doc) {
// -- Private Variables ------------------------------------------------------
// User agent and feature test information.
var env,
// Reference to the <head> element (populated lazily).
head,
// Requests currently in progress, if any.
pending = {},
// Number of times we've polled to check whether a pending stylesheet has
// finished loading. If this gets too high, we're probably stalled.
pollCount = 0,
// Queued requests.
queue = {css: [], js: []},
// Reference to the browser's list of stylesheets.
styleSheets = doc.styleSheets;
// -- Private Methods --------------------------------------------------------
/**
Creates and returns an HTML element with the specified name and attributes.
@method createNode
@param {String} name element name
@param {Object} attrs name/value mapping of element attributes
@return {HTMLElement}
@private
*/
function createNode(name, attrs) {
var node = doc.createElement(name), attr;
for (attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
node.setAttribute(attr, attrs[attr]);
}
}
return node;
}
/**
Called when the current pending resource of the specified type has finished
loading. Executes the associated callback (if any) and loads the next
resource in the queue.
@method finish
@param {String} type resource type ('css' or 'js')
@private
*/
function finish(type) {
var p = pending[type],
callback,
urls;
if (p) {
callback = p.callback;
urls = p.urls;
urls.shift();
pollCount = 0;
// If this is the last of the pending URLs, execute the callback and
// start the next request in the queue (if any).
if (!urls.length) {
callback && callback.call(p.context, p.obj);
pending[type] = null;
queue[type].length && load(type);
}
}
}
/**
Populates the <code>env</code> variable with user agent and feature test
information.
@method getEnv
@private
*/
function getEnv() {
var ua = navigator.userAgent;
env = {
// True if this browser supports disabling async mode on dynamically
// created script nodes. See
// http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order
async: doc.createElement('script').async === true
};
(env.webkit = /AppleWebKit\//.test(ua))
|| (env.ie = /MSIE/.test(ua))
|| (env.opera = /Opera/.test(ua))
|| (env.gecko = /Gecko\//.test(ua))
|| (env.unknown = true);
}
/**
Loads the specified resources, or the next resource of the specified type
in the queue if no resources are specified. If a resource of the specified
type is already being loaded, the new request will be queued until the
first request has been finished.
When an array of resource URLs is specified, those URLs will be loaded in
parallel if it is possible to do so while preserving execution order. All
browsers support parallel loading of CSS, but only Firefox and Opera
support parallel loading of scripts. In other browsers, scripts will be
queued and loaded one at a time to ensure correct execution order.
@method load
@param {String} type resource type ('css' or 'js')
@param {String|Array} urls (optional) URL or array of URLs to load
@param {Function} callback (optional) callback function to execute when the
resource is loaded
@param {Object} obj (optional) object to pass to the callback function
@param {Object} context (optional) if provided, the callback function will
be executed in this object's context
@private
*/
function load(type, urls, callback, obj, context) {
var _finish = function () { finish(type); },
isCSS = type === 'css',
nodes = [],
i, len, node, p, pendingUrls, url;
env || getEnv();
if (urls) {
// If urls is a string, wrap it in an array. Otherwise assume it's an
// array and create a copy of it so modifications won't be made to the
// original.
urls = typeof urls === 'string' ? [urls] : urls.concat();
// Create a request object for each URL. If multiple URLs are specified,
// the callback will only be executed after all URLs have been loaded.
//
// Sadly, Firefox and Opera are the only browsers capable of loading
// scripts in parallel while preserving execution order. In all other
// browsers, scripts must be loaded sequentially.
//
// All browsers respect CSS specificity based on the order of the link
// elements in the DOM, regardless of the order in which the stylesheets
// are actually downloaded.
if (isCSS || env.async || env.gecko || env.opera) {
// Load in parallel.
queue[type].push({
urls : urls,
callback: callback,
obj : obj,
context : context
});
} else {
// Load sequentially.
for (i = 0, len = urls.length; i < len; ++i) {
queue[type].push({
urls : [urls[i]],
callback: i === len - 1 ? callback : null, // callback is only added to the last URL
obj : obj,
context : context
});
}
}
}
// If a previous load request of this type is currently in progress, we'll
// wait our turn. Otherwise, grab the next item in the queue.
if (pending[type] || !(p = pending[type] = queue[type].shift())) {
return;
}
head || (head = doc.head || doc.getElementsByTagName('head')[0]);
pendingUrls = p.urls;
for (i = 0, len = pendingUrls.length; i < len; ++i) {
url = pendingUrls[i];
if (isCSS) {
node = env.gecko ? createNode('style') : createNode('link', {
href: url,
rel : 'stylesheet'
});
} else {
node = createNode('script', {src: url});
node.async = false;
}
node.className = 'lazyload';
node.setAttribute('charset', 'utf-8');
if (env.ie && !isCSS) {
node.onreadystatechange = function () {
if (/loaded|complete/.test(node.readyState)) {
node.onreadystatechange = null;
_finish();
}
};
} else if (isCSS && (env.gecko || env.webkit)) {
// Gecko and WebKit don't support the onload event on link nodes.
if (env.webkit) {
// In WebKit, we can poll for changes to document.styleSheets to
// figure out when stylesheets have loaded.
p.urls[i] = node.href; // resolve relative URLs (or polling won't work)
pollWebKit();
} else {
// In Gecko, we can import the requested URL into a <style> node and
// poll for the existence of node.sheet.cssRules. Props to Zach
// Leatherman for calling my attention to this technique.
node.innerHTML = '@import "' + url + '";';
pollGecko(node);
}
} else {
node.onload = node.onerror = _finish;
}
nodes.push(node);
}
for (i = 0, len = nodes.length; i < len; ++i) {
head.appendChild(nodes[i]);
}
}
/**
Begins polling to determine when the specified stylesheet has finished loading
in Gecko. Polling stops when all pending stylesheets have loaded or after 10
seconds (to prevent stalls).
Thanks to Zach Leatherman for calling my attention to the @import-based
cross-domain technique used here, and to Oleg Slobodskoi for an earlier
same-domain implementation. See Zach's blog for more details:
http://www.zachleat.com/web/2010/07/29/load-css-dynamically/
@method pollGecko
@param {HTMLElement} node Style node to poll.
@private
*/
function pollGecko(node) {
var hasRules;
try {
// We don't really need to store this value or ever refer to it again, but
// if we don't store it, Closure Compiler assumes the code is useless and
// removes it.
hasRules = !!node.sheet.cssRules;
} catch (ex) {
// An exception means the stylesheet is still loading.
pollCount += 1;
if (pollCount < 200) {
setTimeout(function () { pollGecko(node); }, 50);
} else {
// We've been polling for 10 seconds and nothing's happened. Stop
// polling and finish the pending requests to avoid blocking further
// requests.
hasRules && finish('css');
}
return;
}
// If we get here, the stylesheet has loaded.
finish('css');
}
/**
Begins polling to determine when pending stylesheets have finished loading
in WebKit. Polling stops when all pending stylesheets have loaded or after 10
seconds (to prevent stalls).
@method pollWebKit
@private
*/
function pollWebKit() {
var css = pending.css, i;
if (css) {
i = styleSheets.length;
// Look for a stylesheet matching the pending URL.
while (--i >= 0) {
if (styleSheets[i].href === css.urls[0]) {
finish('css');
break;
}
}
pollCount += 1;
if (css) {
if (pollCount < 200) {
setTimeout(pollWebKit, 50);
} else {
// We've been polling for 10 seconds and nothing's happened, which may
// indicate that the stylesheet has been removed from the document
// before it had a chance to load. Stop polling and finish the pending
// request to prevent blocking further requests.
finish('css');
}
}
}
}
return {
/**
Requests the specified CSS URL or URLs and executes the specified
callback (if any) when they have finished loading. If an array of URLs is
specified, the stylesheets will be loaded in parallel and the callback
will be executed after all stylesheets have finished loading.
@method css
@param {String|Array} urls CSS URL or array of CSS URLs to load
@param {Function} callback (optional) callback function to execute when
the specified stylesheets are loaded
@param {Object} obj (optional) object to pass to the callback function
@param {Object} context (optional) if provided, the callback function
will be executed in this object's context
@static
*/
css: function (urls, callback, obj, context) {
load('css', urls, callback, obj, context);
},
/**
Requests the specified JavaScript URL or URLs and executes the specified
callback (if any) when they have finished loading. If an array of URLs is
specified and the browser supports it, the scripts will be loaded in
parallel and the callback will be executed after all scripts have
finished loading.
Currently, only Firefox and Opera support parallel loading of scripts while
preserving execution order. In other browsers, scripts will be
queued and loaded one at a time to ensure correct execution order.
@method js
@param {String|Array} urls JS URL or array of JS URLs to load
@param {Function} callback (optional) callback function to execute when
the specified scripts are loaded
@param {Object} obj (optional) object to pass to the callback function
@param {Object} context (optional) if provided, the callback function
will be executed in this object's context
@static
*/
js: function (urls, callback, obj, context) {
load('js', urls, callback, obj, context);
}
};
})(this.document);
/* **********************************************
Begin Embed.LoadLib.js
********************************************** */
/*
LoadLib
Designed and built by Zach Wise http://zachwise.com/
Extends LazyLoad
*/
/* * CodeKit Import
* https://incident57.com/codekit/
================================================== */
// @codekit-prepend "LazyLoad.js";
LoadLib = (function (doc) {
var loaded = [];
function isLoaded(url) {
var i = 0,
has_loaded = false;
for (i = 0; i < loaded.length; i++) {
if (loaded[i] == url) {
has_loaded = true;
}
}
if (has_loaded) {
return true;
} else {
loaded.push(url);
return false;
}
}
return {
css: function (urls, callback, obj, context) {
if (!isLoaded(urls)) {
LazyLoad.css(urls, callback, obj, context);
}
},
js: function (urls, callback, obj, context) {
if (!isLoaded(urls)) {
LazyLoad.js(urls, callback, obj, context);
}
}
};
})(this.document);
/* **********************************************
Begin Embed.js
********************************************** */
//StoryJS Embed Loader
// Provide a bootstrap method for instantiating a timeline. On page load, check the definition of these window scoped variables in this order: [url_config, timeline_config, storyjs_config, config]. As soon as one of these is found to be defined with type 'object,' it will be used to automatically instantiate a timeline.
/* CodeKit Import
https://incident57.com/codekit/
================================================== */
// @codekit-prepend "Embed.LoadLib.js";
if(typeof embed_path == 'undefined') {
// REPLACE WITH YOUR BASEPATH IF YOU WANT OTHERWISE IT WILL TRY AND FIGURE IT OUT
var _tmp_script_path = getEmbedScriptPath("timeline-embed.js");
var embed_path = _tmp_script_path.substr(0,_tmp_script_path.lastIndexOf('js/'))
}
function getEmbedScriptPath(scriptname) {
var scriptTags = document.getElementsByTagName('script'),
script_path = "",
script_path_end = "";
for(var i = 0; i < scriptTags.length; i++) {
if (scriptTags[i].src.match(scriptname)) {
script_path = scriptTags[i].src;
}
}
if (script_path != "") {
script_path_end = "/"
}
return script_path.split('?')[0].split('/').slice(0, -1).join('/') + script_path_end;
}
/* CHECK TO SEE IF A CONFIG IS ALREADY DEFINED (FOR EASY EMBED)
================================================== */
(function() {
if (typeof url_config == 'object') {
createStoryJS(url_config);
} else if (typeof timeline_config == 'object') {
createStoryJS(timeline_config);
} else if (typeof storyjs_config == 'object') {
createStoryJS(storyjs_config);
} else if (typeof config == 'object') {
createStoryJS(config);
} else {
// No existing config. Call createStoryJS(your_config) manually with a config
}
})();
/* CREATE StoryJS Embed
================================================== */
function createStoryJS(c, src) {
/* VARS
================================================== */
var storyjs_embedjs, t, te, x,
isCDN = false,
js_version = "2.24",
ready = {
timeout: "",
checks: 0,
finished: false,
js: false,
css: false,
font: {
css: false
}
},
path = {
base: embed_path,
css: embed_path + "css/",
js: embed_path + "js/",
font: {
google: false,
css: embed_path + "css/fonts/",
js: "//ajax.googleapis.com/ajax/libs/webfont/1/webfont.js"
}
},
storyjs_e_config = {
version: js_version,
debug: false,
type: 'timeline',
id: 'storyjs',
embed_id: 'timeline-embed',
is_embed: true,
width: '100%',
height: '100%',
source: 'https://docs.google.com/spreadsheet/pub?key=0Agl_Dv6iEbDadFYzRjJPUGktY0NkWXFUWkVIZDNGRHc&output=html',
lang: 'en',
font: 'default',
start_at_end: false,
timenav_position: 'bottom',
css: path.css + 'timeline.css?'+js_version,
js: '',
api_keys: {
google: "",
flickr: "",
twitter: ""
},
gmap_key: ""
}
/* BUILD CONFIG
================================================== */
if (typeof c == 'object') {
for (x in c) {
if (Object.prototype.hasOwnProperty.call(c, x)) {
storyjs_e_config[x] = c[x];
}
}
}
if (typeof src != 'undefined') {
storyjs_e_config.source = src;
}
/* CDN VERSION?
================================================== */
if (typeof url_config == 'object') {
isCDN = true;
/* IS THE SOURCE GOOGLE SPREADSHEET WITH JUST THE KEY?
================================================== */
if (storyjs_e_config.source.match("docs.google.com") || storyjs_e_config.source.match("json") || storyjs_e_config.source.match("storify") ) {
} else {
storyjs_e_config.source = "https://docs.google.com/spreadsheet/pub?key=" + storyjs_e_config.source + "&output=html";
}
}
/* DETERMINE TYPE
================================================== */
if (storyjs_e_config.js.match("/")) {
} else {
storyjs_e_config.css = path.css + storyjs_e_config.type + ".css?" + js_version;
// Use unminified js file if in debug mode
storyjs_e_config.js = path.js + storyjs_e_config.type;
if (storyjs_e_config.debug) {
storyjs_e_config.js += ".js?" + js_version;
} else {
storyjs_e_config.js += "-min.js?" + js_version;
}
storyjs_e_config.id = "storyjs-" + storyjs_e_config.type;
}
/* PREPARE
================================================== */
createEmbedDiv();
/* Load CSS
================================================== */
LoadLib.css(storyjs_e_config.css, onloaded_css);
/* Load FONT
================================================== */
if (storyjs_e_config.font == "default") {
ready.font.css = true;
} else {
// FONT CSS
var fn;
if (storyjs_e_config.font.match("/")) {
fn = storyjs_e_config.font.split(".css")[0].split("/");
path.font.name = fn[fn.length -1];
path.font.css = storyjs_e_config.font;
} else {
path.font.name = storyjs_e_config.font;
path.font.css = path.font.css + "font."+storyjs_e_config.font.toLowerCase()+".css?" + js_version;
}
LoadLib.css(path.font.css, onloaded_font_css);
}
LoadLib.js(storyjs_e_config.js, onloaded_js);
/* On Loaded
================================================== */
function onloaded_js() {
ready.js = true;
onloaded_check();
}
function onloaded_css() {
ready.css = true;
onloaded_check();
}
function onloaded_font_css() {
ready.font.css = true;
onloaded_check();
}
function onloaded_check() {
if (ready.checks > 40) {
return;
alert("Error Loading Files");
} else {
ready.checks++;
if (ready.js && ready.css && ready.font.css) {
if (!ready.finished) {
ready.finished = true;
buildEmbed();
}
} else {
ready.timeout = setTimeout('onloaded_check_again();', 250);
}
}
};
this.onloaded_check_again = function() {
onloaded_check();
};
/* Build Timeline
================================================== */
function createEmbedDiv() {
var embed_classname = "tl-timeline-embed";
t = document.createElement('div');
if (storyjs_e_config.embed_id != "") {
te = document.getElementById(storyjs_e_config.embed_id);
} else {
te = document.getElementById("timeline-embed");
}
te.appendChild(t);
t.setAttribute("id", storyjs_e_config.id);
if (storyjs_e_config.width.toString().match("%") ) {
te.style.width = storyjs_e_config.width.split("%")[0] + "%";
} else {
storyjs_e_config.width = storyjs_e_config.width - 2;
te.style.width = (storyjs_e_config.width) + 'px';
}
if (storyjs_e_config.height.toString().match("%")) {
te.style.height = storyjs_e_config.height;
embed_classname += " tl-timeline-full-embed";
te.style.height = storyjs_e_config.height.split("%")[0] + "%";
} else if (storyjs_e_config.width.toString().match("%")) {
embed_classname += " tl-timeline-full-embed";
storyjs_e_config.height = storyjs_e_config.height - 16;
te.style.height = (storyjs_e_config.height) + 'px';
}else {
embed_classname += " sized-embed";
storyjs_e_config.height = storyjs_e_config.height - 16;
te.style.height = (storyjs_e_config.height) + 'px';
}
te.setAttribute("class", embed_classname);
te.setAttribute("className", embed_classname);
t.style.position = 'relative';
}
function buildEmbed() {
TL.debug = storyjs_e_config.debug;
storyjs_e_config['ga_property_id'] = 'UA-27829802-4';
storyjs_e_config.language = storyjs_e_config.lang;
if (storyjs_e_config.width == '100%') {
storyjs_e_config.is_full_embed = true;
}
window.timeline = new TL.Timeline('timeline-embed', storyjs_e_config.source, storyjs_e_config);
}
}
| {'content_hash': 'd7195ab6b709fa4a7af65797d799431c', 'timestamp': '', 'source': 'github', 'line_count': 798, 'max_line_length': 321, 'avg_line_length': 30.949874686716793, 'alnum_prop': 0.5858369098712446, 'repo_name': 'PeterDaveHello/jsdelivr', 'id': 'b08280cbd179d2d9d0a6d1118fc06b70bc7dc2aa', 'size': '25147', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'files/timelinejs3/3.4.7/js/timeline-embed-cdn.js', 'mode': '33188', 'license': 'mit', 'language': []} |
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
namespace Simple.OData.Client;
/// <summary>
/// Provides access to OData operations in a fluent style.
/// </summary>
/// <typeparam name="T">The entity type.</typeparam>
public interface IFluentClient<T, FT>
where T : class
{
/// <summary>
/// Sets the container for data not covered by the entity properties. Typically used with OData open types.
/// </summary>
/// <param name="expression">The filter expression.</param>
/// <returns>Self.</returns>
FT WithProperties(Expression<Func<T, IDictionary<string, object>>> expression);
/// <summary>
/// Sets the container for media stream content to be retrieved or updated together with standard entity properties.
/// </summary>
/// <param name="properties">The media content properties.</param>
/// <returns>Self.</returns>
FT WithMedia(IEnumerable<string> properties);
/// <summary>
/// Sets the container for media stream content to be retrieved or updated together with standard entity properties.
/// </summary>
/// <param name="properties">The media content properties.</param>
/// <returns>Self.</returns>
FT WithMedia(params string[] properties);
/// <summary>
/// Sets the container for media stream content to be retrieved or updated together with standard entity properties.
/// </summary>
/// <param name="properties">The media content properties.</param>
/// <returns>Self.</returns>
FT WithMedia(params ODataExpression[] properties);
/// <summary>
/// Sets the container for media stream content to be retrieved or updated together with standard entity properties.
/// </summary>
/// <param name="properties">The media content properties.</param>
/// <returns>Self.</returns>
FT WithMedia(Expression<Func<T, object>> properties);
/// <summary>
/// Sets the specified entry key.
/// </summary>
/// <param name="entryKey">The entry key.</param>
/// <returns>Self.</returns>
FT Key(params object[] entryKey);
/// <summary>
/// Sets the specified entry key.
/// </summary>
/// <param name="entryKey">The entry key.</param>
/// <returns>Self.</returns>
FT Key(IEnumerable<object> entryKey);
/// <summary>
/// Sets the specified entry key.
/// </summary>
/// <param name="entryKey">The entry key.</param>
/// <returns>Self.</returns>
FT Key(IDictionary<string, object> entryKey);
/// <summary>
/// Sets the specified entry key.
/// </summary>
/// <param name="entryKey">The entry key.</param>
/// <returns>Self.</returns>
FT Key(T entryKey);
/// <summary>
/// Sets the specified OData filter.
/// </summary>
/// <param name="filter">The filter.</param>
/// <returns>Self.</returns>
FT Filter(string filter);
/// <summary>
/// Sets the specified OData filter.
/// </summary>
/// <param name="expression">The filter expression.</param>
/// <returns>Self.</returns>
FT Filter(ODataExpression expression);
/// <summary>
/// Sets the specified OData filter.
/// </summary>
/// <param name="expression">The filter expression.</param>
/// <returns>Self.</returns>
FT Filter(Expression<Func<T, bool>> expression);
/// <summary>
/// Sets the specified OData search.
/// </summary>
/// <param name="search">The search term.</param>
/// <returns>Self.</returns>
FT Search(string search);
/// <summary>
/// Sets the OData function name.
/// </summary>
/// <param name="functionName">Name of the function.</param>
/// <returns>Self.</returns>
FT Function(string functionName);
/// <summary>
/// Sets the OData function name.
/// </summary>
/// <param name="functionName">Name of the function.</param>
/// <returns>Self.</returns>
IBoundClient<U> Function<U>(string functionName) where U : class;
/// <summary>
/// Sets the OData action name.
/// </summary>
/// <param name="actionName">Name of the action.</param>
/// <returns>Self.</returns>
FT Action(string actionName);
/// <summary>
/// Skips the specified number of entries from the result.
/// </summary>
/// <param name="count">The count.</param>
/// <returns>Self.</returns>
FT Skip(long count);
/// <summary>
/// Limits the number of results with the specified value.
/// </summary>
/// <param name="count">The count.</param>
/// <returns>Self.</returns>
FT Top(long count);
/// <summary>
/// Expands top level of all associations.
/// </summary>
/// <param name="expandOptions">The <see cref="ODataExpandOptions"/>.</param>
/// <returns>Self.</returns>
FT Expand(ODataExpandOptions expandOptions);
/// <summary>
/// Expands the top level of the specified associations.
/// </summary>
/// <param name="associations">The associations to expand.</param>
/// <returns>Self.</returns>
FT Expand(IEnumerable<string> associations);
/// <summary>
/// Expands the number of levels of the specified associations.
/// </summary>
/// <param name="expandOptions">The <see cref="ODataExpandOptions"/>.</param>
/// <param name="associations">The associations to expand.</param>
/// <returns>Self.</returns>
FT Expand(ODataExpandOptions expandOptions, IEnumerable<string> associations);
/// <summary>
/// Expands the top level of the specified associations.
/// </summary>
/// <param name="associations">The associations to expand.</param>
/// <returns>Self.</returns>
FT Expand(params string[] associations);
/// <summary>
/// Expands the number of levels of the specified associations.
/// </summary>
/// <param name="expandOptions">The <see cref="ODataExpandOptions"/>.</param>
/// <param name="associations">The associations to expand.</param>
/// <returns>Self.</returns>
FT Expand(ODataExpandOptions expandOptions, params string[] associations);
/// <summary>
/// Expands the top level of the specified associations.
/// </summary>
/// <param name="associations">The associations to expand.</param>
/// <returns>Self.</returns>
FT Expand(params ODataExpression[] associations);
/// <summary>
/// Expands the number of levels of the specified associations.
/// </summary>
/// <param name="expandOptions">The <see cref="ODataExpandOptions"/>.</param>
/// <param name="associations">The associations to expand.</param>
/// <returns>Self.</returns>
FT Expand(ODataExpandOptions expandOptions, params ODataExpression[] associations);
/// <summary>
/// Expands the top level of the specified expression.
/// </summary>
/// <param name="expression">The expression for associations to expand.</param>
/// <returns>Self.</returns>
FT Expand(Expression<Func<T, object>> expression);
/// <summary>
/// Expands the number of levels of the specified associations.
/// </summary>
/// <param name="expandOptions">The <see cref="ODataExpandOptions"/>.</param>
/// <param name="expression">The expression for associations to expand.</param>
/// <returns>Self.</returns>
FT Expand(ODataExpandOptions expandOptions, Expression<Func<T, object>> expression);
/// <summary>
/// Selects the specified result columns.
/// </summary>
/// <param name="columns">The selected columns.</param>
/// <returns>Self.</returns>
FT Select(IEnumerable<string> columns);
/// <summary>
/// Selects the specified result columns.
/// </summary>
/// <param name="columns">The selected columns.</param>
/// <returns>Self.</returns>
FT Select(params string[] columns);
/// <summary>
/// Selects the specified result columns.
/// </summary>
/// <param name="columns">The selected columns.</param>
/// <returns>Self.</returns>
FT Select(params ODataExpression[] columns);
/// <summary>
/// Selects the specified result columns.
/// </summary>
/// <param name="expression">The expression for the selected columns.</param>
/// <returns>Self.</returns>
FT Select(Expression<Func<T, object>> expression);
/// <summary>
/// Sorts the result by the specified columns in the specified order.
/// </summary>
/// <param name="columns">The sort columns.</param>
/// <returns>Self.</returns>
FT OrderBy(IEnumerable<KeyValuePair<string, bool>> columns);
/// <summary>
/// Sorts the result by the specified columns in ascending order.
/// </summary>
/// <param name="columns">The sort columns.</param>
/// <returns>Self.</returns>
FT OrderBy(params string[] columns);
/// <summary>
/// Sorts the result by the specified columns in ascending order.
/// </summary>
/// <param name="columns">The sort columns.</param>
/// <returns>Self.</returns>
FT OrderBy(params ODataExpression[] columns);
/// <summary>
/// Sorts the result by the specified columns in ascending order.
/// </summary>
/// <param name="expression">The expression for the sort columns.</param>
/// <returns>Self.</returns>
FT OrderBy(Expression<Func<T, object>> expression);
/// <summary>
/// Sorts the result by the specified columns in ascending order.
/// </summary>
/// <param name="expression">The expression for the sort columns.</param>
/// <returns>Self.</returns>
FT ThenBy(Expression<Func<T, object>> expression);
/// <summary>
/// Sorts the result by the specified columns in descending order.
/// </summary>
/// <param name="columns">The sort columns.</param>
/// <returns>Self.</returns>
FT OrderByDescending(params string[] columns);
/// <summary>
/// Sorts the result by the specified columns in descending order.
/// </summary>
/// <param name="columns">The sort columns.</param>
/// <returns>Self.</returns>
FT OrderByDescending(params ODataExpression[] columns);
/// <summary>
/// Sorts the result by the specified columns in descending order.
/// </summary>
/// <param name="expression">The expression for the sort columns.</param>
/// <returns>Self.</returns>
FT OrderByDescending(Expression<Func<T, object>> expression);
/// <summary>
/// Sorts the result by the specified columns in descending order.
/// </summary>
/// <param name="expression">The expression for the sort columns.</param>
/// <returns>Self.</returns>
FT ThenByDescending(Expression<Func<T, object>> expression);
/// <summary>
/// Sets the custom query options.
/// </summary>
/// <param name="queryOptions">The custom query options string.</param>
/// <returns>Self.</returns>
FT QueryOptions(string queryOptions);
/// <summary>
/// Sets the custom query options.
/// </summary>
/// <param name="queryOptions">The key/value collection of custom query options.</param>
/// <returns>Self.</returns>
FT QueryOptions(IDictionary<string, object> queryOptions);
/// <summary>
/// Sets the custom query options.
/// </summary>
/// <param name="expression">The custom query options expression.</param>
/// <returns>Self.</returns>
FT QueryOptions(ODataExpression expression);
/// <summary>
/// Sets the custom query options.
/// </summary>
/// <param name="expression">The custom query options expression.</param>
/// <returns>Self.</returns>
FT QueryOptions<U>(Expression<Func<U, bool>> expression);
/// <summary>
/// Adds a header to be included in the HTTP request.
/// </summary>
/// <param name="name">The header name.</param>
/// <param name="value">The header value.</param>
/// <remarks>Ignored in batch actions. For batch headers use the <see cref="ODataBatch.WithHeader(string, string)"/> method.</remarks>
/// <returns>Self.</returns>
FT WithHeader(string name, string value);
/// <summary>
/// Adds a collection of headers to be included in the HTTP request.
/// </summary>
/// <param name="name">The header name.</param>
/// <param name="value">The header value.</param>
/// <remarks>Ignored in batch actions. For batch headers use the <see cref="ODataBatch.WithHeaders(IDictionary{string, string})"/> method.</remarks>
/// <returns>Self.</returns>
FT WithHeaders(IEnumerable<KeyValuePair<string, string>> headers);
/// <summary>
/// Selects retrieval of an entity media stream.
/// </summary>
/// <returns>Self.</returns>
IMediaClient Media();
/// <summary>
/// Selects retrieval of a named media stream.
/// </summary>
/// <param name="streamName">The media stream name.</param>
/// <returns>Self.</returns>
IMediaClient Media(string streamName);
/// <summary>
/// Selects retrieval of a named media stream.
/// </summary>
/// <param name="expression">The media stream name expression.</param>
/// <returns>Self.</returns>
IMediaClient Media(ODataExpression expression);
/// <summary>
/// Selects retrieval of a named media stream.
/// </summary>
/// <param name="expression">The media stream name expression.</param>
/// <returns>Self.</returns>
IMediaClient Media(Expression<Func<T, object>> expression);
/// <summary>
/// Requests the number of results.
/// </summary>
/// <returns>Self.</returns>
FT Count();
/// <summary>
/// Navigates to the linked entity.
/// </summary>
/// <typeparam name="U">The type of the linked entity.</typeparam>
/// <param name="linkName">Name of the link.</param>
/// <returns>Self.</returns>
IBoundClient<U> NavigateTo<U>(string? linkName = null) where U : class;
/// <summary>
/// Navigates to the linked entity.
/// </summary>
/// <typeparam name="U">The type of the linked entity.</typeparam>
/// <param name="expression">The expression for the link.</param>
/// <returns>Self.</returns>
IBoundClient<U> NavigateTo<U>(Expression<Func<T, U>> expression) where U : class;
/// <summary>
/// Navigates to the linked entity.
/// </summary>
/// <typeparam name="U">The type of the linked entity.</typeparam>
/// <param name="expression">The expression for the link.</param>
/// <returns>Self.</returns>
IBoundClient<U> NavigateTo<U>(Expression<Func<T, IEnumerable<U>>> expression) where U : class;
/// <summary>
/// Navigates to the linked entity.
/// </summary>
/// <typeparam name="U">The type of the linked entity.</typeparam>
/// <param name="expression">The expression for the link.</param>
/// <returns>Self.</returns>
IBoundClient<U> NavigateTo<U>(Expression<Func<T, IList<U>>> expression) where U : class;
/// <summary>
/// Navigates to the linked entity.
/// </summary>
/// <typeparam name="U">The type of the linked entity.</typeparam>
/// <param name="expression">The expression for the link.</param>
/// <returns>Self.</returns>
IBoundClient<U> NavigateTo<U>(Expression<Func<T, ISet<U>>> expression) where U : class;
/// <summary>
/// Navigates to the linked entity.
/// </summary>
/// <typeparam name="U">The type of the linked entity.</typeparam>
/// <param name="expression">The expression for the link.</param>
/// <returns>Self.</returns>
IBoundClient<U> NavigateTo<U>(Expression<Func<T, HashSet<U>>> expression) where U : class;
/// <summary>
/// Navigates to the linked entity.
/// </summary>
/// <typeparam name="U">The type of the linked entity.</typeparam>
/// <param name="expression">The expression for the link.</param>
/// <returns>Self.</returns>
IBoundClient<U> NavigateTo<U>(Expression<Func<T, U[]>> expression) where U : class;
/// <summary>
/// Navigates to the linked entity.
/// </summary>
/// <param name="linkName">Name of the link.</param>
/// <returns>Self.</returns>
IBoundClient<IDictionary<string, object>> NavigateTo(string linkName);
/// <summary>
/// Navigates to the linked entity.
/// </summary>
/// <param name="expression">The expression for the link.</param>
/// <returns>Self.</returns>
IBoundClient<T> NavigateTo(ODataExpression expression);
/// <summary>
/// Executes the OData function or action.
/// </summary>
/// <returns>Execution result.</returns>
Task ExecuteAsync();
/// <summary>
/// Executes the OData function or action.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Action execution result.</returns>
Task ExecuteAsync(CancellationToken cancellationToken);
/// <summary>
/// Executes the OData function or action.
/// </summary>
/// <returns>Execution result.</returns>
Task<T> ExecuteAsSingleAsync();
/// <summary>
/// Executes the OData function or action.
/// </summary>
/// <returns>Execution result.</returns>
Task<U> ExecuteAsSingleAsync<U>();
/// <summary>
/// Executes the OData function or action.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Action execution result.</returns>
Task<T> ExecuteAsSingleAsync(CancellationToken cancellationToken);
/// <summary>
/// Executes the OData function or action.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Action execution result.</returns>
Task<U> ExecuteAsSingleAsync<U>(CancellationToken cancellationToken);
/// <summary>
/// Executes the OData function or action and returns collection.
/// </summary>
/// <returns>Action execution result.</returns>
Task<IEnumerable<T>> ExecuteAsEnumerableAsync();
/// <summary>
/// Executes the OData function or action and returns collection.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Execution result.</returns>
Task<IEnumerable<T>> ExecuteAsEnumerableAsync(CancellationToken cancellationToken);
/// <summary>
/// Executes the OData function or action and returns scalar result.
/// </summary>
/// <typeparam name="U">The type of the result.</typeparam>
/// <returns>Execution result.</returns>
Task<U> ExecuteAsScalarAsync<U>();
/// <summary>
/// Executes the OData function or action and returns scalar result.
/// </summary>
/// <typeparam name="U">The type of the result.</typeparam>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Action execution result.</returns>
Task<U> ExecuteAsScalarAsync<U>(CancellationToken cancellationToken);
/// <summary>
/// Executes the OData function or action and returns an array.
/// </summary>
/// <typeparam name="U">The type of the result array.</typeparam>
/// <returns>Execution result.</returns>
Task<U[]> ExecuteAsArrayAsync<U>();
/// <summary>
/// Executes the OData function or action and returns an array.
/// </summary>
/// <returns>Execution result.</returns>
Task<T[]> ExecuteAsArrayAsync();
/// <summary>
/// Executes the OData function or action and returns an array.
/// </summary>
/// <typeparam name="U">The type of the result array.</typeparam>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Action execution result.</returns>
Task<U[]> ExecuteAsArrayAsync<U>(CancellationToken cancellationToken);
/// <summary>
/// Executes the OData function or action and returns an array.
/// </summary>
/// <param name="annotations">The OData feed annotations.</param>
/// <returns>Execution result.</returns>
Task<U[]> ExecuteAsArrayAsync<U>(ODataFeedAnnotations annotations);
/// <summary>
/// Executes the OData function or action and returns an array.
/// </summary>
/// <param name="annotations">The OData feed annotations.</param>
/// <returns>Execution result.</returns>
Task<T[]> ExecuteAsArrayAsync(ODataFeedAnnotations annotations);
/// <summary>
/// Executes the OData function or action and returns an array.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <param name="annotations">The OData feed annotations.</param>
/// <returns>Execution result.</returns>
Task<U[]> ExecuteAsArrayAsync<U>(ODataFeedAnnotations annotations, CancellationToken cancellationToken);
/// <summary>
/// Executes the OData function or action and returns an array.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <param name="annotations">The OData feed annotations.</param>
/// <returns>Execution result.</returns>
Task<T[]> ExecuteAsArrayAsync(ODataFeedAnnotations annotations, CancellationToken cancellationToken);
/// <summary>
/// Executes the OData function or action and returns an array.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Action execution result.</returns>
Task<T[]> ExecuteAsArrayAsync(CancellationToken cancellationToken);
/// <summary>
/// Gets the OData command text.
/// </summary>
/// <returns>The command text.</returns>
Task<string> GetCommandTextAsync();
/// <summary>
/// Gets the OData command text.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The command text.</returns>
Task<string> GetCommandTextAsync(CancellationToken cancellationToken);
}
| {'content_hash': 'cc9908bcc11aa5c81424080b0e429906', 'timestamp': '', 'source': 'github', 'line_count': 581, 'max_line_length': 149, 'avg_line_length': 36.20309810671257, 'alnum_prop': 0.670676048302748, 'repo_name': 'object/Simple.OData.Client', 'id': 'a1f721d8399421f8b12de41b13b2b787fd8d0cdf', 'size': '21036', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Simple.OData.Client.Core/Fluent/IFluentClient.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '121'}, {'name': 'Batchfile', 'bytes': '922'}, {'name': 'C#', 'bytes': '1431079'}, {'name': 'F#', 'bytes': '2482'}, {'name': 'HTML', 'bytes': '9122'}, {'name': 'PowerShell', 'bytes': '394'}]} |
import abc
import logging
from django.db import models
from django.utils import timezone
from osf.exceptions import ValidationValueError, ValidationTypeError
from osf.utils.datetime_aware_jsonfield import DateTimeAwareJSONField
from osf.utils.fields import NonNaiveDateTimeField
from osf.utils import akismet
from website import settings
logger = logging.getLogger(__name__)
def _get_client():
"""
AKISMET_APIKEY should be `None` for local testing.
:return:
"""
return akismet.AkismetClient(
apikey=settings.AKISMET_APIKEY,
website=settings.DOMAIN,
verify=bool(settings.AKISMET_APIKEY)
)
def _validate_reports(value, *args, **kwargs):
from osf.models import OSFUser
for key, val in value.items():
if not OSFUser.load(key):
raise ValidationValueError('Keys must be user IDs')
if not isinstance(val, dict):
raise ValidationTypeError('Values must be dictionaries')
if ('category' not in val or 'text' not in val or 'date' not in val or 'retracted' not in val):
raise ValidationValueError(
('Values must include `date`, `category`, ',
'`text`, `retracted` keys')
)
class SpamStatus(object):
UNKNOWN = None
FLAGGED = 1
SPAM = 2
HAM = 4
class SpamMixin(models.Model):
"""Mixin to add to objects that can be marked as spam.
"""
class Meta:
abstract = True
# # Node fields that trigger an update to search on save
# SPAM_UPDATE_FIELDS = {
# 'spam_status',
# }
spam_status = models.IntegerField(default=SpamStatus.UNKNOWN, null=True, blank=True, db_index=True)
spam_pro_tip = models.CharField(default=None, null=True, blank=True, max_length=200)
# Data representing the original spam indication
# - author: author name
# - author_email: email of the author
# - content: data flagged
# - headers: request headers
# - Remote-Addr: ip address from request
# - User-Agent: user agent from request
# - Referer: referrer header from request (typo +1, rtd)
spam_data = DateTimeAwareJSONField(default=dict, blank=True)
date_last_reported = NonNaiveDateTimeField(default=None, null=True, blank=True, db_index=True)
# Reports is a dict of reports keyed on reporting user
# Each report is a dictionary including:
# - date: date reported
# - retracted: if a report has been retracted
# - category: What type of spam does the reporter believe this is
# - text: Comment on the comment
reports = DateTimeAwareJSONField(
default=dict, blank=True, validators=[_validate_reports]
)
def flag_spam(self):
# If ham and unedited then tell user that they should read it again
if self.spam_status == SpamStatus.UNKNOWN:
self.spam_status = SpamStatus.FLAGGED
def remove_flag(self, save=False):
if self.spam_status != SpamStatus.FLAGGED:
return
for report in self.reports.values():
if not report.get('retracted', True):
return
self.spam_status = SpamStatus.UNKNOWN
if save:
self.save()
@property
def is_spam(self):
return self.spam_status == SpamStatus.SPAM
@property
def is_spammy(self):
return self.spam_status in [SpamStatus.FLAGGED, SpamStatus.SPAM]
def report_abuse(self, user, save=False, **kwargs):
"""Report object is spam or other abuse of OSF
:param user: User submitting report
:param save: Save changes
:param kwargs: Should include category and message
:raises ValueError: if user is reporting self
"""
if user == self.user:
raise ValueError('User cannot report self.')
self.flag_spam()
date = timezone.now()
report = {'date': date, 'retracted': False}
report.update(kwargs)
if 'text' not in report:
report['text'] = None
self.reports[user._id] = report
self.date_last_reported = report['date']
if save:
self.save()
def retract_report(self, user, save=False):
"""Retract last report by user
Only marks the last report as retracted because there could be
history in how the object is edited that requires a user
to flag or retract even if object is marked as HAM.
:param user: User retracting
:param save: Save changes
"""
if user._id in self.reports:
if not self.reports[user._id]['retracted']:
self.reports[user._id]['retracted'] = True
self.remove_flag()
else:
raise ValueError('User has not reported this content')
if save:
self.save()
def confirm_ham(self, save=False):
# not all mixins will implement check spam pre-req, only submit ham when it was incorrectly flagged
if (
settings.SPAM_CHECK_ENABLED and
self.spam_data and self.spam_status in [SpamStatus.FLAGGED, SpamStatus.SPAM]
):
client = _get_client()
client.submit_ham(
user_ip=self.spam_data['headers']['Remote-Addr'],
user_agent=self.spam_data['headers'].get('User-Agent'),
referrer=self.spam_data['headers'].get('Referer'),
comment_content=self.spam_data['content'],
comment_author=self.spam_data['author'],
comment_author_email=self.spam_data['author_email'],
)
logger.info('confirm_ham update sent')
self.spam_status = SpamStatus.HAM
if save:
self.save()
def confirm_spam(self, save=False):
# not all mixins will implement check spam pre-req, only submit spam when it was incorrectly flagged
if (
settings.SPAM_CHECK_ENABLED and
self.spam_data and self.spam_status in [SpamStatus.UNKNOWN, SpamStatus.HAM]
):
client = _get_client()
client.submit_spam(
user_ip=self.spam_data['headers']['Remote-Addr'],
user_agent=self.spam_data['headers'].get('User-Agent'),
referrer=self.spam_data['headers'].get('Referer'),
comment_content=self.spam_data['content'],
comment_author=self.spam_data['author'],
comment_author_email=self.spam_data['author_email'],
)
logger.info('confirm_spam update sent')
self.spam_status = SpamStatus.SPAM
if save:
self.save()
@abc.abstractmethod
def check_spam(self, user, saved_fields, request_headers, save=False):
"""Must return is_spam"""
pass
def do_check_spam(self, author, author_email, content, request_headers, update=True):
if self.spam_status == SpamStatus.HAM:
return False
if self.is_spammy:
return True
client = _get_client()
remote_addr = request_headers['Remote-Addr']
user_agent = request_headers.get('User-Agent')
referer = request_headers.get('Referer')
is_spam, pro_tip = client.check_comment(
user_ip=remote_addr,
user_agent=user_agent,
referrer=referer,
comment_content=content,
comment_author=author,
comment_author_email=author_email
)
if update:
self.spam_pro_tip = pro_tip
self.spam_data['headers'] = {
'Remote-Addr': remote_addr,
'User-Agent': user_agent,
'Referer': referer,
}
self.spam_data['content'] = content
self.spam_data['author'] = author
self.spam_data['author_email'] = author_email
if is_spam:
self.flag_spam()
return is_spam
| {'content_hash': '2cf3af3f7a99a0d9ab3d3e1b80e847ac', 'timestamp': '', 'source': 'github', 'line_count': 221, 'max_line_length': 108, 'avg_line_length': 35.90497737556561, 'alnum_prop': 0.6025204788909893, 'repo_name': 'baylee-d/osf.io', 'id': '1281073a681ad09b6b63d34a6c1058aef2bc1454', 'size': '7935', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'osf/models/spam.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '92773'}, {'name': 'Dockerfile', 'bytes': '5721'}, {'name': 'HTML', 'bytes': '318459'}, {'name': 'JavaScript', 'bytes': '1792442'}, {'name': 'Jupyter Notebook', 'bytes': '41326'}, {'name': 'Mako', 'bytes': '654930'}, {'name': 'Python', 'bytes': '10662092'}, {'name': 'VCL', 'bytes': '13885'}]} |
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
namespace BoderlessFun
{
public partial class MainWindow : Window
{
private Dictionary<int, string> _processes;
public MainWindow()
{
InitializeComponent();
LoadProcesses();
}
private void LoadProcesses()
{
ddlProcesses.Items.Clear();
_processes = new Dictionary<int, string>();
foreach (Process p in Process.GetProcesses().OrderBy(x => x.ProcessName))
{
if (p.Id == 0 || p.Id == 4) continue;
ddlProcesses.Items.Add(new ComboBoxItem() { Content = p.Id + " - " + p.ProcessName, Tag = p });
}
ddlScreen.ItemsSource = System.Windows.Forms.Screen.AllScreens.Select(x => x.DeviceName);
}
private void btnReloadProcesses_Click(object sender, RoutedEventArgs e)
{
LoadProcesses();
}
private void btnSetBorderless_Click(object sender, RoutedEventArgs e)
{
Process p = GetProcessFromDDL();
if (p == null) return;
WinAPIClasses.WinAPIHelper.SetBorderless(p, App.DoResize, App.MoveToScreen);
UpdateButtons(p);
}
private void btnUnsetBorderless_Click(object sender, RoutedEventArgs e)
{
Process p = GetProcessFromDDL();
if (p == null) return;
WinAPIClasses.WinAPIHelper.UnsetBorderless(p, App.DoResize, App.MoveToScreen);
UpdateButtons(p);
}
private void ddlProcesses_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
UpdateButtons(GetProcessFromDDL());
}
private void btnAddAutoBorderless_Click(object sender, RoutedEventArgs e)
{
Process p = GetProcessFromDDL();
if (p == null) return;
WinAPIClasses.ShellHook.AddAutoBorderless(GetProcessFilename(p));
UpdateButtons(p);
}
private void btnRemoveAutoBorderless_Click(object sender, RoutedEventArgs e)
{
Process p = GetProcessFromDDL();
if (p == null) return;
WinAPIClasses.ShellHook.RemoveAutoBorderless(GetProcessFilename(p));
UpdateButtons(p);
}
private Process GetProcessFromDDL()
{
ComboBoxItem item = ddlProcesses.SelectedItem as ComboBoxItem;
if (item == null || string.IsNullOrWhiteSpace(item.Content.ToString())) return null;
return item.Tag as Process;
}
private void UpdateButtons(Process p)
{
bool borderless = false, isAuto = false;
bool disableAll = p == null;
if (!disableAll)
{
borderless = WinAPIClasses.WinAPIHelper.IsBorderless(p);
isAuto = WinAPIClasses.ShellHook.IsAutoBorderlessFilename(GetProcessFilename(p));
}
UpdateButtons(disableAll, borderless, isAuto);
}
private void UpdateButtons(bool disableAll, bool borderless, bool isAuto)
{
btnSetBorderless.IsEnabled = !disableAll && !borderless;
btnUnsetBorderless.IsEnabled = !disableAll && borderless;
btnAddAutoBorderless.IsEnabled = !disableAll && WinAPIClasses.ShellHook.IsRegistered && !isAuto;
btnRemoveAutoBorderless.IsEnabled = !disableAll && WinAPIClasses.ShellHook.IsRegistered && isAuto;
}
private string GetProcessFilename(Process p)
{
if (p == null) return null;
try
{
return p.MainModule.ModuleName;
}
catch
{
return null;
}
}
private void rbResize_Checked(object sender, RoutedEventArgs e)
{
if (!this.IsInitialized) return;
if (rbDontResize.IsChecked.Value)
App.DoResize = false;
else if (rbResize.IsChecked.Value)
App.DoResize = true;
}
private void ddlScreen_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ddlScreen.SelectedIndex < Screen.AllScreens.Count())
{
App.MoveToScreen = Screen.AllScreens[ddlScreen.SelectedIndex];
}
}
}
} | {'content_hash': 'e6b4db3f60d6f8da3ed01818a48aed86', 'timestamp': '', 'source': 'github', 'line_count': 131, 'max_line_length': 111, 'avg_line_length': 34.282442748091604, 'alnum_prop': 0.5842796704520151, 'repo_name': 'hiiru/lab', 'id': '567f708888551e0567093f51b5eeeafddc63a6c5', 'size': '4493', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'BoderlessFun/BoderlessFun/MainWindow.xaml.cs', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []} |
from __future__ import print_function
def donuts(count):
if count < 10:
count_str = str(count)
else:
count_str = 'many'
return 'Number of donuts: {0}'.format(count_str)
# B. both_ends
# Given a string s, return a string made of the first 2
# and the last 2 chars of the original string,
# so 'spring' yields 'spng'. However, if the string length
# is less than 2, return instead the empty string.
def both_ends(s):
if len(s) < 2:
return ""
else:
return s[:2] + s[-2:]
# C. fix_start
# Given a string s, return a string
# where all occurences of its first char have
# been changed to '*', except do not change
# the first char itself.
# e.g. 'babble' yields 'ba**le'
# Assume that the string is length 1 or more.
# Hint: s.replace(stra, strb) returns a version of string s
# where all instances of stra have been replaced by strb.
def fix_start(s):
new_s = s.replace(s[0], '*')
return s[0] + new_s[1:]
# D. MixUp
# Given strings a and b, return a single string with a and b separated
# by a space '<a> <b>', except swap the first 2 chars of each string.
# e.g.
# 'mix', pod' -> 'pox mid'
# 'dog', 'dinner' -> 'dig donner'
# Assume a and b are length 2 or more.
def mix_up(a, b):
return '{0}{1} {2}{3}'.format(b[:2], a[2:], a[:2], b[2:])
# Provided simple test() function used in main() to print
# what each function returns vs. what it's supposed to return.
def test(got, expected):
if got == expected:
prefix = ' OK '
else:
prefix = ' X '
print('%s got: %s expected: %s' % (prefix, repr(got), repr(expected)))
# Provided main() calls the above functions with interesting inputs,
# using test() to check if each result is correct or not.
def main():
print('donuts')
# Each line calls donuts, compares its result to the expected for that call.
test(donuts(4), 'Number of donuts: 4')
test(donuts(9), 'Number of donuts: 9')
test(donuts(10), 'Number of donuts: many')
test(donuts(99), 'Number of donuts: many')
print()
print('both_ends')
test(both_ends('spring'), 'spng')
test(both_ends('Hello'), 'Helo')
test(both_ends('a'), '')
test(both_ends('xyz'), 'xyyz')
print()
print('fix_start')
test(fix_start('babble'), 'ba**le')
test(fix_start('aardvark'), 'a*rdv*rk')
test(fix_start('google'), 'goo*le')
test(fix_start('donut'), 'donut')
print()
print('mix_up')
test(mix_up('mix', 'pod'), 'pox mid')
test(mix_up('dog', 'dinner'), 'dig donner')
test(mix_up('gnash', 'sport'), 'spash gnort')
test(mix_up('pezzy', 'firm'), 'fizzy perm')
# Standard boilerplate to call the main() function.
if __name__ == '__main__':
main()
| {'content_hash': '69dc3395d5288e276fbff776f6bed376', 'timestamp': '', 'source': 'github', 'line_count': 94, 'max_line_length': 80, 'avg_line_length': 29.0, 'alnum_prop': 0.6126192223037418, 'repo_name': 'dynaryu/google-python-excercise', 'id': 'dcff5561b3f82d534fd7bf37c5f0e54edf33021b', 'size': '3716', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'basic/string1.py', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'DIGITAL Command Language', 'bytes': '191608'}, {'name': 'HTML', 'bytes': '647778'}, {'name': 'Python', 'bytes': '25887'}]} |
=pod
Task worker - design 2
Adds pub-sub flow to receive and respond to kill signal
Author: Alexander D'Archangel (darksuji) <darksuji(at)gmail(dot)com>
=cut
use strict;
use warnings;
use 5.10.0;
use IO::Handle;
use ZeroMQ qw/:all/;
use Time::HiRes qw/nanosleep/;
use constant NSECS_PER_MSEC => 1_000_000;
my $context = ZeroMQ::Context->new();
# Socket to receive messages on
my $receiver = $context->socket(ZMQ_PULL);
$receiver->connect('tcp://localhost:5557');
# Socket to send messages to
my $sender = $context->socket(ZMQ_PUSH);
$sender->connect('tcp://localhost:5558');
# Socket for control input
my $controller = $context->socket(ZMQ_SUB);
$controller->connect('tcp://localhost:5559');
$controller->setsockopt(ZMQ_SUBSCRIBE, '');
# Process messages from receiver and controller
my $poller = ZeroMQ::Poller->new(
{
name => 'receiver',
socket => $receiver,
events => ZMQ_POLLIN,
}, {
name => 'controller',
socket => $controller,
events => ZMQ_POLLIN,
},
);
# Process messages from both sockets
while (1) {
$poller->poll();
if ( $poller->has_event('receiver') ) {
my $message = $receiver->recv();
# Process task
my $workload = $message->data * NSECS_PER_MSEC;
# Do the work
nanosleep $workload;
# Send results to sink
$sender->send('');
# Simple progress indicator for the viewer
STDOUT->printflush('.');
}
# Any waiting controller command acts as 'KILL'
last if $poller->has_event('controller');
}
# Finished
| {'content_hash': 'd2ee1f00a88dcb355d96a30394d2c68e', 'timestamp': '', 'source': 'github', 'line_count': 71, 'max_line_length': 68, 'avg_line_length': 22.43661971830986, 'alnum_prop': 0.6258631512868801, 'repo_name': 'krattai/noo-ebs', 'id': 'ba7ff370b984d7ab39bb47ec7cf124f9da622b26', 'size': '1609', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/zeroMQ-guide2/examples/Perl/taskwork2.pl', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'ActionScript', 'bytes': '2384'}, {'name': 'Assembly', 'bytes': '4590201'}, {'name': 'Awk', 'bytes': '396'}, {'name': 'Batchfile', 'bytes': '19241'}, {'name': 'C', 'bytes': '15563482'}, {'name': 'C#', 'bytes': '265955'}, {'name': 'C++', 'bytes': '691846'}, {'name': 'CMake', 'bytes': '104078'}, {'name': 'CSS', 'bytes': '72772'}, {'name': 'DTrace', 'bytes': '1258'}, {'name': 'Erlang', 'bytes': '4424888'}, {'name': 'GAP', 'bytes': '1517'}, {'name': 'HTML', 'bytes': '65461'}, {'name': 'Haxe', 'bytes': '6282'}, {'name': 'Java', 'bytes': '6899'}, {'name': 'JavaScript', 'bytes': '494026'}, {'name': 'Lua', 'bytes': '274783'}, {'name': 'M4', 'bytes': '107581'}, {'name': 'Makefile', 'bytes': '143161'}, {'name': 'NSIS', 'bytes': '27658'}, {'name': 'Objective-C', 'bytes': '13321'}, {'name': 'PHP', 'bytes': '43263'}, {'name': 'PLpgSQL', 'bytes': '80625'}, {'name': 'Perl', 'bytes': '344546'}, {'name': 'Python', 'bytes': '500718'}, {'name': 'QML', 'bytes': '150'}, {'name': 'QMake', 'bytes': '3028'}, {'name': 'Ragel', 'bytes': '46210'}, {'name': 'Roff', 'bytes': '120721'}, {'name': 'Ruby', 'bytes': '121530'}, {'name': 'Shell', 'bytes': '293349'}, {'name': 'TeX', 'bytes': '788237'}, {'name': 'XSLT', 'bytes': '1459'}, {'name': 'Yacc', 'bytes': '5139'}]} |
import System.Posix.Process(forkProcess, getAnyProcessStatus)
import System.Posix.Signals(signalProcess, sigKILL)
import System.Posix.Types(ProcessID)
import Network.Socket
import System.Exit(exitSuccess)
import Data.Maybe(Maybe(..))
import System.Posix.Signals(installHandler, Handler(..), sigINT)
import Control.Monad(forever, forM)
processPoolSize :: Int
processPoolSize = 5
main :: IO ()
main = do
listeningSocket <- setupSocket 3001
pids <- forM [1..processPoolSize] $ \num ->
forkProcess (runServer num listeningSocket)
installHandler sigINT (Catch (killChildren pids >> exitSuccess)) Nothing
monitorProcesses
killChildren :: [ProcessID] -> IO ()
killChildren = mapM_ (signalProcess sigKILL)
monitorProcesses :: IO ()
monitorProcesses = do
mpid <- getAnyProcessStatus True True
case mpid of
Just (pid, status) -> do
putStrLn $ "Process" ++ show pid ++ " quit unexpectedly\n\n"
monitorProcesses
Nothing -> do
putStrLn "No processes have exited\n"
monitorProcesses
setupSocket :: PortNumber -> IO Socket
setupSocket port = do
s <- socket AF_INET Stream defaultProtocol
bind s (SockAddrInet port 0) >> listen s 5
setSocketOption s ReuseAddr 1
return s
runServer :: Int -> Socket -> IO ()
runServer num socket =
forever $ do
(connection, _) <- accept socket
msg <- recv connection 1024
send connection $ "Received Connection in process Number" ++ show num ++ "\n\n"
send connection $ "\n Echo..." ++ msg
close connection
| {'content_hash': 'a41101f1deb48042d7e9630b73dc99f3', 'timestamp': '', 'source': 'github', 'line_count': 49, 'max_line_length': 83, 'avg_line_length': 31.0, 'alnum_prop': 0.7103357472021067, 'repo_name': 'jvans1/haskell_servers', 'id': '4c42bd3282a56ffa8239e17e0acc30fe234b7c6c', 'size': '1519', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/ProcessPool.hs', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Haskell', 'bytes': '9823'}]} |
require "rails_helper"
describe Case::SAR::OffenderDecorator do
let(:offender_sar_case) {
build_stubbed(
:offender_sar_case,
date_responded: Date.new(2020, 1, 10),
received_date: Date.new(2020, 1, 1)).decorate
}
it 'instantiates the correct decorator' do
expect(Case::SAR::Offender.new.decorate).to be_instance_of Case::SAR::OffenderDecorator
end
describe "#current_step" do
it "returns the first step by default" do
expect(offender_sar_case.current_step).to eq "subject-details"
end
end
describe "#next_step" do
it "causes #current_step to return the next step" do
offender_sar_case.next_step
expect(offender_sar_case.current_step).to eq "requester-details"
end
end
describe "#get_step_partial" do
it "returns the first step as default filename" do
expect(offender_sar_case.get_step_partial).to eq "subject_details_step"
end
it "returns each subsequent step as a partial filename" do
expect(offender_sar_case.get_step_partial).to eq "subject_details_step"
offender_sar_case.next_step
expect(offender_sar_case.get_step_partial).to eq "requester_details_step"
offender_sar_case.next_step
expect(offender_sar_case.get_step_partial).to eq "recipient_details_step"
offender_sar_case.next_step
expect(offender_sar_case.get_step_partial).to eq "requested_info_step"
offender_sar_case.next_step
expect(offender_sar_case.get_step_partial).to eq "request_details_step"
offender_sar_case.next_step
expect(offender_sar_case.get_step_partial).to eq "date_received_step"
end
end
describe "#time_taken" do
it "returns total number of days between date received and date responded" do
expect(offender_sar_case.time_taken).to eq "9 calendar days"
end
end
describe '#type_printer' do
it 'pretty prints Case' do
expect(offender_sar_case.pretty_type).to eq 'Offender SAR'
end
end
describe '#request_methods_sorted' do
it 'returns an ordered request methods list of options' do
expect(offender_sar_case.request_methods_sorted).to eq %w[email post unknown web_portal]
end
end
describe '#request_method_for_display' do
it 'does not return the "unknown" request method' do
expect(offender_sar_case.request_methods_for_display).to match_array %w[email post web_portal]
end
it 'returns an ordered request methods list of options for display' do
expect(offender_sar_case.request_methods_for_display).to eq %w[email post web_portal]
end
end
end
| {'content_hash': 'b36f3a55a1627275ae89478035eb16fd', 'timestamp': '', 'source': 'github', 'line_count': 77, 'max_line_length': 100, 'avg_line_length': 33.57142857142857, 'alnum_prop': 0.702514506769826, 'repo_name': 'ministryofjustice/correspondence_tool_staff', 'id': '0293d3a1e52202a4094b22e76d60fef622821e9b', 'size': '2585', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'spec/decorators/case/offender_sar_decorator_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '383'}, {'name': 'Dockerfile', 'bytes': '1559'}, {'name': 'HTML', 'bytes': '83918'}, {'name': 'JavaScript', 'bytes': '50629'}, {'name': 'Procfile', 'bytes': '174'}, {'name': 'Python', 'bytes': '5159'}, {'name': 'Ruby', 'bytes': '4621757'}, {'name': 'SCSS', 'bytes': '38011'}, {'name': 'Shell', 'bytes': '11912'}, {'name': 'Slim', 'bytes': '253831'}]} |
namespace T3000Controls
{
using System;
using System.Windows.Forms;
internal class TransparentLabel : Label
{
protected override void WndProc(ref Message m)
{
const int WM_NCHITTEST = 0x0084;
const int HTTRANSPARENT = (-1);
if (m.Msg == WM_NCHITTEST)
{
m.Result = (IntPtr)HTTRANSPARENT;
}
else
{
base.WndProc(ref m);
}
}
}
}
| {'content_hash': 'd2f87e9b11c67524e85c74539692d750', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 54, 'avg_line_length': 20.875, 'alnum_prop': 0.4750499001996008, 'repo_name': 'temcocontrols/T3000_Building_Automation_System', 'id': 'a8108be4c56c5272f352f75166f1e46b08121296', 'size': '503', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'T3000Controls/Controls/TransparentLabel.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '555'}, {'name': 'C', 'bytes': '4704332'}, {'name': 'C#', 'bytes': '9337521'}, {'name': 'C++', 'bytes': '15665753'}, {'name': 'CMake', 'bytes': '169395'}, {'name': 'CSS', 'bytes': '111688'}, {'name': 'Dockerfile', 'bytes': '210'}, {'name': 'HTML', 'bytes': '125316'}, {'name': 'Inno Setup', 'bytes': '5879'}, {'name': 'JavaScript', 'bytes': '1789138'}, {'name': 'Makefile', 'bytes': '6851'}, {'name': 'Meson', 'bytes': '7623'}, {'name': 'NASL', 'bytes': '14427'}, {'name': 'Objective-C', 'bytes': '7094'}, {'name': 'Perl', 'bytes': '40922'}, {'name': 'PowerShell', 'bytes': '4726'}, {'name': 'Python', 'bytes': '1992'}, {'name': 'Shell', 'bytes': '143'}]} |
namespace AppDomainToolkit.UnitTests
{
using System;
using Xunit;
public class RemoteActionUnitTests
{
#region Test Methods
[Fact]
public void Invoke_NullDomain()
{
Assert.Throws(typeof(ArgumentNullException), () =>
{
RemoteAction.Invoke(null, () => { });
});
}
[Fact]
public void Invoke_NullFunction()
{
Assert.Throws(typeof(ArgumentNullException), () =>
{
using (var context = AppDomainContext.Create())
{
RemoteAction.Invoke(context.Domain, null);
}
});
}
[Fact]
public void Invoke_InstanceNoTypes_NullFunction()
{
Assert.Throws(typeof(ArgumentNullException), () =>
{
var action = new RemoteAction();
action.Invoke(null);
});
}
[Fact]
public void Invoke_InstanceOneType_NullFunction()
{
Assert.Throws(typeof(ArgumentNullException), () =>
{
var action = new RemoteAction<int>();
action.Invoke(1, null);
});
}
[Fact]
public void Invoke_InstanceTwoTypes_NullFunction()
{
Assert.Throws(typeof(ArgumentNullException), () =>
{
var action = new RemoteAction<int, int>();
action.Invoke(1, 2, null);
});
}
[Fact]
public void Invoke_InstanceThreeTypes_NullFunction()
{
Assert.Throws(typeof(ArgumentNullException), () =>
{
var action = new RemoteAction<int, int, int>();
action.Invoke(1, 2, 3, null);
});
}
[Fact]
public void Invoke_InstanceFourTypes_NullFunction()
{
Assert.Throws(typeof(ArgumentNullException), () =>
{
var action = new RemoteAction<int, int, int, int>();
action.Invoke(1, 2, 3, 4, null);
});
}
[Fact]
public void Invoke_MarshalObjectByRef_NoArguments()
{
using (var context = AppDomainContext.Create())
{
RemoteAction.Invoke(context.Domain, () => { });
}
}
[Fact]
public void Invoke_MarshalObjectByRef_OneArg()
{
using (var context = AppDomainContext.Create())
{
var actual = new Test();
RemoteAction.Invoke(
context.Domain,
actual,
(test) =>
{
test.Value1 = 10;
});
Assert.NotNull(actual);
Assert.Equal(10, actual.Value1);
}
}
[Fact]
public void Invoke_MarshalObjectByRef_TwoArg()
{
using (var context = AppDomainContext.Create())
{
var actual = new Test();
RemoteAction.Invoke(
context.Domain,
actual,
(short)11,
(test, value2) =>
{
test.Value1 = 10;
test.Value2 = value2;
});
Assert.NotNull(actual);
Assert.Equal(10, actual.Value1);
Assert.Equal(11, actual.Value2);
}
}
[Fact]
public void Invoke_MarshalObjectByRef_ThreeArg()
{
using (var context = AppDomainContext.Create())
{
var actual = new Test();
RemoteAction.Invoke(
context.Domain,
actual,
(short)11,
new Double?(12.0),
(test, value2, value3) =>
{
test.Value1 = 10;
test.Value2 = value2;
test.Value3 = value3;
});
Assert.NotNull(actual);
Assert.Equal(10, actual.Value1);
Assert.Equal(11, actual.Value2);
Assert.Equal(12.0, actual.Value3);
}
}
[Fact]
public void Invoke_MarshalObjectByRef_FourArg()
{
using (var context = AppDomainContext.Create())
{
var actual = new Test();
RemoteAction.Invoke(
context.Domain,
actual,
(short)11,
new Double?(12.0),
new Composite() { Value = 13 },
(test, value2, value3, value4) =>
{
test.Value1 = 10;
test.Value2 = value2;
test.Value3 = value3;
test.Value4 = value4;
});
Assert.NotNull(actual);
Assert.Equal(10, actual.Value1);
Assert.Equal(11, actual.Value2);
Assert.Equal(12.0, actual.Value3);
Assert.NotNull(actual.Value4);
Assert.Equal(13, actual.Value4.Value);
}
}
#endregion
#region Inner Classes
private class Test : MarshalByRefObject
{
#region Constructors & Destructors
public Test()
{
}
#endregion
#region Properties
public int Value1 { get; set; }
public short Value2 { get; set; }
public Double? Value3 { get; set; }
public Composite Value4 { get; set; }
#endregion
}
private class Composite : MarshalByRefObject
{
#region Constructors & Destructors
public Composite()
{
}
#endregion
#region Properties
public short Value { get; set; }
#endregion
}
#endregion
}
} | {'content_hash': '0f0e8bc220fc0b24d8c2ffdbad288658', 'timestamp': '', 'source': 'github', 'line_count': 230, 'max_line_length': 68, 'avg_line_length': 28.234782608695653, 'alnum_prop': 0.410378811210348, 'repo_name': 'jduv/AppDomainToolkit', 'id': '73c253d7f2ffca9aba895b41e91ee2a2ddc0243a', 'size': '6496', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'AppDomainToolkit.UnitTests/RemoteActionUnitTests.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '166351'}]} |
package tiff66
import (
"bytes"
"encoding/binary"
"errors"
"strings"
)
// Identify a maker note and return its TagSpace, or TagSpace(0) if not found.
func identifyMakerNote(buf []byte, pos uint32, make, model string) TagSpace {
var space TagSpace
lcMake := strings.ToLower(make)
switch {
case bytes.HasPrefix(buf[pos:], fujifilm1Label):
space = Fujifilm1Space
case bytes.HasPrefix(buf[pos:], generaleLabel):
space = Fujifilm1Space
case bytes.HasPrefix(buf[pos:], nikon1Label):
space = Nikon1Space
case bytes.HasPrefix(buf[pos:], nikon2LabelPrefix):
space = Nikon2Space
case bytes.HasPrefix(buf[pos:], panasonic1Label):
space = Panasonic1Space
default:
for i := range olympus1Labels {
if bytes.HasPrefix(buf[pos:], olympus1Labels[i].prefix) {
space = Olympus1Space
}
}
if space == TagSpace(0) {
for i := range sony1Labels {
if bytes.HasPrefix(buf[pos:], sony1Labels[i]) {
space = Sony1Space
}
}
}
// If no maker note label was recognized above, assume
// the maker note is appropriate for the camera make
// and/or model.
if space == TagSpace(0) {
switch {
case strings.HasPrefix(lcMake, "nikon"):
space = Nikon2Space
case strings.HasPrefix(lcMake, "canon"):
space = Canon1Space
}
}
}
return space
}
// Given a buffer pointing to a an IFD entry count, guess the byte
// order of the IFD. The number of entries is usually small,
// usually less than 256.
func detectByteOrder(buf []byte) binary.ByteOrder {
big := binary.BigEndian.Uint16(buf)
little := binary.LittleEndian.Uint16(buf)
if little < big {
return binary.LittleEndian
} else {
return binary.BigEndian
}
}
// SpaceRec for Canon1 maker notes.
type Canon1SpaceRec struct {
}
func (*Canon1SpaceRec) GetSpace() TagSpace {
return Canon1Space
}
func (*Canon1SpaceRec) IsMakerNote() bool {
return true
}
func (*Canon1SpaceRec) nodeSize(node IFDNode) uint32 {
return node.genericSize()
}
func (*Canon1SpaceRec) takeField(buf []byte, order binary.ByteOrder, ifdPositions posMap, idx uint16, field Field, dataPos uint32) ([]SubIFD, error) {
return nil, nil
}
func (*Canon1SpaceRec) getIFDTree(node *IFDNode, buf []byte, pos uint32, ifdPositions posMap) error {
return node.genericGetIFDTreeIter(buf, pos, ifdPositions)
}
func (*Canon1SpaceRec) getFooter(node *IFDNode, buf []byte, pos uint32, ifdPositions posMap) error {
return node.unexpectedFooter(buf, pos, ifdPositions)
}
func (*Canon1SpaceRec) putIFDTree(node IFDNode, buf []byte, pos uint32) (uint32, error) {
return node.genericPutIFDTree(buf, pos)
}
func (*Canon1SpaceRec) GetImageData() []ImageData {
return nil
}
// SpaceRec for Fujifilm1 maker notes.
type Fujifilm1SpaceRec struct {
label []byte
}
func (*Fujifilm1SpaceRec) GetSpace() TagSpace {
return Fujifilm1Space
}
func (*Fujifilm1SpaceRec) IsMakerNote() bool {
return true
}
var fujifilm1Label = []byte("FUJIFILM")
var generaleLabel = []byte("GENERALE") // GE E1255W
func (rec *Fujifilm1SpaceRec) nodeSize(node IFDNode) uint32 {
// Label, IFD position, and IFD.
return uint32(len(rec.label)) + 4 + node.genericSize()
}
func (*Fujifilm1SpaceRec) takeField(buf []byte, order binary.ByteOrder, ifdPositions posMap, idx uint16, field Field, dataPos uint32) ([]SubIFD, error) {
return nil, nil
}
func (rec *Fujifilm1SpaceRec) getIFDTree(node *IFDNode, buf []byte, pos uint32, ifdPositions posMap) error {
// Offsets are relative to start of the makernote.
tiff := buf[pos:]
if bytes.HasPrefix(tiff, fujifilm1Label) {
rec.label = append([]byte{}, fujifilm1Label...)
} else if bytes.HasPrefix(tiff, generaleLabel) {
rec.label = append([]byte{}, generaleLabel...)
} else {
// Shouldn't reach this point if we already know it's a Fujifilm1SpaceRec.
return errors.New("Invalid label for Fujifilm1 maker note")
}
// Must be read as little-endian, even if the Exif block is
// big endian (as in Leica digilux 4.3).
node.Order = binary.LittleEndian
// Only the 2nd half of the TIFF header is present, the position
// of the IFD.
pos = node.Order.Uint32(tiff[len(rec.label):])
return node.genericGetIFDTreeIter(tiff, pos, ifdPositions)
}
func (*Fujifilm1SpaceRec) getFooter(node *IFDNode, buf []byte, pos uint32, ifdPositions posMap) error {
return node.unexpectedFooter(buf, pos, ifdPositions)
}
func (rec *Fujifilm1SpaceRec) putIFDTree(node IFDNode, buf []byte, pos uint32) (uint32, error) {
tiff := buf[pos:]
copy(tiff, rec.label)
lablen := uint32(len(rec.label))
start := lablen + 4
node.Order.PutUint32(tiff[lablen:], start)
next, err := node.genericPutIFDTree(tiff, start)
if err != nil {
return 0, err
}
return pos + next, nil
}
func (*Fujifilm1SpaceRec) GetImageData() []ImageData {
return nil
}
// SpaceRec for Nikon1 maker notes.
type Nikon1SpaceRec struct {
}
func (*Nikon1SpaceRec) GetSpace() TagSpace {
return Nikon1Space
}
func (*Nikon1SpaceRec) IsMakerNote() bool {
return true
}
var nikon1Label = []byte("Nikon\000\001\000")
func (*Nikon1SpaceRec) nodeSize(node IFDNode) uint32 {
return uint32(len(nikon1Label)) + node.genericSize()
}
func (*Nikon1SpaceRec) takeField(buf []byte, order binary.ByteOrder, ifdPositions posMap, idx uint16, field Field, dataPos uint32) ([]SubIFD, error) {
return nil, nil
}
func (*Nikon1SpaceRec) getIFDTree(node *IFDNode, buf []byte, pos uint32, ifdPositions posMap) error {
return node.genericGetIFDTreeIter(buf, pos+uint32(len(nikon1Label)), ifdPositions)
}
func (*Nikon1SpaceRec) getFooter(node *IFDNode, buf []byte, pos uint32, ifdPositions posMap) error {
return node.unexpectedFooter(buf, pos, ifdPositions)
}
func (*Nikon1SpaceRec) putIFDTree(node IFDNode, buf []byte, pos uint32) (uint32, error) {
copy(buf[pos:], nikon1Label)
pos += uint32(len(nikon1Label))
return node.genericPutIFDTree(buf, pos)
}
func (*Nikon1SpaceRec) GetImageData() []ImageData {
return nil
}
// Fields in Nikon2 IFD.
const nikon2PreviewIFD = 0x11
const nikon2NikonScanIFD = 0xE10
// SpaceRec for Nikon2 maker notes.
type Nikon2SpaceRec struct {
// The maker note header/label varies, but the tags are
// compatible. Model examples:
// Coolpix 990: no header
// Coolpix 5000: "Nikon\0\2\0\0\0"
// Nikon D5100: "Nikon\0\2\x10\0\0"
// Nikon D500: "Nikon\0\2\x11\0\0"
label []byte
}
func (*Nikon2SpaceRec) GetSpace() TagSpace {
return Nikon2Space
}
func (*Nikon2SpaceRec) IsMakerNote() bool {
return true
}
var nikon2LabelPrefix = []byte("Nikon\000")
func (rec *Nikon2SpaceRec) nodeSize(node IFDNode) uint32 {
labelLen := len(rec.label)
if labelLen == 0 {
// maker note without label or TIFF header.
return node.genericSize()
}
return uint32(labelLen) + HeaderSize + node.genericSize()
}
func (*Nikon2SpaceRec) takeField(buf []byte, order binary.ByteOrder, ifdPositions posMap, idx uint16, field Field, dataPos uint32) ([]SubIFD, error) {
// SubIFDs.
if field.Type == IFD || field.Tag == nikon2PreviewIFD || field.Tag == nikon2NikonScanIFD {
subspace := Nikon2Space
if field.Tag == nikon2PreviewIFD {
subspace = Nikon2PreviewSpace
} else if field.Tag == nikon2NikonScanIFD {
subspace = Nikon2ScanSpace
}
return recurseSubIFDs(buf, order, ifdPositions, field, NewSpaceRec(subspace))
}
return nil, nil
}
func (rec *Nikon2SpaceRec) getIFDTree(node *IFDNode, buf []byte, pos uint32, ifdPositions posMap) error {
// A few early cameras like Coolpix 775 and 990 use the Nikon
// 2 tags, but encode the maker note without a label or TIFF
// header. If the label is present, the maker note contains a
// new TIFF block and uses relative offsets within the block.
if bytes.HasPrefix(buf[pos:], nikon2LabelPrefix) {
lablen := uint32(len(nikon2LabelPrefix) + 4)
rec.label = append([]byte{}, buf[pos:pos+lablen]...)
tiff := buf[pos+lablen:]
valid, order, pos := GetHeader(tiff)
if !valid {
return errors.New("TIFF header not found in Nikon2 maker note")
}
node.Order = order
return node.genericGetIFDTreeIter(tiff, pos, ifdPositions)
} else {
// Byte order may differ from Exif block.
node.Order = detectByteOrder(buf[pos:])
return node.genericGetIFDTreeIter(buf, pos, ifdPositions)
}
}
func (*Nikon2SpaceRec) getFooter(node *IFDNode, buf []byte, pos uint32, ifdPositions posMap) error {
return node.unexpectedFooter(buf, pos, ifdPositions)
}
func (rec *Nikon2SpaceRec) putIFDTree(node IFDNode, buf []byte, pos uint32) (uint32, error) {
if len(rec.label) == 0 {
// maker note without label or TIFF header.
return node.genericPutIFDTree(buf, pos)
}
copy(buf[pos:], rec.label)
pos += uint32(len(rec.label))
makerBuf := buf[pos:]
PutHeader(makerBuf, node.Order, HeaderSize)
next, err := node.genericPutIFDTree(makerBuf, HeaderSize)
if err != nil {
return 0, err
}
return pos + next, nil
}
func (rec *Nikon2SpaceRec) GetImageData() []ImageData {
return nil
}
const nikon2PreviewImageStart = 0x201
const nikon2PreviewImageLength = 0x202
// SpaceRec for Nikon2 Preview IFDs.
type Nikon2PreviewSpaceRec struct {
offsetField Field
lengthField Field
imageData []ImageData // May be used for preview image.
}
func (rec *Nikon2PreviewSpaceRec) GetSpace() TagSpace {
return Nikon2PreviewSpace
}
func (*Nikon2PreviewSpaceRec) IsMakerNote() bool {
return false
}
func (*Nikon2PreviewSpaceRec) nodeSize(node IFDNode) uint32 {
return node.genericSize()
}
// Store preview image in the space rec.
func (rec *Nikon2PreviewSpaceRec) appendImageData(buf []byte, order binary.ByteOrder, offsetField, sizeField Field) error {
imageData, err := newImageData(buf, order, offsetField, sizeField)
if err != nil {
return err
}
rec.imageData = append(rec.imageData, *imageData)
return nil
}
func (rec *Nikon2PreviewSpaceRec) takeField(buf []byte, order binary.ByteOrder, ifdPositions posMap, idx uint16, field Field, dataPos uint32) ([]SubIFD, error) {
// IFD fields aren't usually present in this IFD.
if field.Type == IFD {
return recurseSubIFDs(buf, order, ifdPositions, field, NewSpaceRec(Nikon2PreviewSpace))
}
if field.Tag == nikon2PreviewImageStart {
rec.offsetField = field
} else if field.Tag == nikon2PreviewImageLength {
rec.lengthField = field
}
if rec.offsetField.Tag != 0 && rec.lengthField.Tag != 0 {
rec.appendImageData(buf, order, rec.offsetField, rec.lengthField)
rec.offsetField.Tag = 0
rec.lengthField.Tag = 0
}
return nil, nil
}
func (*Nikon2PreviewSpaceRec) getIFDTree(node *IFDNode, buf []byte, pos uint32, ifdPositions posMap) error {
return node.genericGetIFDTreeIter(buf, pos, ifdPositions)
}
func (*Nikon2PreviewSpaceRec) getFooter(node *IFDNode, buf []byte, pos uint32, ifdPositions posMap) error {
return node.unexpectedFooter(buf, pos, ifdPositions)
}
func (*Nikon2PreviewSpaceRec) putIFDTree(node IFDNode, buf []byte, pos uint32) (uint32, error) {
return node.genericPutIFDTree(buf, pos)
}
func (rec *Nikon2PreviewSpaceRec) GetImageData() []ImageData {
return rec.imageData
}
// Fields in Olympus1 IFD.
const olympus1EquipmentIFD = 0x2010
const olympus1CameraSettingsIFD = 0x2020
const olympus1RawDevelopmentIFD = 0x2030
const olympus1RawDev2IFD = 0x2031
const olympus1ImageProcessingIFD = 0x2040
const olympus1FocusInfo = 0x2050
// The Olympus1 maker note header/label varies, but the tags are
// compatible. The older type is decoded with offsets relative to the
// start of the Tiff block and starts with "OLYMP\0" or other labels;
// the newer type is decoded relative to the start of the maker note
// and starts with ""OLYMPUS\000II".
var olympus1Labels = []struct {
prefix []byte // Identifying prefix of maker note label.
length uint32 // Full length of maker note label.
relative bool // True if offsets are relative to the start of the maker note, instead of the entire Tiff block.
}{
{[]byte("OLYMP\000"), 8, false}, // Many Olympus models.
{[]byte("OLYMPUS\000II"), 12, true}, // Many Olympus models.
{[]byte("SONY PI\000"), 12, false}, // Sony DSC-S650 etc.
{[]byte("PREMI\000"), 8, false}, // Sony DSC-S45, DSC-S500.
{[]byte("CAMER\000"), 8, false}, // Various Premier models, sometimes rebranded.
{[]byte("MINOL\000"), 8, false}, // Minolta DiMAGE E323.
}
// SpaceRec for Olympus1 maker notes.
type Olympus1SpaceRec struct {
label []byte
relative bool // True if offsets relative to start of maker note, instead of entire Tiff block.
}
func (*Olympus1SpaceRec) GetSpace() TagSpace {
return Olympus1Space
}
func (*Olympus1SpaceRec) IsMakerNote() bool {
return true
}
func (rec *Olympus1SpaceRec) nodeSize(node IFDNode) uint32 {
labelLen := len(rec.label)
return uint32(labelLen) + node.genericSize()
}
func (*Olympus1SpaceRec) takeField(buf []byte, order binary.ByteOrder, ifdPositions posMap, idx uint16, field Field, dataPos uint32) ([]SubIFD, error) {
// SubIFDs.
if field.Type == IFD || field.Tag == olympus1EquipmentIFD || field.Tag == olympus1CameraSettingsIFD || field.Tag == olympus1RawDevelopmentIFD || field.Tag == olympus1RawDev2IFD || field.Tag == olympus1ImageProcessingIFD || field.Tag == olympus1FocusInfo {
if field.Tag == olympus1FocusInfo && field.Type == UNDEFINED {
// Some camera models make this is an IFD, but in others it's just an array of data. Make a guess.
// The field size is often just the TableEntrySize times the number of entries
// in the table. I.e., it omits the table overhead and the external data.
if field.Size() < TableEntrySize {
// Too small to be an IFD.
return nil, nil
}
data := field.Data
entries := order.Uint16(data)
if entries == 0 {
// IFD should have entries.
return nil, nil
}
if field.Size() < uint32(entries)*TableEntrySize {
// Field is too small to be an IFD with the specified number of fields.
return nil, nil
}
end := dataPos + TableSize(entries)
if end < dataPos || end > uint32(len(buf)) {
// IFD with specified number of fields would run past end of buffer.
return nil, nil
}
check := uint16(3) // Check the types of the first fields, allow for slightly damaged IFDs.
if check > entries {
check = entries
}
for i := uint16(0); i < check; i++ {
typ := Type(order.Uint16(data[2+i*TableEntrySize+2:]))
if typ == 0 || typ > IFD {
// Not an offficial data type: probably not an IFD field.
return nil, nil
}
}
}
subspace := Olympus1Space
switch field.Tag {
case olympus1EquipmentIFD:
subspace = Olympus1EquipmentSpace
case olympus1CameraSettingsIFD:
subspace = Olympus1CameraSettingsSpace
case olympus1RawDevelopmentIFD:
subspace = Olympus1RawDevelopmentSpace
case olympus1RawDev2IFD:
subspace = Olympus1RawDev2Space
case olympus1ImageProcessingIFD:
subspace = Olympus1ImageProcessingSpace
case olympus1FocusInfo:
subspace = Olympus1FocusInfoSpace
}
var sub SubIFD
sub.Tag = field.Tag
var err error
// In newer maker notes, these fields are IFD type.
// In older maker notes, they are nominally arrays of
// UNDEFINED, but contain IFDs that point to data
// outside the arrays.
if field.Type == IFD {
return recurseSubIFDs(buf, order, ifdPositions, field, NewSpaceRec(subspace))
}
sub.Node, err = getIFDTreeIter(buf, order, dataPos, NewSpaceRec(subspace), ifdPositions)
return []SubIFD{sub}, err
}
return nil, nil
}
func (rec *Olympus1SpaceRec) getIFDTree(node *IFDNode, buf []byte, pos uint32, ifdPositions posMap) error {
for i := range olympus1Labels {
if bytes.HasPrefix(buf[pos:], olympus1Labels[i].prefix) {
rec.label = append([]byte{}, buf[pos:pos+olympus1Labels[i].length]...)
// Byte order varies by camera model, and may differ from Exif order.
node.Order = detectByteOrder(buf[pos+olympus1Labels[i].length:])
if olympus1Labels[i].relative {
// Offsets are relative to start of maker note.
tiff := buf[pos:]
rec.relative = true
return node.genericGetIFDTreeIter(tiff, olympus1Labels[i].length, ifdPositions)
} else {
// Offsets are relative to start of buffer.
rec.relative = false
return node.genericGetIFDTreeIter(buf, pos+olympus1Labels[i].length, ifdPositions)
}
}
}
// Shouldn't reach this point if we already know it's an Olympus1SpaceRec.
return errors.New("Invalid label for Olympus1 maker note")
}
func (*Olympus1SpaceRec) getFooter(node *IFDNode, buf []byte, pos uint32, ifdPositions posMap) error {
return node.unexpectedFooter(buf, pos, ifdPositions)
}
func (rec *Olympus1SpaceRec) putIFDTree(node IFDNode, buf []byte, pos uint32) (uint32, error) {
copy(buf[pos:], rec.label)
labelLen := uint32(len(rec.label))
if rec.relative {
makerBuf := buf[pos:]
next, err := node.genericPutIFDTree(makerBuf, labelLen)
if err != nil {
return 0, err
} else {
return pos + next, nil
}
} else {
pos += uint32(labelLen)
return node.genericPutIFDTree(buf, pos)
}
}
func (*Olympus1SpaceRec) GetImageData() []ImageData {
return nil
}
// SpaceRec for Panasonic1 maker notes.
type Panasonic1SpaceRec struct {
}
func (*Panasonic1SpaceRec) GetSpace() TagSpace {
return Panasonic1Space
}
func (*Panasonic1SpaceRec) IsMakerNote() bool {
return true
}
var panasonic1Label = []byte("Panasonic\000\000\000")
func (*Panasonic1SpaceRec) nodeSize(node IFDNode) uint32 {
return uint32(len(panasonic1Label)) + node.genericSize()
}
func (*Panasonic1SpaceRec) takeField(buf []byte, order binary.ByteOrder, ifdPositions posMap, idx uint16, field Field, dataPos uint32) ([]SubIFD, error) {
return nil, nil
}
func (*Panasonic1SpaceRec) getIFDTree(node *IFDNode, buf []byte, pos uint32, ifdPositions posMap) error {
// Offsets are relative to start of buf.
return node.genericGetIFDTreeIter(buf, pos+uint32(len(panasonic1Label)), ifdPositions)
}
func (rec *Panasonic1SpaceRec) getFooter(node *IFDNode, buf []byte, pos uint32, ifdPositions posMap) error {
// Next pointer is generally missing, don't try to read it.
return nil
}
func (*Panasonic1SpaceRec) putIFDTree(node IFDNode, buf []byte, pos uint32) (uint32, error) {
copy(buf[pos:], panasonic1Label)
pos += uint32(len(panasonic1Label))
return node.genericPutIFDTree(buf, pos)
}
func (*Panasonic1SpaceRec) GetImageData() []ImageData {
return nil
}
// SpaceRec for Sony1 maker notes.
type Sony1SpaceRec struct {
label []byte
}
func (*Sony1SpaceRec) GetSpace() TagSpace {
return Sony1Space
}
func (*Sony1SpaceRec) IsMakerNote() bool {
return true
}
var sony1Labels = [][]byte{
[]byte("SONY CAM \000\000\000"), // Includes various Sony camcorders.
[]byte("SONY DSC \000\000\000"), // Includes various Sony still cameras.
[]byte("\000\000SONY PIC\000\000"), // Sony DSC-TF1.
[]byte("SONY MOBILE\000"), // Sony Xperia.
[]byte("VHAB \000\000\000"), // Hasselblad versions of Sony cameras.
}
// Fields in Sony1 IFD.
const sony1PreviewImage = 0x2001
func (rec *Sony1SpaceRec) nodeSize(node IFDNode) uint32 {
return uint32(len(rec.label)) + node.genericSize()
}
func (*Sony1SpaceRec) takeField(buf []byte, order binary.ByteOrder, ifdPositions posMap, idx uint16, field Field, dataPos uint32) ([]SubIFD, error) {
return nil, nil
}
func (rec *Sony1SpaceRec) getIFDTree(node *IFDNode, buf []byte, pos uint32, ifdPositions posMap) error {
for _, label := range sony1Labels {
if bytes.HasPrefix(buf[pos:], label) {
rec.label = append([]byte{}, label...)
ifdpos := pos + uint32(len(rec.label))
// Byte order varies by camera model, and may differ from Exif order.
node.Order = detectByteOrder(buf[ifdpos:])
return node.genericGetIFDTreeIter(buf, ifdpos, ifdPositions)
}
}
// Shouldn't reach this point if we already know it's a Sony1SpaceRec.
return errors.New("Invalid label for Sony1 maker note")
}
func (rec *Sony1SpaceRec) getFooter(node *IFDNode, buf []byte, pos uint32, ifdPositions posMap) error {
// Next pointer is often invalid, don't try to read it.
return nil
}
func (rec *Sony1SpaceRec) putIFDTree(node IFDNode, buf []byte, pos uint32) (uint32, error) {
copy(buf[pos:], rec.label)
pos += uint32(len(rec.label))
return node.genericPutIFDTree(buf, pos)
}
func (*Sony1SpaceRec) GetImageData() []ImageData {
return nil
}
| {'content_hash': '222a4fb78444e1d3a06c2cf0d2bb03a6', 'timestamp': '', 'source': 'github', 'line_count': 631, 'max_line_length': 256, 'avg_line_length': 31.76862123613312, 'alnum_prop': 0.720193554823905, 'repo_name': 'garyhouston/tiff66', 'id': 'aff58960ece7b0660af13a2a18e982ea5d2ef649', 'size': '20046', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'makernotes.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Go', 'bytes': '85482'}]} |
package io.cattle.platform.simple.allocator.dao;
import java.util.HashSet;
import java.util.Set;
public class QueryOptions {
Long accountId;
String kind;
boolean includeUsedPorts;
Set<Long> hosts = new HashSet<Long>();
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public Set<Long> getHosts() {
return hosts;
}
public Long getAccountId() {
return accountId;
}
public void setAccountId(Long accountId) {
this.accountId = accountId;
}
public boolean isIncludeUsedPorts() {
return includeUsedPorts;
}
public void setIncludeUsedPorts(boolean getUsedPorts) {
this.includeUsedPorts = getUsedPorts;
}
}
| {'content_hash': '913845685ec35c8c29955463c36dfa66', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 59, 'avg_line_length': 19.146341463414632, 'alnum_prop': 0.6382165605095541, 'repo_name': 'jimengliu/cattle', 'id': '0a10b04e82a24f6fcc5e571341355f362c92aac8', 'size': '785', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'code/iaas/simple-allocator/src/main/java/io/cattle/platform/simple/allocator/dao/QueryOptions.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'FreeMarker', 'bytes': '15475'}, {'name': 'Java', 'bytes': '6117577'}, {'name': 'Python', 'bytes': '809691'}, {'name': 'Shell', 'bytes': '48232'}]} |
/**
* Created by kun
*/
var express = require('express');
var magazineDB = require('../database/magazineDB');
var validator = require('validator');
var async = require('async');
var router = express.Router();
var returnArticles = function (err, recordSet, res) {
if (!err) {
var result = [];
for (var i = 0; i < recordSet.length; i++) {
result[i] = recordSet[i];
}
res.status(200).json({result: true, data: result});
} else {
console.error(err);
res.status(200).json({result: false, data: "发生异常"});
}
};
var returnMagazine = function (nextId, res, callback) {
magazineDB.getMagazine(nextId, function (err, recordSet) {
if (!err) {
var result = null;
if (recordSet.length > 0) {
result = recordSet[0];
}
res.status(200).json({result: true, data: result});
} else {
res.status(200).json({result: false, data: "发生异常"});
}
});
}
var checkMagId = function (req, res, next) {
var magId = req.param("magId");
if (!validator.isNumeric(magId)) {
res.status(400).json({result: false, data: "invalid param magId"});
} else {
next();
}
};
var checkKeywords = function (req, res, next) {
var keywords = req.param("keywords");
if (keywords) {
next();
} else {
res.status(400).json({result: false, data: "miss required param keywords"});
}
}
/**
* 获取最新杂志列表
*/
router.get('/list', function (req, res) {
magazineDB.listMagazines(function (err, recordSet) {
if (!err) {
var result = [];
for (var i = 0; i < recordSet.length; i++) {
result[i] = recordSet[i];
}
res.status(200).json({result: true, data: result});
} else {
console.error(err);
res.status(200).json({result: false, data: "发生异常"});
}
});
});
/**
* 获取杂志目录信息
*/
router.get('/articles', checkMagId, function (req, res) {
var magId = req.param("magId");
magazineDB.listArticles(magId, function (err, recordSet) {
returnArticles(err, recordSet, res);
});
});
/**
* 获取下一期杂志目录信息
*/
router.get('/nextMag', function (req, res) {
var magId = req.param("magId");
async.waterfall(
[
function (callback) {
magazineDB.getNextMagazineId(magId, function (err, recordSet) {
if (!err && recordSet.length > 0) {
var nextId = recordSet[0].id;
callback(null, nextId, res);
} else {
res.status(200).json({result: false, data: (err ? "get next magazine failed!" : null)});
callback("no next magazine", null, res);
}
});
}, returnMagazine
]
);
});
/**
* 获取上一期杂志目录信息
*/
router.get('/prevMag', function (req, res) {
var magId = req.param("magId");
async.waterfall(
[
function (callback) {
magazineDB.getPreviousMagazineId(magId, function (err, recordSet) {
if (!err && recordSet.length > 0) {
var nextId = recordSet[0].id;
callback(null, nextId, res);
} else {
res.status(200).json({result: false, data: (err ? "get previous magazine failed!" : null)});
callback("no previous magazine", null, res);
}
});
}, returnMagazine
]
);
});
/**
* 根据条件搜索杂志信息
*/
router.get('/search', checkKeywords, function (req, res) {
var keywords = req.param("keywords");
var index = req.param("index");
magazineDB.search(keywords, index, function (err, recordSet) {
returnArticles(err, recordSet, res)
});
});
router.get('/news', function (req, res) {
magazineDB.notice(function (err, recordSet) {
returnArticles(err, recordSet, res);
});
});
module.exports = router; | {'content_hash': '08d97389a26d6a45b101e1d620fd0c29', 'timestamp': '', 'source': 'github', 'line_count': 148, 'max_line_length': 116, 'avg_line_length': 27.66216216216216, 'alnum_prop': 0.5156326331216414, 'repo_name': 'chris6k/tiyuzazhi-bk', 'id': '9e842d21d2dd3fd07bcf41b275dd57f3e829d93d', 'size': '4214', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'routes/magazine.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '46'}, {'name': 'CSS', 'bytes': '110'}, {'name': 'HTML', 'bytes': '274'}, {'name': 'JavaScript', 'bytes': '39615'}]} |
<!DOCTYPE html>
<html lang = "en" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="prime.css">
<title>Prime Properties</title>
</head>
<body>
<div id="wrapper">
<header>
</header>
<nav>
<ul>
<li> <a href="index.html"> Home </a> </li>
<li> <a href="listings.html"> Listings </a> </li>
<li> <a href="financing.html"> Financing </a> </li>
<li> <a href="contact.html"> Contact </a> </li>
</ul>
</nav>
<div id="content">
<!-- Financing -->
<h1> Financing </h1>
<p> We work with many area mortgage and finance companies </p>
<!-- Mortgage faqs -->
<h2> Mortgage FAQs </h2>
<dl>
<dt> What amount of mortgage do I qualify for? </dt>
<dd>The total basic monthly housing cost is normally based on 20% to
41% of your gross monthly income</dd>
<dt> Which percentage is most often used? </dt>
<dd>The percentage used depends on the lending institution and type of financing</dd>
<dt> How do I get started? </dt>
<dd>Contact us today to help you arrange financing for your home</dd>
</dl>
</div>
<footer>
<a href="index.html">Home</a>
<a href="listings.html">Listings</a>
<a href="financing.html">Financing</a>
<a href="contact.html">Contact</a>
<br>
Copyright © 2015 Prime Properties
<br>
<a href="mailto:[email protected]">[email protected]</a>
</footer>
<!--End of wrapper div -->
</div>
</body>
</html> | {'content_hash': 'd5c39acf2337a15fea3464536ccc7939', 'timestamp': '', 'source': 'github', 'line_count': 56, 'max_line_length': 86, 'avg_line_length': 26.232142857142858, 'alnum_prop': 0.6364874063989108, 'repo_name': 'torch2424/SchoolSourceSpring2015', 'id': '15a3128d16b507a33dd17196b8bfbb688293292f', 'size': '1469', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'WebPagesCECS110/Midterm/financing.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C++', 'bytes': '61130'}, {'name': 'CSS', 'bytes': '16767'}, {'name': 'HTML', 'bytes': '45538'}, {'name': 'Java', 'bytes': '71890'}, {'name': 'Makefile', 'bytes': '31266'}]} |
package org.schema.api.model.thing.medicalEntity.medicalProcedure;
import org.schema.api.model.thing.medicalEntity.medicalProcedure.MedicalProcedure;
public class PalliativeProcedure extends MedicalProcedure
{
} | {'content_hash': '875d7374a1a4947d103c810163972912', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 82, 'avg_line_length': 30.428571428571427, 'alnum_prop': 0.863849765258216, 'repo_name': 'omindra/schema_org_java_api', 'id': 'babefd895cae5c2571f7595bb28cfe5714fbc8dd', 'size': '213', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'core/main/java/org/schema/api/model/thing/medicalEntity/medicalProcedure/PalliativeProcedure.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '2797669'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<document id="DDI-MedLine.d126">
<sentence id="DDI-MedLine.d126.s0" text="Cypermethrin-induced oxidative stress in rat brain and liver is prevented by vitamin E or allopurinol.
">
<entity id="DDI-MedLine.d126.s0.e0" charOffset="0-11"
type="drug" text="Cypermethrin"/>
<entity id="DDI-MedLine.d126.s0.e1" charOffset="77-85"
type="drug" text="vitamin E"/>
<entity id="DDI-MedLine.d126.s0.e2" charOffset="90-100"
type="drug" text="allopurinol"/>
<pair id="DDI-MedLine.d126.s0.p0" e1="DDI-MedLine.d126.s0.e0"
e2="DDI-MedLine.d126.s0.e1" ddi="true" type="effect"/>
<pair id="DDI-MedLine.d126.s0.p1" e1="DDI-MedLine.d126.s0.e0"
e2="DDI-MedLine.d126.s0.e2" ddi="true" type="effect"/>
<pair id="DDI-MedLine.d126.s0.p2" e1="DDI-MedLine.d126.s0.e1"
e2="DDI-MedLine.d126.s0.e2" ddi="false"/>
</sentence>
<sentence id="DDI-MedLine.d126.s1" text="Considering that the involvement of reactive oxygen species (ROS) has been implicated in the toxicity of various pesticides, this study was designed to investigate the possibility of oxidative stress induction by cypermethrin, a Type II pyrethroid. ">
<entity id="DDI-MedLine.d126.s1.e0" charOffset="213-224"
type="drug" text="cypermethrin"/>
<entity id="DDI-MedLine.d126.s1.e1" charOffset="229-246"
type="drug_n" text="Type II pyrethroid"/>
<pair id="DDI-MedLine.d126.s1.p0" e1="DDI-MedLine.d126.s1.e0"
e2="DDI-MedLine.d126.s1.e1" ddi="false"/>
</sentence>
<sentence id="DDI-MedLine.d126.s2" text="Either single (170 mg/kg) or repeated (75 mg/kg per day for 5 days) oral administration of cypermethrin was found to produce significant oxidative stress in cerebral and hepatic tissues of rats, as was evident by the elevation of the level of thiobarbituric acid reactive substances (TBARS) in both tissues, either 4 or 24 h after treatment. ">
<entity id="DDI-MedLine.d126.s2.e0" charOffset="91-102"
type="drug" text="cypermethrin"/>
</sentence>
<sentence id="DDI-MedLine.d126.s3" text="Much higher changes were observed in liver, increasing from a level of 60% at 4 h up to nearly 4 times the control at 24 h for single dose. "/>
<sentence id="DDI-MedLine.d126.s4" text="Reduced levels (up to 20%) of total glutathione (total GSH), and elevation of conjugated dienes ( approximately 60% in liver by single dose at 4 h) also indicated the presence of an oxidative insult. "/>
<sentence id="DDI-MedLine.d126.s5" text="Glutathione-S-transferase (GST) activity, however, did not differ from control values for any dose or at any time point in cerebral and hepatic tissues. "/>
<sentence id="DDI-MedLine.d126.s6" text="Pretreatment of rats with allopurinol (100 mg/kg, ip) or Vitamin E (100 mg/kg per day, ig, for 3 days and a dose of 40 mg/kg on the 4th day) provided significant protection against the elevation of TBARS levels in cerebral and hepatic tissues, induced by single high dose of oral cypermethrin administration within 4 h. ">
<entity id="DDI-MedLine.d126.s6.e0" charOffset="26-36"
type="drug" text="allopurinol"/>
<entity id="DDI-MedLine.d126.s6.e1" charOffset="57-65"
type="drug" text="Vitamin E"/>
<entity id="DDI-MedLine.d126.s6.e2" charOffset="280-291"
type="drug" text="cypermethrin"/>
<pair id="DDI-MedLine.d126.s6.p0" e1="DDI-MedLine.d126.s6.e0"
e2="DDI-MedLine.d126.s6.e1" ddi="false"/>
<pair id="DDI-MedLine.d126.s6.p1" e1="DDI-MedLine.d126.s6.e0"
e2="DDI-MedLine.d126.s6.e2" ddi="true" type="effect"/>
<pair id="DDI-MedLine.d126.s6.p2" e1="DDI-MedLine.d126.s6.e1"
e2="DDI-MedLine.d126.s6.e2" ddi="true" type="effect"/>
</sentence>
<sentence id="DDI-MedLine.d126.s7" text="Thus, the results suggest that cypermethrin exposure of rats results in free radical-mediated tissue damage, as indicated by elevated cerebral and hepatic lipid peroxidation, which was prevented by allopurinol and Vitamin E.">
<entity id="DDI-MedLine.d126.s7.e0" charOffset="31-42"
type="drug" text="cypermethrin"/>
<entity id="DDI-MedLine.d126.s7.e1" charOffset="198-208"
type="drug" text="allopurinol"/>
<entity id="DDI-MedLine.d126.s7.e2" charOffset="214-222"
type="drug" text="Vitamin E"/>
<pair id="DDI-MedLine.d126.s7.p0" e1="DDI-MedLine.d126.s7.e0"
e2="DDI-MedLine.d126.s7.e1" ddi="true" type="effect"/>
<pair id="DDI-MedLine.d126.s7.p1" e1="DDI-MedLine.d126.s7.e0"
e2="DDI-MedLine.d126.s7.e2" ddi="true" type="effect"/>
<pair id="DDI-MedLine.d126.s7.p2" e1="DDI-MedLine.d126.s7.e1"
e2="DDI-MedLine.d126.s7.e2" ddi="false"/>
</sentence>
</document>
| {'content_hash': '7d11e8726a1b38087144c8377a3aa446', 'timestamp': '', 'source': 'github', 'line_count': 60, 'max_line_length': 389, 'avg_line_length': 82.06666666666666, 'alnum_prop': 0.6661251015434606, 'repo_name': 'dbmi-pitt/pk-ddi-role-identifier', 'id': '84724286490c1c01d938e7a5a2c698fff300b5a6', 'size': '4924', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'nlp-ddi-role-identifier/DDI/DDI_corpora/Train2013/MedLine/11137320.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '201212'}, {'name': 'Python', 'bytes': '27449'}]} |
package eu.fraho.spring.securityJwt.base.dto;
import lombok.Getter;
/**
* Configuration of available crypt-algorithms.
*
* @see #DES
* @see #MD5
* @see #SHA256
* @see #SHA512
*/
@Getter
public enum CryptAlgorithm {
/**
* Use classic DES crypt (insecure, no rounds supported)
*
* @deprecated Do not use!
*/
@Deprecated
DES(true, false, "", 2),
/**
* Use MD5 based crypt (insecure, no rounds supported)
*
* @deprecated Do not use!
*/
@Deprecated
MD5(true, false, "$1$", 8),
/**
* Use blowfish based crypt (2a, rounds supported)
*/
BLOWFISH(false, false, "$2a$", 0),
/**
* Use SHA2-256 based crypt (rounds supported)
*/
SHA256(false, true, "$5$", 16),
/**
* Use SHA2-512 based crypt (rounds supported)
*/
SHA512(false, true, "$6$", 16);
final boolean insecure;
final boolean roundsSupported;
final String prefix;
final int saltLength;
CryptAlgorithm(boolean insecure, boolean roundsSupported, String prefix, int saltLength) {
this.insecure = insecure;
this.roundsSupported = roundsSupported;
this.prefix = prefix;
this.saltLength = saltLength;
}
}
| {'content_hash': '20ef3e0e9033b1dde96f63bb0eb3154a', 'timestamp': '', 'source': 'github', 'line_count': 58, 'max_line_length': 94, 'avg_line_length': 21.29310344827586, 'alnum_prop': 0.5983805668016194, 'repo_name': 'bratkartoffel/security-jwt', 'id': '3bc5aa452468af0daed8a5df20648e0fc2fdcd45', 'size': '1353', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'base/src/main/java/eu/fraho/spring/securityJwt/base/dto/CryptAlgorithm.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '307230'}]} |
ActiveRecord::Schema.define(version: 20141111000221) do
end
| {'content_hash': '672e0820ad2b4cc667dba4302ec487ec', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 55, 'avg_line_length': 20.333333333333332, 'alnum_prop': 0.819672131147541, 'repo_name': 'hired/fortitude_rails', 'id': '7b5bd652977a9b13e5618d4c3e195ecd277ec309', 'size': '802', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/dummy/db/schema.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '6422'}, {'name': 'HTML', 'bytes': '63947'}, {'name': 'JavaScript', 'bytes': '9669'}, {'name': 'Ruby', 'bytes': '33942'}]} |
Additional header content
Clones this instance.
**Namespace:** <a href="N_iTin_Export_Model">iTin.Export.Model</a><br />**Assembly:** iTin.Export.Core (in iTin.Export.Core.dll) Version: 2.0.0.0 (2.0.0.0)
## Syntax
**C#**<br />
``` C#
public NumberDataTypeModel Clone()
```
**VB**<br />
``` VB
Public Function Clone As NumberDataTypeModel
```
#### Return Value
Type: <a href="T_iTin_Export_Model_NumberDataTypeModel">NumberDataTypeModel</a><br />A new object that is a copy of this instance.
## Remarks
\[Missing <remarks> documentation for "M:iTin.Export.Model.NumberDataTypeModel.Clone"\]
## See Also
#### Reference
<a href="T_iTin_Export_Model_NumberDataTypeModel">NumberDataTypeModel Class</a><br /><a href="N_iTin_Export_Model">iTin.Export.Model Namespace</a><br /> | {'content_hash': 'eb00b8fbd74e5559d03e8d163b704642', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 165, 'avg_line_length': 26.366666666666667, 'alnum_prop': 0.706700379266751, 'repo_name': 'iAJTin/iExportEngine', 'id': '8fbf264f8177118cbf9fed529871056845d93e96', 'size': '827', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'source/documentation/iTin.Export.Documentation/Documentation/M_iTin_Export_Model_NumberDataTypeModel_Clone.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '2298'}, {'name': 'C#', 'bytes': '2815693'}, {'name': 'Smalltalk', 'bytes': '7632'}, {'name': 'XSLT', 'bytes': '14099'}]} |
package abi43_0_0.expo.modules.ads.facebook;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import com.facebook.ads.AdOptionsView;
import com.facebook.ads.NativeAdLayout;
import java.lang.ref.WeakReference;
public class AdOptionsWrapperView extends LinearLayout {
private int mIconSize = -1;
private Integer mColor = null;
private AdOptionsView.Orientation mOrientation = null;
private WeakReference<NativeAdView> mNativeAdViewWeakReference = new WeakReference<>(null);
private WeakReference<AdOptionsView> mAdOptionsViewWeakReference = new WeakReference<>(null);
public AdOptionsWrapperView(Context context) {
super(context);
}
public void setNativeAdView(NativeAdView nativeAdView) {
mNativeAdViewWeakReference = new WeakReference<>(nativeAdView);
maybeSetUpOptionsView();
}
public void setIconSize(int iconSize) {
mIconSize = iconSize;
maybeSetUpOptionsView();
}
public void setOrientation(AdOptionsView.Orientation orientation) {
mOrientation = orientation;
maybeSetUpOptionsView();
}
public void setIconColor(Integer color) {
mColor = color;
AdOptionsView adOptionsView = mAdOptionsViewWeakReference.get();
if (adOptionsView != null && color != null) {
adOptionsView.setIconColor(mColor);
}
}
private void maybeSetUpOptionsView() {
NativeAdView nativeAdView = mNativeAdViewWeakReference.get();
if (mIconSize == -1 ||
mOrientation == null ||
nativeAdView == null) {
return;
}
removeAllViews();
AdOptionsView adOptionsView = createNewAdOptionsView(nativeAdView);
addView(adOptionsView);
mAdOptionsViewWeakReference = new WeakReference<>(adOptionsView);
}
private AdOptionsView createNewAdOptionsView(NativeAdView nativeAdView) {
AdOptionsView adOptionsView = new AdOptionsView(
getContext(),
nativeAdView.getNativeAd(),
getNativeAdLayout(nativeAdView),
mOrientation,
mIconSize
);
if (mColor != null) {
adOptionsView.setIconColor(mColor);
}
return adOptionsView;
}
private NativeAdLayout getNativeAdLayout(NativeAdView nativeAdView) {
View currentView = nativeAdView;
try {
while (!(currentView instanceof NativeAdLayout)) {
currentView = (View) currentView.getParent();
}
} catch (Exception e) {
System.out.println();
Log.e("AdOptionsView","NativeAdLayout is not an ancestor of nativeAdView!", e);
}
return (NativeAdLayout) currentView;
}
@Override
public void requestLayout() {
super.requestLayout();
// Relayout child
post(mMeasureAndLayout);
}
private final Runnable mMeasureAndLayout = new Runnable() {
@Override
public void run() {
measure(
MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY));
layout(getLeft(), getTop(), getRight(), getBottom());
}
};
}
| {'content_hash': 'ee2e42b6f3614b46e6e022ab1fba2c36', 'timestamp': '', 'source': 'github', 'line_count': 112, 'max_line_length': 95, 'avg_line_length': 27.294642857142858, 'alnum_prop': 0.709192018318613, 'repo_name': 'exponent/exponent', 'id': '8483afa06951bc2cb6bc1e33c900831b510fcda0', 'size': '3057', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/ads/facebook/AdOptionsWrapperView.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '113276'}, {'name': 'Batchfile', 'bytes': '127'}, {'name': 'C', 'bytes': '1744836'}, {'name': 'C++', 'bytes': '1801159'}, {'name': 'CSS', 'bytes': '7854'}, {'name': 'HTML', 'bytes': '176329'}, {'name': 'IDL', 'bytes': '897'}, {'name': 'Java', 'bytes': '6251130'}, {'name': 'JavaScript', 'bytes': '4416558'}, {'name': 'Makefile', 'bytes': '18061'}, {'name': 'Objective-C', 'bytes': '13971362'}, {'name': 'Objective-C++', 'bytes': '725480'}, {'name': 'Perl', 'bytes': '5860'}, {'name': 'Prolog', 'bytes': '287'}, {'name': 'Python', 'bytes': '125673'}, {'name': 'Ruby', 'bytes': '61190'}, {'name': 'Shell', 'bytes': '4441'}]} |
package com.facebook.buck.distributed;
import com.facebook.buck.distributed.thrift.BuckVersion;
import com.facebook.buck.distributed.thrift.BuildId;
import com.facebook.buck.distributed.thrift.BuildJob;
import com.facebook.buck.distributed.thrift.BuildJobState;
import com.facebook.buck.distributed.thrift.BuildStatus;
import com.facebook.buck.distributed.thrift.LogRecord;
import com.facebook.buck.event.BuckEventBus;
import com.facebook.buck.log.Logger;
import com.facebook.buck.util.concurrent.WeightedListeningExecutorService;
import com.google.common.base.Optional;
import com.google.common.base.Stopwatch;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class DistBuildClientExecutor {
private static final Logger LOG = Logger.get(DistBuildClientExecutor.class);
private static final DateFormat DATE_FORMAT = new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss.SSS]");
private static final int MAX_BUILD_DURATION_MILLIS = 10000; // hack. remove.
private final DistBuildService distBuildService;
private final BuildJobState buildJobState;
private final BuckVersion buckVersion;
private int millisBetweenStatusPoll;
public DistBuildClientExecutor(
BuildJobState buildJobState,
DistBuildService distBuildService,
int millisBetweenStatusPoll,
BuckVersion buckVersion) {
this.buildJobState = buildJobState;
this.distBuildService = distBuildService;
this.millisBetweenStatusPoll = millisBetweenStatusPoll;
this.buckVersion = buckVersion;
}
public int executeAndPrintFailuresToEventBus(
final WeightedListeningExecutorService executorService,
BuckEventBus eventBus)
throws IOException, InterruptedException {
BuildJob job = distBuildService.createBuild();
final BuildId id = job.getBuildId();
LOG.info("Created job. Build id = " + id.getId());
logDebugInfo(job);
try {
distBuildService.uploadMissingFiles(buildJobState.fileHashes, executorService).get();
} catch (ExecutionException e) {
LOG.error("Exception uploading local changes: " + e);
throw new RuntimeException(e);
}
LOG.info("Uploaded local changes. Build status: " + job.getStatus().toString());
try {
distBuildService.uploadTargetGraph(buildJobState, id, executorService).get();
} catch (ExecutionException e) {
LOG.error("Exception uploading build graph: " + e);
throw new RuntimeException(e);
}
LOG.info("Uploaded target graph. Build status: " + job.getStatus().toString());
distBuildService.setBuckVersion(id, buckVersion);
LOG.info("Set Buck Version. Build status: " + job.getStatus().toString());
job = distBuildService.startBuild(id);
LOG.info("Started job. Build status: " + job.getStatus().toString());
logDebugInfo(job);
Stopwatch stopwatch = Stopwatch.createStarted();
// Keep polling until the build is complete or failed.
do {
job = distBuildService.getCurrentBuildJobState(id);
LOG.info("Got build status: " + job.getStatus().toString());
DistBuildStatus distBuildStatus =
prepareStatusFromJob(job)
.setETAMillis(MAX_BUILD_DURATION_MILLIS - stopwatch.elapsed(TimeUnit.MILLISECONDS))
.build();
eventBus.post(new DistBuildStatusEvent(distBuildStatus));
try {
// TODO(shivanker): Get rid of sleeps in methods which we want to unit test
Thread.sleep(millisBetweenStatusPoll);
} catch (InterruptedException e) {
LOG.error(e, "BuildStatus polling sleep call has been interrupted unexpectedly.");
}
} while (!(job.getStatus().equals(BuildStatus.FINISHED_SUCCESSFULLY) ||
job.getStatus().equals(BuildStatus.FAILED)));
LOG.info("Build was " +
(job.getStatus().equals(BuildStatus.FINISHED_SUCCESSFULLY) ? "" : "not ") +
"successful!");
logDebugInfo(job);
DistBuildStatus distBuildStatus = prepareStatusFromJob(job).setETAMillis(0).build();
eventBus.post(new DistBuildStatusEvent(distBuildStatus));
return job.getStatus().equals(BuildStatus.FINISHED_SUCCESSFULLY) ? 0 : 1;
}
private DistBuildStatus.Builder prepareStatusFromJob(BuildJob job) {
Optional<List<LogRecord>> logBook = Optional.absent();
Optional<String> lastLine = Optional.absent();
if (job.isSetDebug() && job.getDebug().isSetLogBook()) {
logBook = Optional.of(job.getDebug().getLogBook());
if (logBook.get().size() > 0) {
lastLine = Optional.of(logBook.get().get(logBook.get().size() - 1).getName());
}
}
return DistBuildStatus.builder()
.setStatus(job.getStatus())
.setMessage(lastLine)
.setLogBook(logBook);
}
private void logDebugInfo(BuildJob job) {
if (job.isSetDebug() && job.getDebug().getLogBook().size() > 0) {
LOG.debug("Debug info: ");
for (LogRecord log : job.getDebug().getLogBook()) {
LOG.debug(DATE_FORMAT.format(new Date(log.getTimestampMillis())) + log.getName());
}
}
}
}
| {'content_hash': '3b7d818adbeb5463749a254d74a29403', 'timestamp': '', 'source': 'github', 'line_count': 136, 'max_line_length': 98, 'avg_line_length': 38.044117647058826, 'alnum_prop': 0.7155005798221878, 'repo_name': 'raviagarwal7/buck', 'id': 'd06eb5fbfc2b4714e100e4eb941f8dd9325ed5d6', 'size': '5779', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/com/facebook/buck/distributed/DistBuildClientExecutor.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '579'}, {'name': 'Batchfile', 'bytes': '726'}, {'name': 'C', 'bytes': '248999'}, {'name': 'C#', 'bytes': '237'}, {'name': 'C++', 'bytes': '6648'}, {'name': 'CSS', 'bytes': '54863'}, {'name': 'D', 'bytes': '1017'}, {'name': 'Go', 'bytes': '15018'}, {'name': 'Groff', 'bytes': '440'}, {'name': 'Groovy', 'bytes': '3362'}, {'name': 'HTML', 'bytes': '5552'}, {'name': 'Haskell', 'bytes': '895'}, {'name': 'IDL', 'bytes': '128'}, {'name': 'Java', 'bytes': '16103550'}, {'name': 'JavaScript', 'bytes': '934068'}, {'name': 'Kotlin', 'bytes': '1344'}, {'name': 'Lex', 'bytes': '2595'}, {'name': 'MATLAB', 'bytes': '47'}, {'name': 'Makefile', 'bytes': '1812'}, {'name': 'OCaml', 'bytes': '3102'}, {'name': 'Objective-C', 'bytes': '1135673'}, {'name': 'Objective-C++', 'bytes': '34'}, {'name': 'PowerShell', 'bytes': '244'}, {'name': 'Python', 'bytes': '481875'}, {'name': 'Rust', 'bytes': '1388'}, {'name': 'Scala', 'bytes': '1690'}, {'name': 'Shell', 'bytes': '35582'}, {'name': 'Smalltalk', 'bytes': '4788'}, {'name': 'Standard ML', 'bytes': '15'}, {'name': 'Swift', 'bytes': '4737'}, {'name': 'Thrift', 'bytes': '11826'}, {'name': 'Yacc', 'bytes': '323'}]} |
using System.Collections.Generic;
namespace ExParser {
class TokenBuffer : ITokenReader {
public int Index { get; private set; }
Token[] tokens;
public TokenBuffer(List<Token> tokens) : this(tokens.ToArray()) { }
public TokenBuffer(Token[] tokens) {
this.tokens = tokens;
}
public Token GetToken() {
return EOF() ? null : tokens[Index++];
}
public Token PeekToken() {
return EOF() ? null : tokens[Index];
}
bool EOF() => Index >= tokens.Length;
}
}
| {'content_hash': '306bf8a606e435d64656253246100901', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 75, 'avg_line_length': 25.17391304347826, 'alnum_prop': 0.5457685664939551, 'repo_name': 'davudk/ExpressionParser', 'id': 'aebed842c61189fbe2d987c65826f811e9fcf2fe', 'size': '581', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ExParser/ExParser/TokenBuffer.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '19906'}]} |
<!DOCTYPE html>
<html class="no-js">
<head lang="en-us">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=1,maximum-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=10" />
<title>Apis - Uchiwa Documentation</title>
<meta name="generator" content="Hugo 0.30.2" />
<meta name="description" content="A simple dashboard for the Sensu monitoring framework">
<link rel="canonical" href="https://docs.uchiwa.io/api/">
<meta name="author" content="Simon Plourde">
<meta property="og:url" content="https://docs.uchiwa.io/api/">
<meta property="og:title" content="Uchiwa Documentation">
<meta name="apple-mobile-web-app-title" content="Uchiwa Documentation">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<link rel="shortcut icon" type="image/x-icon" href="https://docs.uchiwa.io/images/favicon.ico">
<link rel="icon" type="image/x-icon" href="https://docs.uchiwa.io/images/favicon.ico">
<style>
@font-face {
font-family: 'Icon';
src: url('https://docs.uchiwa.io/fonts/icon.eot?52m981');
src: url('https://docs.uchiwa.io/fonts/icon.eot?#iefix52m981')
format('embedded-opentype'),
url('https://docs.uchiwa.io/fonts/icon.woff?52m981')
format('woff'),
url('https://docs.uchiwa.io/fonts/icon.ttf?52m981')
format('truetype'),
url('https://docs.uchiwa.io/fonts/icon.svg?52m981#icon')
format('svg');
font-weight: normal;
font-style: normal;
}
</style>
<link rel="stylesheet" href="https://docs.uchiwa.io/stylesheets/application.css">
<link rel="stylesheet" href="https://docs.uchiwa.io/stylesheets/temporary.css">
<link rel="stylesheet" href="https://docs.uchiwa.io/stylesheets/palettes.css">
<link rel="stylesheet" href="https://docs.uchiwa.io/stylesheets/highlight/highlight.css">
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Roboto:400,700|Roboto+Mono">
<style>
body, input {
font-family: 'Roboto', Helvetica, Arial, sans-serif;
}
pre, code {
font-family: 'Roboto Mono', 'Courier New', 'Courier', monospace;
}
</style>
<script src="https://docs.uchiwa.io/javascripts/modernizr.js"></script>
<link href="https://docs.uchiwa.io/api/index.xml" rel="alternate" type="application/rss+xml" title="Uchiwa Documentation" />
<link href="https://docs.uchiwa.io/api/index.xml" rel="feed" type="application/rss+xml" title="Uchiwa Documentation" />
</head>
<body class="palette-primary-light-blue palette-accent-light-blue">
<div class="backdrop">
<div class="backdrop-paper"></div>
</div>
<input class="toggle" type="checkbox" id="toggle-drawer">
<input class="toggle" type="checkbox" id="toggle-search">
<label class="toggle-button overlay" for="toggle-drawer"></label>
<header class="header">
<nav aria-label="Header">
<div class="bar default">
<div class="button button-menu" role="button" aria-label="Menu">
<label class="toggle-button icon icon-menu" for="toggle-drawer">
<span></span>
</label>
</div>
<div class="stretch">
<div class="title">
Apis
</div>
</div>
<div class="button button-twitter" role="button" aria-label="Twitter">
<a href="https://twitter.com/uchiwaio" title="@uchiwaio on Twitter" target="_blank" class="toggle-button icon icon-twitter"></a>
</div>
<div class="button button-github" role="button" aria-label="GitHub">
<a href="https://github.com/palourde" title="@palourde on GitHub" target="_blank" class="toggle-button icon icon-github"></a>
</div>
</div>
<div class="bar search">
<div class="button button-close" role="button" aria-label="Close">
<label class="toggle-button icon icon-back" for="toggle-search"></label>
</div>
<div class="stretch">
<div class="field">
<input class="query" type="text" placeholder="Search" autocapitalize="off" autocorrect="off" autocomplete="off" spellcheck>
</div>
</div>
<div class="button button-reset" role="button" aria-label="Search">
<button class="toggle-button icon icon-close" id="reset-search"></button>
</div>
</div>
</nav>
</header>
<main class="main">
<div class="drawer">
<nav aria-label="Navigation">
<a href="https://github.com/sensu/uchiwa" class="project">
<div class="banner">
<div class="name">
<strong>Uchiwa Documentation <span class="version">1.1.0</span></strong>
</div>
</div>
</a>
<div class="scrollable">
<div class="wrapper">
<ul class="repo">
<li class="repo-download">
<a href="https://uchiwa.io/#/download" title="Download" data-action="download">
<i class="icon icon-download"></i> Download
</a>
</li>
<li class="repo-stars">
<a href="https://github.com/sensu/uchiwa/stargazers" target="_blank" title="Stargazers" data-action="star">
<i class="icon icon-star"></i> Stars
<span class="count">–</span>
</a>
</li>
</ul>
<hr>
<div class="toc">
<ul>
<li>
<a title="Home" href="https://docs.uchiwa.io/">
Home
</a>
</li>
<li>
<span class="section">Getting Started</span>
<ul>
<a title="Basic Concepts" href="https://docs.uchiwa.io/getting-started/basic-concepts/">
Basic Concepts
</a>
<a title="Installation" href="https://docs.uchiwa.io/getting-started/installation/">
Installation
</a>
<a title="Configuration" href="https://docs.uchiwa.io/getting-started/configuration/">
Configuration
</a>
</ul>
</li>
<li>
<span class="section">Guides</span>
<ul>
<a title="High Availability" href="https://docs.uchiwa.io/guides/high-availability/">
High Availability
</a>
<a title="Search Queries" href="https://docs.uchiwa.io/guides/search-queries/">
Search Queries
</a>
<a title="Security" href="https://docs.uchiwa.io/guides/security/">
Security
</a>
<a title="Troubleshooting" href="https://docs.uchiwa.io/guides/troubleshooting/">
Troubleshooting
</a>
</ul>
</li>
<li>
<span class="section">Reference</span>
<ul>
<a title="Aggregates" href="https://docs.uchiwa.io/reference/aggregates/">
Aggregates
</a>
<a title="Checks" href="https://docs.uchiwa.io/reference/checks/">
Checks
</a>
<a title="Clients" href="https://docs.uchiwa.io/reference/clients/">
Clients
</a>
<a title="Events" href="https://docs.uchiwa.io/reference/events/">
Events
</a>
<a title="Silencing" href="https://docs.uchiwa.io/reference/silencing/">
Silencing
</a>
</ul>
</li>
<li>
<span class="section">API</span>
<ul>
<a title="Authentication" href="https://docs.uchiwa.io/api/authentication/">
Authentication
</a>
<a title="Health API" href="https://docs.uchiwa.io/api/health/">
Health API
</a>
</ul>
</li>
<li>
<a title="Contributing" href="https://docs.uchiwa.io/contributing">
Contributing
</a>
</li>
</ul>
<hr>
<span class="section">The author</span>
<ul>
<li>
<a href="https://twitter.com/uchiwaio" target="_blank" title="@uchiwaio on Twitter">
@uchiwaio on Twitter
</a>
</li>
<li>
<a href="https://github.com/palourde" target="_blank" title="@palourde on GitHub">
@palourde on GitHub
</a>
</li>
<li>
<a href="mailto:[email protected]" title="Email of [email protected]">
Contact via email
</a>
</li>
</ul>
</div>
</div>
</div>
</nav>
</div>
<article class="article">
<div class="wrapper">
<h1>Pages in Api</h1>
<a href="https://docs.uchiwa.io/api/authentication/" title="Authentication">
<h2>Authentication</h2>
</a>
<br>
In order to use the Uchiwa API when authentication is enabled, you must provide an access token with every request.
Remember to keep your access tokens secret and use HTTPS wherever possible.
Configuring an access token Set the accessToken attribute in the appropriate role; see the documentation. Restart Uchiwa to apply this change. Providing the access token In a header
curl -H "Authorization: token TOKEN" <a href="https://localhost:3000/events">https://localhost:3000/events</a> As a parameter
<hr>
<a href="https://docs.uchiwa.io/api/health/" title="Health API">
<h2>Health API</h2>
</a>
<br>
/health (GET) Returns both Uchiwa and Sensu API status
Response Example (Status 200) { "uchiwa": "ok", "sensu": { "us-east-1": { "output": "ok" }, "us-west-1":{ "output": "ok" } } } Response Codes HTTP Status Code Reason 200 All the services are working 503 One of the service is unavailable /health/{service} Returns status of Sensu API or Uchiwa service.
<hr>
<aside class="copyright" role="note">
© 2018 Released under the MIT license –
Documentation built with
<a href="https://www.gohugo.io" target="_blank">Hugo</a>
using the
<a href="http://github.com/digitalcraftsman/hugo-material-docs" target="_blank">Material</a> theme.
</aside>
</div>
</article>
<div class="results" role="status" aria-live="polite">
<div class="scrollable">
<div class="wrapper">
<div class="meta"></div>
<div class="list"></div>
</div>
</div>
</div>
</main>
<script>
var base_url = '';
var repo_id = '';
</script>
<script src="https://docs.uchiwa.io/javascripts/application.js"></script>
<script>
/* Add headers to scrollspy */
var headers = document.getElementsByTagName("h2");
var scrollspy = document.getElementById('scrollspy');
if(scrollspy) {
if(headers.length > 0) {
for(var i = 0; i < headers.length; i++) {
var li = document.createElement("li");
li.setAttribute("class", "anchor");
var a = document.createElement("a");
a.setAttribute("href", "#" + headers[i].id);
a.setAttribute("title", headers[i].innerHTML);
a.innerHTML = headers[i].innerHTML;
li.appendChild(a)
scrollspy.appendChild(li);
}
} else {
scrollspy.parentElement.removeChild(scrollspy)
}
/* Add permanent link next to the headers */
var headers = document.querySelectorAll("h1, h2, h3, h4, h5, h6");
for(var i = 0; i < headers.length; i++) {
var a = document.createElement("a");
a.setAttribute("class", "headerlink");
a.setAttribute("href", "#" + headers[i].id);
a.setAttribute("title", "Permanent link")
a.innerHTML = "#";
headers[i].appendChild(a);
}
}
</script>
<script>
(function(i,s,o,g,r,a,m){
i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||
[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;
m.parentNode.insertBefore(a,m)
})(window, document,
'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-56100759-3', 'auto');
ga('set', 'anonymizeIp', true);
ga('send', 'pageview');
var buttons = document.querySelectorAll('a');
Array.prototype.map.call(buttons, function(item) {
if (item.host != document.location.host) {
item.addEventListener('click', function() {
var action = item.getAttribute('data-action') || 'follow';
ga('send', 'event', 'outbound', action, item.href);
});
}
});
var query = document.querySelector('.query');
query.addEventListener('blur', function() {
if (this.value) {
var path = document.location.pathname;
ga('send', 'pageview', path + '?q=' + this.value);
}
});
</script>
<script src="//gohugo.io/js/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
</body>
</html>
| {'content_hash': '36df28451b7bfa54305a3464b5cb381c', 'timestamp': '', 'source': 'github', 'line_count': 608, 'max_line_length': 404, 'avg_line_length': 21.981907894736842, 'alnum_prop': 0.5669285447063225, 'repo_name': 'palourde/uchiwa-docs', 'id': 'eabed7a549eef9f15bf798b9db1649774ee1bc4f', 'size': '13365', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/api/index.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1426'}, {'name': 'HTML', 'bytes': '18439'}]} |
from google.cloud import datacatalog_v1
from google.iam.v1 import iam_policy_pb2 # type: ignore
def sample_set_iam_policy():
# Create a client
client = datacatalog_v1.PolicyTagManagerClient()
# Initialize request argument(s)
request = iam_policy_pb2.SetIamPolicyRequest(
resource="resource_value",
)
# Make the request
response = client.set_iam_policy(request=request)
# Handle the response
print(response)
# [END datacatalog_v1_generated_PolicyTagManager_SetIamPolicy_sync]
| {'content_hash': 'aa5320607197a1f7b41a2c6358f602ef', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 67, 'avg_line_length': 26.3, 'alnum_prop': 0.7186311787072244, 'repo_name': 'googleapis/python-datacatalog', 'id': 'dd717ff17a3e2f94234066f3df5aeee90a05da15', 'size': '1920', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'samples/generated_samples/datacatalog_v1_generated_policy_tag_manager_set_iam_policy_sync.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '2050'}, {'name': 'Python', 'bytes': '3073442'}, {'name': 'Shell', 'bytes': '30675'}]} |
package ecommerce
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestServiceConfig(t *testing.T) {
svc := New("example-tag")
assert.Equal(t, svc.APIVersion, "2013-08-01")
assert.Equal(t, svc.ServiceName, "AWSECommerceService")
assert.Equal(t, svc.Endpoint, "https://webservices.amazon.com")
assert.Equal(t, svc.AssociateTag, "example-tag")
assert.NotEmpty(t, svc.SigningRegion)
}
func TestServiceRequestParams(t *testing.T) {
svc := New("example-tag")
req := svc.NewOperationRequest("DoSomething", nil, nil)
query := req.HTTPRequest.URL.Query()
assert.Equal(t, query.Get("Operation"), "DoSomething")
assert.Equal(t, query.Get("AssociateTag"), "example-tag")
}
| {'content_hash': '50db9cd7358a884f736240708b40b99d', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 64, 'avg_line_length': 30.08695652173913, 'alnum_prop': 0.726878612716763, 'repo_name': 'vially/aws', 'id': 'd1fe669cbe3fcd355838aea6798d50aec0cda0be', 'size': '692', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'service/ecommerce/service_test.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Go', 'bytes': '13911'}]} |
<?php
namespace GithubService\Model;
class RepoStatsPunchCardInfo
{
use GithubTrait;
use SafeAccess;
public $day;
public $hour;
public $numberCommits;
//Each array contains the day number, hour number, and number of commits:
//
//0-6: Sunday - Saturday
//0-23: Hour of day
//Number of commits
static function createFromData($data) {
$instance = new static();
$instance->day = $data[0];
$instance->hour = $data[1];
$instance->numberCommits = $data[2];
return $instance;
}
}
| {'content_hash': '61a1444dce485bf0ab5e3c159e9546c2', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 73, 'avg_line_length': 18.29032258064516, 'alnum_prop': 0.6067019400352733, 'repo_name': 'Danack/GithubArtaxService', 'id': 'b43da295c2d8fdcd877c0bd520d56fd3c729565f', 'size': '567', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/GithubService/Model/RepoStatsPunchCardInfo.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '2357319'}, {'name': 'Ruby', 'bytes': '99744'}]} |
.admin-title {
color: var(--color-dark);
font-size: 150%; /* 1.5rem;*/
margin-bottom: var(--default-space);
font-weight: bold;
width: 100%;
border-bottom-style: solid;
border-bottom-width: 1px;
border-bottom-color: var(--color-dark);
}
.admin-subtitle {
font-size: 120%;
color: var(--color-dark);
width: 100%;
border-bottom-style: solid;
border-bottom-width: 1px;
border-bottom-color: var(--color-dark);
margin-bottom: var(--default-space);
}
.admin-subtitle-bold {
font-size: 100%;
color: var(--color-dark);
width: 100%;
font-weight: bold;
/*border-bottom-style: solid;
border-bottom-width: 1px;
border-bottom-color: var(--color-dark);*/
margin-bottom: var(--default-space);
}
.admin-bold {
font-weight: bold;
}
| {'content_hash': 'e771f1edb8245f15c045156ee0625930', 'timestamp': '', 'source': 'github', 'line_count': 49, 'max_line_length': 45, 'avg_line_length': 16.857142857142858, 'alnum_prop': 0.6029055690072639, 'repo_name': 'nemundo/framework', 'id': '70a551410e16c2489b179e79ac23f0ec21dd45af', 'size': '826', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'package/framework/css/typography/title.css', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '627'}, {'name': 'CSS', 'bytes': '27454'}, {'name': 'Dockerfile', 'bytes': '1204'}, {'name': 'Go', 'bytes': '8964'}, {'name': 'HTML', 'bytes': '304347'}, {'name': 'JavaScript', 'bytes': '10351912'}, {'name': 'PHP', 'bytes': '2062836'}, {'name': 'Python', 'bytes': '7574'}]} |
(function() {
'use strict';
angular
.module('webHipsterApp')
.controller('EditoraController', EditoraController);
EditoraController.$inject = ['Editora', 'ParseLinks', 'AlertService', 'paginationConstants'];
function EditoraController(Editora, ParseLinks, AlertService, paginationConstants) {
var vm = this;
vm.editoras = [];
vm.loadPage = loadPage;
vm.itemsPerPage = paginationConstants.itemsPerPage;
vm.page = 0;
vm.links = {
last: 0
};
vm.predicate = 'id';
vm.reset = reset;
vm.reverse = true;
loadAll();
function loadAll () {
Editora.query({
page: vm.page,
size: vm.itemsPerPage,
sort: sort()
}, onSuccess, onError);
function sort() {
var result = [vm.predicate + ',' + (vm.reverse ? 'asc' : 'desc')];
if (vm.predicate !== 'id') {
result.push('id');
}
return result;
}
function onSuccess(data, headers) {
vm.links = ParseLinks.parse(headers('link'));
vm.totalItems = headers('X-Total-Count');
for (var i = 0; i < data.length; i++) {
vm.editoras.push(data[i]);
}
}
function onError(error) {
AlertService.error(error.data.message);
}
}
function reset () {
vm.page = 0;
vm.editoras = [];
loadAll();
}
function loadPage(page) {
vm.page = page;
loadAll();
}
}
})();
| {'content_hash': '2c166964dfa52ef80adbceefba8409f4', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 97, 'avg_line_length': 26.892307692307693, 'alnum_prop': 0.4576659038901602, 'repo_name': 'rafaelmss/WebHipster', 'id': '91fe32d431036f2254275996eaf6bc3be876090c', 'size': '1748', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/webapp/app/entities/editora/editora.controller.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '5006'}, {'name': 'CSS', 'bytes': '9760'}, {'name': 'HTML', 'bytes': '175415'}, {'name': 'Java', 'bytes': '357100'}, {'name': 'JavaScript', 'bytes': '242593'}, {'name': 'Scala', 'bytes': '13675'}, {'name': 'Shell', 'bytes': '7058'}]} |
import tornado.web
import tornado.websocket
import tornado.httpserver
import tornado.ioloop
import logging
import json
from threading import Thread
from queue import Queue
# Handle WebSocket clients
clients = []
### Handler -------------------------------------------------------------------
class WebSocketHandler(tornado.websocket.WebSocketHandler):
""" Handle default WebSocket connections """
# Logging settings
logger = logging.getLogger("WebSocketHandler")
logger.setLevel(logging.INFO)
def open(self):
""" New connection has been established """
clients.append(self)
self.logger.info("New connection")
def on_message(self, message):
""" Data income event callback """
self.write_message(u"%s" % message)
def on_close(self):
""" Connection was closed """
clients.remove(self)
self.logger.info("Connection removed")
class IndexPageHandler(tornado.web.RequestHandler):
""" Default index page handler. Not implemented yet. """
def get(self):
pass
### Classes -------------------------------------------------------------------
class Application(tornado.web.Application):
def __init__(self):
# Add here several handlers
handlers = [
(r'/', IndexPageHandler),
(r'/websocket', WebSocketHandler)
]
# Application settings
settings = {
'template_path': 'templates'
}
# Call parents constructor
tornado.web.Application.__init__(self, handlers, **settings)
class HTTPServer():
""" Create tornado HTTP server serving our application """
def __init__(self, host, port, in_queue=Queue()):
# Settings
self.application = Application()
self.server = tornado.httpserver.HTTPServer(self.application)
self.host = host
self.port = port
self.in_queue = in_queue
# Listen to ..
self.server.listen(self.port, self.host)
# Logging settings
logging.basicConfig(level=logging.DEBUG)
self.logger = logging.getLogger("HTTPServer")
self.logger.setLevel(logging.INFO)
def start_server(self):
""" Start HTTP server """
self.logger.info("Starting HTTP server on port %d" % self.port)
http_server = Thread(target=tornado.ioloop.IOLoop.instance().start)
http_server.start()
def start_collector(self):
""" Start collector server """
self.logger.info("Start collector server")
collector_server = Thread(target=self.collect_data)
collector_server.start()
def collector_process_data(self, data):
""" Process incoming data and send it to all available clients """
for c in clients:
c.on_message(json.dumps(data))
def collect_data(self):
""" Wait for data in individual thread """
self.logger.info("Waiting for incoming data ...")
while True:
item = self.in_queue.get()
self.logger.info("Received data!")
self.collector_process_data(item)
def start(self):
""" Start server """
# Start HTTP server
self.start_server()
# Start data collector
self.start_collector()
| {'content_hash': '17791bb435a841b01c4b0e3d8a37495c', 'timestamp': '', 'source': 'github', 'line_count': 110, 'max_line_length': 79, 'avg_line_length': 29.818181818181817, 'alnum_prop': 0.5963414634146341, 'repo_name': 'dorneanu/pyTCP2WS', 'id': '2a7e3cbb0fb04d9bd1675f4034266840dbca2aea', 'size': '3326', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/WebSocketServer.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Python', 'bytes': '6931'}]} |
2017-11-17 23:24:10
Run with arguments ./test/criticalpracticalreason.c2-3200 none
## Description
Just try all
| {'content_hash': 'b6ceb4544600704c8fe3cf4aaf9df016', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 62, 'avg_line_length': 16.285714285714285, 'alnum_prop': 0.7719298245614035, 'repo_name': 'philayres/babble-rnn', 'id': '11aa41c93c35674921c22dfd5c65c73b05089fd9', 'size': '135', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'out/func-20-9-1/notes.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Jupyter Notebook', 'bytes': '2230415'}, {'name': 'Python', 'bytes': '69065'}, {'name': 'Shell', 'bytes': '2257'}]} |
class Category < ActiveRecord::Base
self.primary_key = 'not_default_id_name'
acts_as_nested_set
def to_s
name
end
def recurse(&block)
block.call self, lambda{
self.children.each do |child|
child.recurse(&block)
end
}
end
end
class Category_NoToArray < Category
def to_a
raise 'to_a called'
end
end
class Category_DefaultScope < Category
default_scope order('categories.not_default_id_name ASC')
end
class Category_WithCustomDestroy < ActiveRecord::Base
self.table_name = 'categories'
self.primary_key = 'not_default_id_name'
acts_as_nested_set
private :destroy
def custom_destroy
destroy
end
end
| {'content_hash': '2ec1735c209215512e23222643e5a2c8', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 59, 'avg_line_length': 17.710526315789473, 'alnum_prop': 0.6909361069836553, 'repo_name': 'skyeagle/nested_set', 'id': 'eecf058f16f4085bfefe0f7af364d6ddcd852ab5', 'size': '673', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'test/fixtures/category.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '76158'}]} |
"""Test entry formatting and printing."""
import bibpy
import pytest
@pytest.fixture
def test_entries():
return bibpy.read_file('tests/data/simple_1.bib', 'biblatex').entries
def test_formatting(test_entries):
print(test_entries[0].format())
assert test_entries[0].format(align=True, indent=' ') ==\
"""@article{test,
author = {James Conway and Archer Sterling},
title = {1337 Hacker},
year = {2010},
month = {4},
institution = {Office of Information Management {and} Communications}
}"""
assert test_entries[1].format(align=True, indent=' ', order=[]) ==\
"""@conference{anything,
author = {k}
}"""
def test_align(test_entries):
assert test_entries[0].format(align=False, indent=' ') ==\
"""@article{test,
author = {James Conway and Archer Sterling},
title = {1337 Hacker},
year = {2010},
month = {4},
institution = {Office of Information Management {and} Communications}
}"""
def test_indent(test_entries, monkeypatch):
assert test_entries[0].format(align=True, indent='') ==\
"""@article{test,
author = {James Conway and Archer Sterling},
title = {1337 Hacker},
year = {2010},
month = {4},
institution = {Office of Information Management {and} Communications}
}"""
assert test_entries[0].format(align=True, indent=' ' * 9) ==\
"""@article{test,
author = {James Conway and Archer Sterling},
title = {1337 Hacker},
year = {2010},
month = {4},
institution = {Office of Information Management {and} Communications}
}"""
def test_ordering(test_entries, monkeypatch):
for fail in ('string', 0.453245, object()):
with pytest.raises(ValueError):
test_entries[0].format(order=fail)
# Print a predefined order
order = ['author', 'title', 'year', 'institution', 'month']
assert test_entries[0].format(align=True, indent=' ', order=order) ==\
"""@article{test,
author = {James Conway and Archer Sterling},
title = {1337 Hacker},
year = {2010},
institution = {Office of Information Management {and} Communications},
month = {4}
}"""
# Print fields as sorted
assert test_entries[0].format(align=True, indent=' ', order=True) ==\
"""@article{test,
author = {James Conway and Archer Sterling},
institution = {Office of Information Management {and} Communications},
month = {4},
title = {1337 Hacker},
year = {2010}
}"""
| {'content_hash': '6914ba65ae0885dc55df4f94e6ea1973', 'timestamp': '', 'source': 'github', 'line_count': 86, 'max_line_length': 78, 'avg_line_length': 30.41860465116279, 'alnum_prop': 0.5909785932721713, 'repo_name': 'MisanthropicBit/bibpy', 'id': 'd9fd2a781f183428da0c1be3ea64a8ac782879b3', 'size': '2641', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/test_formatting.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Perl', 'bytes': '13208'}, {'name': 'Python', 'bytes': '224105'}, {'name': 'TeX', 'bytes': '361020'}]} |
package com.couchbase.spark.query
import com.couchbase.client.core.error.DmlFailureException
import com.couchbase.client.scala.codec.JsonDeserializer.Passthrough
import com.couchbase.client.scala.json.JsonObject
import com.couchbase.client.scala.query.{QueryScanConsistency, QueryOptions => CouchbaseQueryOptions}
import com.couchbase.spark.DefaultConstants
import com.couchbase.spark.config.{CouchbaseConfig, CouchbaseConnection}
import org.apache.spark.api.java.function.ForeachPartitionFunction
import org.apache.spark.internal.Logging
import org.apache.spark.sql.connector.catalog.{Table, TableProvider}
import org.apache.spark.sql.connector.expressions.Transform
import org.apache.spark.sql.sources.{BaseRelation, CreatableRelationProvider, DataSourceRegister}
import org.apache.spark.sql.types.StructType
import org.apache.spark.sql.util.CaseInsensitiveStringMap
import org.apache.spark.sql.{DataFrame, Encoders, SQLContext, SaveMode, SparkSession}
import scala.collection.JavaConverters._
import java.util
import scala.concurrent.duration.Duration
class QueryTableProvider extends TableProvider with Logging with DataSourceRegister with CreatableRelationProvider {
override def shortName(): String = "couchbase.query"
private lazy val sparkSession = SparkSession.active
private lazy val conf = CouchbaseConfig(sparkSession.sparkContext.getConf)
/**
* InferSchema is always called if the user does not pass in an explicit schema.
*
* @param options the options provided from the user.
* @return the inferred schema, if possible.
*/
override def inferSchema(options: CaseInsensitiveStringMap): StructType = {
if (isWrite) {
logDebug("Not inferring schema because called from the DataFrameWriter")
return null
}
val idFieldName = Option(options.get(QueryOptions.IdFieldName)).getOrElse(DefaultConstants.DefaultIdFieldName)
val whereClause = Option(options.get(QueryOptions.Filter)).map(p => s" WHERE $p").getOrElse("")
val bucketName = conf.implicitBucketNameOr(options.get(QueryOptions.Bucket))
val inferLimit = Option(options.get(QueryOptions.InferLimit)).getOrElse(DefaultConstants.DefaultInferLimit)
val scanConsistency = Option(options.get(QueryOptions.ScanConsistency))
.getOrElse(DefaultConstants.DefaultQueryScanConsistency)
val opts = CouchbaseQueryOptions()
scanConsistency match {
case QueryOptions.NotBoundedScanConsistency => opts.scanConsistency(QueryScanConsistency.NotBounded)
case QueryOptions.RequestPlusScanConsistency => opts.scanConsistency(QueryScanConsistency.RequestPlus())
case v => throw new IllegalArgumentException("Unknown scanConsistency of " + v)
}
val scopeName = conf.implicitScopeNameOr(options.get(QueryOptions.Scope)).getOrElse(DefaultConstants.DefaultScopeName)
val collectionName = conf.implicitCollectionName(options.get(QueryOptions.Collection)).getOrElse(DefaultConstants.DefaultCollectionName)
val result = if (scopeName.equals(DefaultConstants.DefaultScopeName) && collectionName.equals(DefaultConstants.DefaultCollectionName)) {
val statement = s"SELECT META().id as $idFieldName, `$bucketName`.* FROM `$bucketName`$whereClause LIMIT $inferLimit"
logDebug(s"Inferring schema from bucket $bucketName with query '$statement'")
CouchbaseConnection().cluster(conf).query(statement, opts)
} else {
val statement = s"SELECT META().id as $idFieldName, `$collectionName`.* FROM `$collectionName`$whereClause LIMIT $inferLimit"
logDebug(s"Inferring schema from bucket/scope/collection $bucketName/$scopeName/$collectionName with query '$statement'")
CouchbaseConnection().cluster(conf).bucket(bucketName).scope(scopeName).query(statement, opts)
}
val rows = result.flatMap(result => result.rowsAs[String](Passthrough.StringConvert)).get
val ds = sparkSession.sqlContext.createDataset(rows)(Encoders.STRING)
val schema = sparkSession.sqlContext.read.json(ds).schema
logDebug(s"Inferred schema is $schema")
schema
}
/**
* This is a hack because even from the DataFrameWriter the infer schema is called - even though
* we accept any schema.
*
* So check the stack where we are coming from and it allows to bail out early since we don't care
* about the schema on a write op at all.
*
* @return true if we are in a write op, this is a hack.
*/
def isWrite: Boolean =
Thread.currentThread().getStackTrace.exists(_.getClassName.contains("DataFrameWriter"))
def readConfig(properties: util.Map[String, String]): QueryReadConfig = {
QueryReadConfig(
conf.implicitBucketNameOr(properties.get(QueryOptions.Bucket)),
conf.implicitScopeNameOr(properties.get(QueryOptions.Scope)),
conf.implicitCollectionName(properties.get(QueryOptions.Collection)),
Option(properties.get(QueryOptions.IdFieldName)).getOrElse(DefaultConstants.DefaultIdFieldName),
Option(properties.get(QueryOptions.Filter)),
Option(properties.get(QueryOptions.ScanConsistency)).getOrElse(DefaultConstants.DefaultQueryScanConsistency),
Option(properties.get(QueryOptions.Timeout)),
Option(properties.get(QueryOptions.PushDownAggregate)).getOrElse("true").toBoolean
)
}
def writeConfig(properties: util.Map[String, String]): QueryWriteConfig = {
QueryWriteConfig(
conf.implicitBucketNameOr(properties.get(QueryOptions.Bucket)),
conf.implicitScopeNameOr(properties.get(QueryOptions.Scope)),
conf.implicitCollectionName(properties.get(QueryOptions.Collection)),
Option(properties.get(QueryOptions.IdFieldName)).getOrElse(DefaultConstants.DefaultIdFieldName),
Option(properties.get(QueryOptions.Timeout))
)
}
/**
* Returns the "Table", either with an inferred schema or a user provide schema.
*
* @param schema the schema, either inferred or provided by the user.
* @param partitioning partitioning information.
* @param properties the properties for customization
* @return the table instance which performs the actual work inside it.
*/
override def getTable(schema: StructType, partitioning: Array[Transform], properties: util.Map[String, String]): Table =
new QueryTable(schema, partitioning, properties, readConfig(properties))
/**
* We allow a user passing in a custom schema.
*/
override def supportsExternalMetadata(): Boolean = true
override def createRelation(ctx: SQLContext, mode: SaveMode, properties: Map[String, String], data: DataFrame): BaseRelation = {
val writeConfig = this.writeConfig(properties.asJava)
val couchbaseConfig = CouchbaseConfig(ctx.sparkContext.getConf)
data.toJSON.foreachPartition(new RelationPartitionWriter(writeConfig, couchbaseConfig, mode))
new BaseRelation {
override def sqlContext: SQLContext = ctx
override def schema: StructType = data.schema
}
}
}
class RelationPartitionWriter(writeConfig: QueryWriteConfig, couchbaseConfig: CouchbaseConfig, mode: SaveMode)
extends ForeachPartitionFunction[String]
with Logging {
override def call(t: util.Iterator[String]): Unit = {
val scopeName = writeConfig.scope.getOrElse(DefaultConstants.DefaultScopeName)
val collectionName = writeConfig.collection.getOrElse(DefaultConstants.DefaultCollectionName)
val values = t.asScala.map(encoded => {
val decoded = JsonObject.fromJson(encoded)
val id = decoded.str(writeConfig.idFieldName)
decoded.remove(writeConfig.idFieldName)
s"VALUES ('$id', ${decoded.toString})"
}).mkString(", ")
val prefix = mode match {
case SaveMode.ErrorIfExists | SaveMode.Ignore => "INSERT"
case SaveMode.Overwrite => "UPSERT"
case SaveMode.Append => throw new IllegalArgumentException("SaveMode.Append is not support with couchbase.query " +
"DataFrame on write. Please use ErrorIfExists, Ignore or Overwrite instead.")
}
val statement = if (scopeName.equals(DefaultConstants.DefaultScopeName) &&
collectionName.equals(DefaultConstants.DefaultCollectionName)) {
s"$prefix INTO `${writeConfig.bucket}` (KEY, VALUE) $values"
} else {
s"$prefix INTO `$collectionName` (KEY, VALUE) $values"
}
logDebug("Building and running N1QL query " + statement)
val opts = buildOptions()
try {
val result = if (scopeName.equals(DefaultConstants.DefaultScopeName) && collectionName.equals(DefaultConstants.DefaultCollectionName)) {
CouchbaseConnection().cluster(couchbaseConfig).query(statement, opts).get
} else {
CouchbaseConnection().cluster(couchbaseConfig).bucket(writeConfig.bucket).scope(scopeName).query(statement, opts).get
}
logDebug("Completed query in: " + result.metaData.metrics.get)
} catch {
case e: DmlFailureException =>
if (mode == SaveMode.Ignore) {
logDebug("Failed to run query, but ignoring because of SaveMode.Ignore: ", e)
} else {
throw e
}
}
}
def buildOptions(): CouchbaseQueryOptions = {
var opts = CouchbaseQueryOptions().metrics(true)
writeConfig.timeout.foreach(t => opts = opts.timeout(Duration(t)))
opts
}
}
| {'content_hash': '0bbf9637a417df88c4288c4870504355', 'timestamp': '', 'source': 'github', 'line_count': 199, 'max_line_length': 142, 'avg_line_length': 46.15577889447236, 'alnum_prop': 0.7518780620577028, 'repo_name': 'couchbaselabs/couchbase-spark-connector', 'id': '9864e52680bbc418e56a91d4547830133fc67862', 'size': '9786', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/scala/com/couchbase/spark/query/QueryTableProvider.scala', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '15884'}, {'name': 'Scala', 'bytes': '87210'}]} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:id="@id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="test......." />
<com.panda.videolivecore.view.CircleImageView
android:id="@id/faceCategroyTabs"
android:layout_width="40.0dip"
android:layout_height="40.0dip"
android:layout_centerInParent="true"
android:src="@drawable/default_head_img"
app:border_width="2.0dip" />
</LinearLayout> | {'content_hash': '5a0e1f35195d0dd64a4bfc8d752a61c9', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 72, 'avg_line_length': 37.63636363636363, 'alnum_prop': 0.6654589371980676, 'repo_name': 'chenstrace/Videoliveplatform', 'id': 'c4d9570add81ac7db94d2a1435b2e3c4710201d8', 'size': '828', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/res/layout/my_fragment.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '1022198'}, {'name': 'Makefile', 'bytes': '1030956'}, {'name': 'Shell', 'bytes': '410'}]} |
package org.fusesource.insight.graph.support;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Properties;
/**
* A helper factory class for creating Quartz {@link Scheduler} instances
*/
public class SchedulerFactory {
private static final transient Logger LOG = LoggerFactory.getLogger(SchedulerFactory.class);
private static final String PID = "org.fusesource.insight.graph";
private StdSchedulerFactory factory = new StdSchedulerFactory();
private Properties properties = new Properties();
private ConfigurationAdmin configAdmin;
public Scheduler createScheduler() throws SchedulerException {
if (configAdmin != null) {
try {
Configuration configuration = configAdmin.getConfiguration(PID);
Dictionary dictionary = configuration.getProperties();
if (dictionary == null) {
LOG.warn("No properties for configuration: " + PID);
} else {
Enumeration e = dictionary.keys();
if (e == null) {
LOG.warn("No properties for configuration: " + PID);
} else {
properties = new Properties();
while (e.hasMoreElements()) {
Object key = e.nextElement();
if (key != null) {
properties.put(key.toString(), dictionary.get(key));
}
}
}
}
} catch (IOException e) {
LOG.warn("Failed to get configuration for PID: " + PID);
}
}
LOG.info("Creating Quartz Schedular using properties: " + properties);
factory.initialize(properties);
return factory.getScheduler();
}
public StdSchedulerFactory getFactory() {
return factory;
}
public void setFactory(StdSchedulerFactory factory) {
this.factory = factory;
}
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
public ConfigurationAdmin getConfigAdmin() {
return configAdmin;
}
public void setConfigAdmin(ConfigurationAdmin configAdmin) {
this.configAdmin = configAdmin;
}
}
| {'content_hash': '0636a6df1d12cc800f8e6edd6fb70822', 'timestamp': '', 'source': 'github', 'line_count': 82, 'max_line_length': 96, 'avg_line_length': 33.21951219512195, 'alnum_prop': 0.6035242290748899, 'repo_name': 'Jitendrakry/fuse', 'id': '15e43f5c22f3a66fbc72c8e514aa5d65b48ed89b', 'size': '3347', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'insight/insight-graph/src/main/java/org/fusesource/insight/graph/support/SchedulerFactory.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '16117'}, {'name': 'GAP', 'bytes': '3273'}, {'name': 'Java', 'bytes': '2573655'}, {'name': 'Scala', 'bytes': '172894'}, {'name': 'Shell', 'bytes': '767'}, {'name': 'XSLT', 'bytes': '2430'}]} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content" android:orientation="vertical" android:layout_width="fill_parent">
<TextView android:text="@+id/TextView01" android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:singleLine="true" android:textStyle="bold" android:layout_marginTop="5dip" android:layout_marginLeft="5dip" android:padding="15dip"></TextView>
</LinearLayout>
| {'content_hash': 'be6f4c589d51065be5719531a1f6d478', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 294, 'avg_line_length': 88.5, 'alnum_prop': 0.7721280602636534, 'repo_name': 'tectronics/wiki-to-speech', 'id': 'bdff7b560d1450f6f50ed6281164502441a7c3d8', 'size': '531', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'res/layout/history_view.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '872'}, {'name': 'Java', 'bytes': '132804'}]} |
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Tag
*
* @ORM\Table(name="tag")
* @ORM\Entity(repositoryClass="AppBundle\Repository\TagRepository")
*/
class Tag
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="tagName", type="string", length=255)
*/
private $tagName;
/**
* @var string
*
* @ORM\Column(name="status", type="string", length=255, nullable=true)
*/
private $status;
/**
* @var int
*
* @ORM\Column(name="noOfVotes", type="integer", nullable=true)
*/
private $noOfVotes;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="tag")
*/
private $user;
/**
* @ORM\ManyToMany(targetEntity="Reference", mappedBy="referenceTags")
*/
private $tagReferences;
public function __construct()
{
$this->tagReferences = new ArrayCollection();
}
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set tagName
*
* @param string $tagName
*
* @return tag
*/
public function setTagName($tagName)
{
$this->tagName = $tagName;
return $this;
}
/**
* Get tagName
*
* @return string
*/
public function getTagName()
{
return $this->tagName;
}
/**
* Set status
*
* @param string $status
*
* @return tag
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* @return string
*/
public function getStatus()
{
return $this->status;
}
/**
* Set noOfVotes
*
* @param integer $noOfVotes
*
* @return tag
*/
public function setNoOfVotes($noOfVotes)
{
$this->noOfVotes = $noOfVotes;
return $this;
}
/**
* Get noOfVotes
*
* @return int
*/
public function getNoOfVotes()
{
return $this->noOfVotes;
}
/**
* @return mixed
*/
public function getUser()
{
return $this->user;
}
/**
* @param mixed $user
*/
public function setUser(User $user)
{
$this->user = $user;
}
/**
* @return ArrayCollection|Reference[]
*/
public function getTagReferences()
{
return $this->tagReferences;
}
}
| {'content_hash': '15e580b7d56a9d0d8ea3461b16de0be0', 'timestamp': '', 'source': 'github', 'line_count': 170, 'max_line_length': 75, 'avg_line_length': 15.829411764705883, 'alnum_prop': 0.5024154589371981, 'repo_name': 'lauramcloughlin/web3_project', 'id': '27f8196eebf8a75c00f1dd883f9b653840264c79', 'size': '2691', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/AppBundle/Entity/Tag.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '3605'}, {'name': 'CSS', 'bytes': '2683'}, {'name': 'HTML', 'bytes': '36327'}, {'name': 'PHP', 'bytes': '243252'}]} |
"""Unit tests to cover Error Handling examples."""
__author__ = '[email protected] (Kevin Winter)'
import os
import sys
sys.path.insert(0, os.path.join('..', '..', '..', '..'))
import time
import unittest
from examples.adspygoogle.adwords.v201306.error_handling import handle_partial_failures
from examples.adspygoogle.adwords.v201306.error_handling import handle_two_factor_authorization_error
from tests.adspygoogle.adwords import client
from tests.adspygoogle.adwords import SERVER_V201306
from tests.adspygoogle.adwords import TEST_VERSION_V201306
from tests.adspygoogle.adwords import util
from tests.adspygoogle.adwords import VERSION_V201306
class ErrorHandling(unittest.TestCase):
"""Unittest suite for Error Handling code examples."""
SERVER = SERVER_V201306
VERSION = VERSION_V201306
client.debug = False
loaded = False
def setUp(self):
"""Prepare unittest."""
time.sleep(1)
client.use_mcc = False
if not self.__class__.loaded:
self.__class__.campaign_id = util.CreateTestCampaign(client)
self.__class__.ad_group_id = util.CreateTestAdGroup(
client, self.__class__.campaign_id)
self.__class__.loaded = True
def tearDown(self):
"""Reset partial failure."""
client.partial_failure = False
def testHandlePartialFailures(self):
"""Tests whether we can handle partial failures."""
handle_partial_failures.main(client, self.__class__.ad_group_id)
def testHandleTwoFactorAuthorizationError(self):
"""Test whether we can handle two factor authorization errors."""
handle_two_factor_authorization_error.main()
if __name__ == '__main__':
if TEST_VERSION_V201306:
unittest.main()
| {'content_hash': 'b7ec457669d3d459d0757121fa529e32', 'timestamp': '', 'source': 'github', 'line_count': 54, 'max_line_length': 101, 'avg_line_length': 31.25925925925926, 'alnum_prop': 0.7227488151658767, 'repo_name': 'donspaulding/adspygoogle', 'id': '7d1cb9af3b743a212b7d17d5980cc016b787bd6a', 'size': '2306', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/adspygoogle/adwords/examples/error_handling_unittest.py', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '3734067'}, {'name': 'Shell', 'bytes': '603'}]} |
require File.expand_path('../../test_helper', __FILE__)
class ContactsCsvControllerTest < ActionController::TestCase
# Replace this with your real tests.
def test_truth
assert true
end
end
| {'content_hash': '98658b4e181e64a954cc6794fdd25624', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 60, 'avg_line_length': 25.0, 'alnum_prop': 0.725, 'repo_name': 'druidPollux/RedmineCRM', 'id': 'e85dc023ceba2a280bc08af554da429b68d5e8af', 'size': '1060', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'plugins/redmine_contacts/test/functional/contacts_csv_controller_test.rb', 'mode': '33188', 'license': 'mit', 'language': []} |
/**
* Module dependencies
*/
var request = require('../lib/request')
/**
* List Roles
*/
function listRoles (clientId, options) {
options = options || {}
options.url = '/v1/clients/' + clientId + '/roles'
return request.bind(this)(options)
}
exports.listRoles = listRoles
/**
* Add Role
*/
function addRole (client, role, options) {
options = options || {}
options.url = '/v1/clients/' + client + '/roles/' + role
options.method = 'PUT'
return request.bind(this)(options)
}
exports.addRole = addRole
/**
* Delete Role
*/
function deleteRole (client, role, options) {
options = options || {}
options.url = '/v1/clients/' + client + '/roles/' + role
options.method = 'DELETE'
delete options.json
return request.bind(this)(options)
}
exports.deleteRole = deleteRole
| {'content_hash': 'eb33b8e3cf89b55e1f671befabaff8b2', 'timestamp': '', 'source': 'github', 'line_count': 44, 'max_line_length': 58, 'avg_line_length': 18.295454545454547, 'alnum_prop': 0.6472049689440994, 'repo_name': 'anvilresearch/connect-nodejs', 'id': 'e7592490cd0a4793887254b6f410cbfde7d4f293', 'size': '805', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'rest/clientRoles.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CoffeeScript', 'bytes': '106638'}, {'name': 'JavaScript', 'bytes': '46443'}]} |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include <boost/optional/optional.hpp>
#include <gflags/gflags.h>
#include <gflags/gflags_declare.h>
#include <rapidjson/document.h>
#include "kudu/client/client.h"
#include "kudu/client/replica_controller-internal.h"
#include "kudu/client/scan_batch.h"
#include "kudu/client/scan_predicate.h"
#include "kudu/client/schema.h"
#include "kudu/client/shared_ptr.h"
#include "kudu/client/value.h"
#include "kudu/common/partition.h"
#include "kudu/common/schema.h"
#include "kudu/gutil/map-util.h"
#include "kudu/gutil/stl_util.h"
#include "kudu/gutil/strings/join.h"
#include "kudu/gutil/strings/split.h"
#include "kudu/gutil/strings/substitute.h"
#include "kudu/tools/table_scanner.h"
#include "kudu/tools/tool_action.h"
#include "kudu/tools/tool_action_common.h"
#include "kudu/util/jsonreader.h"
#include "kudu/util/status.h"
using kudu::client::KuduClient;
using kudu::client::KuduClientBuilder;
using kudu::client::KuduColumnSchema;
using kudu::client::KuduPredicate;
using kudu::client::KuduScanToken;
using kudu::client::KuduScanTokenBuilder;
using kudu::client::KuduScanner;
using kudu::client::KuduSchema;
using kudu::client::KuduTable;
using kudu::client::KuduTableAlterer;
using kudu::client::internal::ReplicaController;
using std::cerr;
using std::cout;
using std::endl;
using std::string;
using std::unique_ptr;
using std::vector;
using strings::Split;
using strings::Substitute;
DEFINE_bool(check_row_existence, false,
"Also check for the existence of the row on the leader replica of "
"the tablet. If found, the full row will be printed; if not found, "
"an error message will be printed and the command will return a "
"non-zero status.");
DEFINE_string(dst_table, "",
"The name of the destination table the data will be copied to. "
"If the empty string, use the same name as the source table.");
DEFINE_bool(list_tablets, false,
"Include tablet and replica UUIDs in the output");
DEFINE_bool(modify_external_catalogs, true,
"Whether to modify external catalogs, such as the Hive Metastore, "
"when renaming or dropping a table.");
DECLARE_bool(show_values);
DECLARE_string(tables);
namespace kudu {
namespace tools {
// This class only exists so that ListTables() can easily be friended by
// KuduReplica, KuduReplica::Data, and KuduClientBuilder.
class TableLister {
public:
static Status ListTablets(const vector<string>& master_addresses) {
KuduClientBuilder builder;
ReplicaController::SetVisibility(&builder, ReplicaController::Visibility::ALL);
client::sp::shared_ptr<KuduClient> client;
RETURN_NOT_OK(builder
.master_server_addrs(master_addresses)
.Build(&client));
vector<string> table_names;
RETURN_NOT_OK(client->ListTables(&table_names));
vector<string> table_filters = Split(FLAGS_tables, ",", strings::SkipEmpty());
for (const auto& tname : table_names) {
if (!MatchesAnyPattern(table_filters, tname)) continue;
cout << tname << endl;
if (!FLAGS_list_tablets) {
continue;
}
client::sp::shared_ptr<KuduTable> client_table;
RETURN_NOT_OK(client->OpenTable(tname, &client_table));
vector<KuduScanToken*> tokens;
ElementDeleter deleter(&tokens);
KuduScanTokenBuilder builder(client_table.get());
RETURN_NOT_OK(builder.Build(&tokens));
for (const auto* token : tokens) {
cout << " T " << token->tablet().id() << endl;
for (const auto* replica : token->tablet().replicas()) {
const bool is_voter = ReplicaController::is_voter(*replica);
const bool is_leader = replica->is_leader();
cout << Substitute(" $0 $1 $2:$3",
is_leader ? "L" : (is_voter ? "V" : "N"), replica->ts().uuid(),
replica->ts().hostname(), replica->ts().port()) << endl;
}
cout << endl;
}
cout << endl;
}
return Status::OK();
}
};
namespace {
const char* const kNewTableNameArg = "new_table_name";
const char* const kColumnNameArg = "column_name";
const char* const kNewColumnNameArg = "new_column_name";
const char* const kKeyArg = "primary_key";
const char* const kDestMasterAddressesArg = "dest_master_addresses";
Status DeleteTable(const RunnerContext& context) {
const string& table_name = FindOrDie(context.required_args, kTableNameArg);
client::sp::shared_ptr<KuduClient> client;
RETURN_NOT_OK(CreateKuduClient(context, &client));
return client->DeleteTableInCatalogs(table_name, FLAGS_modify_external_catalogs);
}
Status DescribeTable(const RunnerContext& context) {
client::sp::shared_ptr<KuduClient> client;
RETURN_NOT_OK(CreateKuduClient(context, &client));
const string& table_name = FindOrDie(context.required_args, kTableNameArg);
client::sp::shared_ptr<KuduTable> table;
RETURN_NOT_OK(client->OpenTable(table_name, &table));
// The schema.
const KuduSchema& schema = table->schema();
cout << "TABLE " << table_name << " " << schema.ToString() << endl;
// The partition schema with current range partitions.
vector<Partition> partitions;
RETURN_NOT_OK_PREPEND(table->ListPartitions(&partitions),
"failed to retrieve current partitions");
const auto& schema_internal = KuduSchema::ToSchema(schema);
const auto& partition_schema = table->partition_schema();
vector<string> partition_strs;
for (const auto& partition : partitions) {
// Deduplicate by hash bucket to get a unique entry per range partition.
const auto& hash_buckets = partition.hash_buckets();
if (!std::all_of(hash_buckets.begin(),
hash_buckets.end(),
[](int32_t bucket) { return bucket == 0; })) {
continue;
}
auto range_partition_str =
partition_schema.RangePartitionDebugString(partition.range_key_start(),
partition.range_key_end(),
schema_internal);
partition_strs.emplace_back(std::move(range_partition_str));
}
cout << partition_schema.DisplayString(schema_internal, partition_strs)
<< endl;
// Finally, the replication factor.
cout << "REPLICAS " << table->num_replicas() << endl;
return Status::OK();
}
Status LocateRow(const RunnerContext& context) {
client::sp::shared_ptr<KuduClient> client;
RETURN_NOT_OK(CreateKuduClient(context, &client));
const string& table_name = FindOrDie(context.required_args, kTableNameArg);
client::sp::shared_ptr<KuduTable> table;
RETURN_NOT_OK(client->OpenTable(table_name, &table));
// Create an equality predicate for each primary key column.
const string& row_str = FindOrDie(context.required_args, kKeyArg);
JsonReader reader(row_str);
RETURN_NOT_OK(reader.Init());
vector<const rapidjson::Value*> values;
RETURN_NOT_OK(reader.ExtractObjectArray(reader.root(),
/*field=*/nullptr,
&values));
const auto& schema = table->schema();
vector<int> key_indexes;
schema.GetPrimaryKeyColumnIndexes(&key_indexes);
if (values.size() != key_indexes.size()) {
return Status::InvalidArgument(
Substitute("wrong number of key columns specified: expected $0 but received $1",
key_indexes.size(),
values.size()));
}
vector<unique_ptr<KuduPredicate>> predicates;
for (int i = 0; i < values.size(); i++) {
const auto key_index = key_indexes[i];
const auto& column = schema.Column(key_index);
const auto& col_name = column.name();
const auto type = column.type();
switch (type) {
case KuduColumnSchema::INT8:
case KuduColumnSchema::INT16:
case KuduColumnSchema::INT32:
case KuduColumnSchema::INT64:
case KuduColumnSchema::UNIXTIME_MICROS: {
int64_t value;
RETURN_NOT_OK_PREPEND(
reader.ExtractInt64(values[i], /*field=*/nullptr, &value),
Substitute("unable to parse value for column '$0' of type $1",
col_name,
KuduColumnSchema::DataTypeToString(type)));
predicates.emplace_back(
table->NewComparisonPredicate(col_name,
client::KuduPredicate::EQUAL,
client::KuduValue::FromInt(value)));
break;
}
case KuduColumnSchema::BINARY:
case KuduColumnSchema::STRING: {
string value;
RETURN_NOT_OK_PREPEND(
reader.ExtractString(values[i], /*field=*/nullptr, &value),
Substitute("unable to parse value for column '$0' of type $1",
col_name,
KuduColumnSchema::DataTypeToString(type)));
predicates.emplace_back(
table->NewComparisonPredicate(col_name,
client::KuduPredicate::EQUAL,
client::KuduValue::CopyString(value)));
break;
}
case KuduColumnSchema::BOOL: {
// As of the writing of this tool, BOOL is not a supported key column
// type, but just in case it becomes one, we pre-load support for it.
bool value;
RETURN_NOT_OK_PREPEND(
reader.ExtractBool(values[i], /*field=*/nullptr, &value),
Substitute("unable to parse value for column '$0' of type $1",
col_name,
KuduColumnSchema::DataTypeToString(type)));
predicates.emplace_back(
table->NewComparisonPredicate(col_name,
client::KuduPredicate::EQUAL,
client::KuduValue::FromBool(value)));
break;
}
case KuduColumnSchema::FLOAT:
case KuduColumnSchema::DOUBLE: {
// Like BOOL, as of the writing of this tool, floating point types are
// not supported for key columns, but we can pre-load support for them
// in case they become supported.
double value;
RETURN_NOT_OK_PREPEND(
reader.ExtractDouble(values[i], /*field=*/nullptr, &value),
Substitute("unable to parse value for column '$0' of type $1",
col_name,
KuduColumnSchema::DataTypeToString(type)));
predicates.emplace_back(
table->NewComparisonPredicate(col_name,
client::KuduPredicate::EQUAL,
client::KuduValue::FromDouble(value)));
break;
}
case KuduColumnSchema::DECIMAL:
return Status::NotSupported(
Substitute("unsupported type $0 for key column '$1': "
"$0 key columns are not supported by this tool",
KuduColumnSchema::DataTypeToString(type),
col_name));
default:
return Status::NotSupported(
Substitute("unsupported type $0 for key column '$1': "
"is this tool out of date?",
KuduColumnSchema::DataTypeToString(type),
col_name));
}
}
// Find the tablet by constructing scan tokens for a scan with equality
// predicates on all key columns. At most one tablet will match, so there
// will be at most one token, and we can report the id of its tablet.
vector<KuduScanToken*> tokens;
ElementDeleter deleter(&tokens);
KuduScanTokenBuilder builder(table.get());
// In case we go on to check for existence of the row.
RETURN_NOT_OK(builder.SetSelection(KuduClient::ReplicaSelection::LEADER_ONLY));
for (auto& predicate : predicates) {
RETURN_NOT_OK(builder.AddConjunctPredicate(predicate.release()));
}
RETURN_NOT_OK(builder.Build(&tokens));
if (tokens.empty()) {
// Must be in a non-covered range partition.
return Status::NotFound("row does not belong to any currently existing tablet");
}
if (tokens.size() > 1) {
// This should be impossible. But if it does happen, we'd like to know what
// all the matching tablets were.
for (const auto& token : tokens) {
cerr << token->tablet().id() << endl;
}
return Status::IllegalState(Substitute(
"all primary key columns specified but found $0 matching tablets!",
tokens.size()));
}
cout << tokens[0]->tablet().id() << endl;
if (FLAGS_check_row_existence) {
KuduScanner* scanner_ptr;
RETURN_NOT_OK(tokens[0]->IntoKuduScanner(&scanner_ptr));
unique_ptr<KuduScanner> scanner(scanner_ptr);
RETURN_NOT_OK(scanner->Open());
vector<string> row_str;
client::KuduScanBatch batch;
while (scanner->HasMoreRows()) {
RETURN_NOT_OK(scanner->NextBatch(&batch));
for (const auto& row : batch) {
row_str.emplace_back(row.ToString());
}
}
if (row_str.empty()) {
return Status::NotFound("row does not exist");
}
// There should be exactly one result, but if somehow there are more, print
// them all before returning an error.
cout << JoinStrings(row_str, "\n") << endl;
if (row_str.size() != 1) {
// This should be impossible.
return Status::IllegalState(
Substitute("expected 1 row but received $0", row_str.size()));
}
}
return Status::OK();
}
Status RenameTable(const RunnerContext& context) {
const string& table_name = FindOrDie(context.required_args, kTableNameArg);
const string& new_table_name = FindOrDie(context.required_args, kNewTableNameArg);
client::sp::shared_ptr<KuduClient> client;
RETURN_NOT_OK(CreateKuduClient(context, &client));
unique_ptr<KuduTableAlterer> alterer(client->NewTableAlterer(table_name));
return alterer->RenameTo(new_table_name)
->modify_external_catalogs(FLAGS_modify_external_catalogs)
->Alter();
}
Status RenameColumn(const RunnerContext& context) {
const string& table_name = FindOrDie(context.required_args, kTableNameArg);
const string& column_name = FindOrDie(context.required_args, kColumnNameArg);
const string& new_column_name = FindOrDie(context.required_args, kNewColumnNameArg);
client::sp::shared_ptr<KuduClient> client;
RETURN_NOT_OK(CreateKuduClient(context, &client));
unique_ptr<KuduTableAlterer> alterer(client->NewTableAlterer(table_name));
alterer->AlterColumn(column_name)->RenameTo(new_column_name);
return alterer->Alter();
}
Status ListTables(const RunnerContext& context) {
const string& master_addresses_str = FindOrDie(context.required_args,
kMasterAddressesArg);
return TableLister::ListTablets(Split(master_addresses_str, ","));
}
Status ScanTable(const RunnerContext &context) {
client::sp::shared_ptr<KuduClient> client;
RETURN_NOT_OK(CreateKuduClient(context, &client));
const string& table_name = FindOrDie(context.required_args, kTableNameArg);
FLAGS_show_values = true;
TableScanner scanner(client, table_name);
scanner.SetOutput(&cout);
return scanner.StartScan();
}
Status CopyTable(const RunnerContext& context) {
client::sp::shared_ptr<KuduClient> src_client;
RETURN_NOT_OK(CreateKuduClient(context, &src_client));
const string& src_table_name = FindOrDie(context.required_args, kTableNameArg);
client::sp::shared_ptr<KuduClient> dst_client;
if (FindOrDie(context.required_args, kMasterAddressesArg)
== FindOrDie(context.required_args, kDestMasterAddressesArg)) {
dst_client = src_client;
} else {
RETURN_NOT_OK(CreateKuduClient(context, kDestMasterAddressesArg, &dst_client));
}
const string& dst_table_name = FLAGS_dst_table.empty() ? src_table_name : FLAGS_dst_table;
TableScanner scanner(src_client, src_table_name, dst_client, dst_table_name);
scanner.SetOutput(&cout);
return scanner.StartCopy();
}
} // anonymous namespace
unique_ptr<Mode> BuildTableMode() {
unique_ptr<Action> delete_table =
ActionBuilder("delete", &DeleteTable)
.Description("Delete a table")
.AddRequiredParameter({ kMasterAddressesArg, kMasterAddressesArgDesc })
.AddRequiredParameter({ kTableNameArg, "Name of the table to delete" })
.AddOptionalParameter("modify_external_catalogs")
.Build();
unique_ptr<Action> describe_table =
ActionBuilder("describe", &DescribeTable)
.Description("Describe a table")
.AddRequiredParameter({ kMasterAddressesArg, kMasterAddressesArgDesc })
.AddRequiredParameter({ kTableNameArg, "Name of the table to describe" })
.AddOptionalParameter("show_attributes")
.Build();
unique_ptr<Action> list_tables =
ActionBuilder("list", &ListTables)
.Description("List tables")
.AddRequiredParameter({ kMasterAddressesArg, kMasterAddressesArgDesc })
.AddOptionalParameter("tables")
.AddOptionalParameter("list_tablets")
.Build();
unique_ptr<Action> locate_row =
ActionBuilder("locate_row", &LocateRow)
.Description("Locate which tablet a row belongs to")
.ExtraDescription("Provide the primary key as a JSON array of primary "
"key values, e.g. '[1, \"foo\", 2, \"bar\"]'. The "
"output will be the tablet id associated with the row "
"key. If there is no such tablet, an error message "
"will be printed and the command will return a "
"non-zero status")
.AddRequiredParameter({ kMasterAddressesArg, kMasterAddressesArgDesc })
.AddRequiredParameter({ kTableNameArg, "Name of the table to look up against" })
.AddRequiredParameter({ kKeyArg,
"String representation of the row's primary key "
"as a JSON array" })
.AddOptionalParameter("check_row_existence")
.Build();
unique_ptr<Action> rename_column =
ActionBuilder("rename_column", &RenameColumn)
.Description("Rename a column")
.AddRequiredParameter({ kMasterAddressesArg, kMasterAddressesArgDesc })
.AddRequiredParameter({ kTableNameArg, "Name of the table to alter" })
.AddRequiredParameter({ kColumnNameArg, "Name of the table column to rename" })
.AddRequiredParameter({ kNewColumnNameArg, "New column name" })
.Build();
unique_ptr<Action> rename_table =
ActionBuilder("rename_table", &RenameTable)
.Description("Rename a table")
.AddRequiredParameter({ kMasterAddressesArg, kMasterAddressesArgDesc })
.AddRequiredParameter({ kTableNameArg, "Name of the table to rename" })
.AddRequiredParameter({ kNewTableNameArg, "New table name" })
.AddOptionalParameter("modify_external_catalogs")
.Build();
unique_ptr<Action> scan_table =
ActionBuilder("scan", &ScanTable)
.Description("Scan rows from a table")
.ExtraDescription("Scan rows from an existing table. See the help "
"for the --predicates flag on how predicates can be specified.")
.AddRequiredParameter({ kMasterAddressesArg, kMasterAddressesArgDesc })
.AddRequiredParameter({ kTableNameArg, "Name of the table to scan"})
.AddOptionalParameter("columns")
.AddOptionalParameter("fill_cache")
.AddOptionalParameter("num_threads")
.AddOptionalParameter("predicates")
.AddOptionalParameter("tablets")
.Build();
unique_ptr<Action> copy_table =
ActionBuilder("copy", &CopyTable)
.Description("Copy table data to another table")
.ExtraDescription("Copy table data to another table; the two tables could be in the same "
"cluster or not. The two tables must have the same table schema, but "
"could have different partition schemas. Alternatively, the tool can "
"create the new table using the same table and partition schema as the "
"source table.")
.AddRequiredParameter({ kMasterAddressesArg,
"Comma-separated list of Kudu Master addresses (source) "
"where each address is of form 'hostname:port'" })
.AddRequiredParameter({ kTableNameArg, "Name of the source table" })
.AddRequiredParameter({ kDestMasterAddressesArg,
"Comma-separated list of Kudu Master addresses (destination) "
"where each address is of form 'hostname:port'" })
.AddOptionalParameter("create_table")
.AddOptionalParameter("dst_table")
.AddOptionalParameter("num_threads")
.AddOptionalParameter("predicates")
.AddOptionalParameter("tablets")
.AddOptionalParameter("write_type")
.Build();
return ModeBuilder("table")
.Description("Operate on Kudu tables")
.AddAction(std::move(delete_table))
.AddAction(std::move(describe_table))
.AddAction(std::move(list_tables))
.AddAction(std::move(locate_row))
.AddAction(std::move(rename_column))
.AddAction(std::move(rename_table))
.AddAction(std::move(scan_table))
.AddAction(std::move(copy_table))
.Build();
}
} // namespace tools
} // namespace kudu
| {'content_hash': '6d159ac8e8776f676a3dd527e82f756a', 'timestamp': '', 'source': 'github', 'line_count': 536, 'max_line_length': 96, 'avg_line_length': 41.49813432835821, 'alnum_prop': 0.649148046576451, 'repo_name': 'InspurUSA/kudu', 'id': '5854858424b1efea3ec88890316ae0ced70e9db9', 'size': '22243', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/kudu/tools/tool_action_table.cc', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '423003'}, {'name': 'C++', 'bytes': '15661998'}, {'name': 'CMake', 'bytes': '214461'}, {'name': 'CSS', 'bytes': '1364'}, {'name': 'Clojure', 'bytes': '54903'}, {'name': 'Dockerfile', 'bytes': '8783'}, {'name': 'HTML', 'bytes': '29937'}, {'name': 'Java', 'bytes': '2209848'}, {'name': 'JavaScript', 'bytes': '8018'}, {'name': 'Makefile', 'bytes': '658'}, {'name': 'Perl', 'bytes': '35638'}, {'name': 'Python', 'bytes': '560901'}, {'name': 'R', 'bytes': '11537'}, {'name': 'Scala', 'bytes': '263860'}, {'name': 'Shell', 'bytes': '147843'}, {'name': 'Thrift', 'bytes': '80170'}]} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-GB" xml:lang="en-GB" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Statistics of root in UD_Tamil</title>
<link rel="root" href=""/> <!-- for JS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
<link rel="stylesheet" type="text/css" href="../../css/style.css"/>
<link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
<link rel="stylesheet" type="text/css" href="../../css/hint.css"/>
<script type="text/javascript" src="../../lib/ext/head.load.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/anchor-js/3.2.2/anchor.min.js"></script>
<script>document.addEventListener("DOMContentLoaded", function(event) {anchors.add();});</script>
<!-- Set up this custom Google search at https://cse.google.com/cse/business/settings?cx=001145188882102106025:dl1mehhcgbo -->
<!-- DZ 2021-01-22: I am temporarily hiding the search field to find out whether it slows down loading of the title page.
<script>
(function() {
var cx = '001145188882102106025:dl1mehhcgbo';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script> -->
<!-- <link rel="shortcut icon" href="favicon.ico"/> -->
</head>
<body>
<div id="main" class="center">
<div id="hp-header">
<table width="100%"><tr><td width="50%">
<span class="header-text"><a href="http://universaldependencies.org/#language-">home</a></span>
<span class="header-text"><a href="https://github.com/universaldependencies/docs/edit/pages-source/treebanks/ta_ttb/ta-dep-root.md" target="#">edit page</a></span>
<span class="header-text"><a href="https://github.com/universaldependencies/docs/issues">issue tracker</a></span>
</td><td>
<gcse:search></gcse:search>
</td></tr></table>
</div>
<hr/>
<div class="v2complete">
This page pertains to UD version 2.
</div>
<div id="content">
<noscript>
<div id="noscript">
It appears that you have Javascript disabled.
Please consider enabling Javascript for this page to see the visualizations.
</div>
</noscript>
<!-- The content may include scripts and styles, hence we must load the shared libraries before the content. -->
<script type="text/javascript">
console.time('loading libraries');
var root = '../../'; // filled in by jekyll
head.js(
// External libraries
// DZ: Copied from embedding.html. I don't know which one is needed for what, so I'm currently keeping them all.
root + 'lib/ext/jquery.min.js',
root + 'lib/ext/jquery.svg.min.js',
root + 'lib/ext/jquery.svgdom.min.js',
root + 'lib/ext/jquery.timeago.js',
root + 'lib/ext/jquery-ui.min.js',
root + 'lib/ext/waypoints.min.js',
root + 'lib/ext/jquery.address.min.js'
);
</script>
<h2 id="treebank-statistics-ud_tamil-relations-root">Treebank Statistics: UD_Tamil: Relations: <code class="language-plaintext highlighter-rouge">root</code></h2>
<p>This relation is universal.</p>
<p>600 nodes (6%) are attached to their parents as <code class="language-plaintext highlighter-rouge">root</code>.</p>
<p>600 instances of <code class="language-plaintext highlighter-rouge">root</code> (100%) are left-to-right (parent precedes child).
Average distance between parent and child is 14.2116666666667.</p>
<p>The following 6 pairs of parts of speech are connected with <code class="language-plaintext highlighter-rouge">root</code>: -<tt><a href="ta-pos-VERB.html">VERB</a></tt> (538; 90% instances), -<tt><a href="ta-pos-NOUN.html">NOUN</a></tt> (45; 8% instances), -<tt><a href="ta-pos-AUX.html">AUX</a></tt> (13; 2% instances), -<tt><a href="ta-pos-PROPN.html">PROPN</a></tt> (2; 0% instances), -<tt><a href="ta-pos-NUM.html">NUM</a></tt> (1; 0% instances), -<tt><a href="ta-pos-PRON.html">PRON</a></tt> (1; 0% instances).</p>
<pre><code class="language-conllu"># visual-style 2 bgColor:blue
# visual-style 2 fgColor:white
# visual-style 0 bgColor:blue
# visual-style 0 fgColor:white
# visual-style 0 2 root color:blue
1 அவர் அவர் PRON RpN-3SH-- Case=Nom|Gender=Com|Number=Sing|Person=3|Polite=Form|PronType=Prs 2 nsubj _ Translit=avar|LTranslit=avar
2 பேசியத் பேசு VERB VzND3SNAA Case=Nom|Gender=Neut|Number=Sing|Person=3|Polarity=Pos|Tense=Past|VerbForm=Ger|Voice=Act 0 root _ Translit=pēciyat|LTranslit=pēcu
3 ஆவது ஆவது PART Tl------- _ 2 advmod:emph _ Translit=āvatu|LTranslit=āvatu
4 : : PUNCT Z:------- PunctType=Comm 2 punct _ SpaceAfter=No|Translit=:|LTranslit=:
5 . . PUNCT Z#------- PunctType=Peri 2 punct _ Translit=.|LTranslit=.
</code></pre>
<pre><code class="language-conllu"># visual-style 6 bgColor:blue
# visual-style 6 fgColor:white
# visual-style 0 bgColor:blue
# visual-style 0 fgColor:white
# visual-style 0 6 root color:blue
1 கிழக்கு கிழக்கு NOUN NNN-3SN-- Case=Nom|Gender=Neut|Number=Sing|Person=3 2 nmod _ Translit=kilakku|LTranslit=kilakku
2 ஆசியா ஆசியா PROPN NEN-3SN-- Case=Nom|Gender=Neut|Number=Sing|Person=3 3 obj _ Translit=āciyā|LTranslit=āciyā
3 குறித்த குறி ADJ Jd-D----A Polarity=Pos|Tense=Past|VerbForm=Part 4 amod _ Translit=kuritta|LTranslit=kuri
4 பேச்சுவார்த்தை பேச்சுவார்த்தை NOUN NNA-3SN-- Case=Acc|Gender=Neut|Number=Sing|Person=3 5 obj _ Translit=pēccuvārttai|LTranslit=pēccuvārttai
5 நடத்த நடத்து VERB Vu-T---AA Polarity=Pos|VerbForm=Inf|Voice=Act 6 advcl _ Translit=naṭatta|LTranslit=naṭattu
6 முடிவு முடிவு NOUN NNN-3SN-- Case=Nom|Gender=Neut|Number=Sing|Person=3 0 root _ Translit=muṭivu|LTranslit=muṭivu
7 செய்யப் செய் VERB Vu-T---AA Polarity=Pos|VerbForm=Inf|Voice=Act 6 acl _ Translit=ceyyap|LTranslit=cey
8 பட்ட் படு AUX VT-T---PA Polarity=Pos|VerbForm=Part|Voice=Pass 6 aux _ Translit=paṭṭ|LTranslit=paṭu
9 உள்ளது உள் AUX VR-T3SNAA Gender=Neut|Mood=Ind|Number=Sing|Person=3|Polarity=Pos|VerbForm=Fin|Voice=Act 6 aux _ Translit=uḷḷatu|LTranslit=uḷ
10 . . PUNCT Z#------- PunctType=Peri 6 punct _ Translit=.|LTranslit=.
</code></pre>
<pre><code class="language-conllu"># visual-style 7 bgColor:blue
# visual-style 7 fgColor:white
# visual-style 0 bgColor:blue
# visual-style 0 fgColor:white
# visual-style 0 7 root color:blue
1 இதுகுறித்து இதுகுறித்து ADV AA------- _ 7 advmod _ Translit=itukurittu|LTranslit=itukurittu
2 அவர் அவர் PRON RpN-3SH-- Case=Nom|Gender=Com|Number=Sing|Person=3|Polite=Form|PronType=Prs 4 nsubj _ Translit=avar|LTranslit=avar
3 இன்று இன்று ADV AA------- _ 4 advmod _ Translit=inru|LTranslit=inru
4 வெளியிட்ட் வெளியிடு VERB Vt-T---AA Polarity=Pos|VerbForm=Part|Voice=Act 5 advcl _ Translit=veḷiyiṭṭ|LTranslit=veḷiyiṭu
5 உள்ள உள் ADJ Jd-T----A Polarity=Pos|VerbForm=Part 6 amod _ Translit=uḷḷa|LTranslit=uḷ
6 அறிக்கையில் அறிக்கை NOUN NNL-3SN-- Case=Loc|Gender=Neut|Number=Sing|Person=3 7 obl _ Translit=arikkaiyil|LTranslit=arikkai
7 கூறியிருப்பத் கூறு AUX VZNF3SNAA Case=Nom|Gender=Neut|Number=Sing|Person=3|Polarity=Pos|Tense=Fut|VerbForm=Ger|Voice=Act 0 root _ Translit=kūriyiruppat|LTranslit=kūru
8 ஆவது ஆவது PART Tl------- _ 7 advmod:emph _ Translit=āvatu|LTranslit=āvatu
9 : : PUNCT Z:------- PunctType=Comm 7 punct _ SpaceAfter=No|Translit=:|LTranslit=:
10 . . PUNCT Z#------- PunctType=Peri 7 punct _ Translit=.|LTranslit=.
</code></pre>
</div>
<!-- support for embedded visualizations -->
<script type="text/javascript">
var root = '../../'; // filled in by jekyll
head.js(
// We assume that external libraries such as jquery.min.js have already been loaded outside!
// (See _layouts/base.html.)
// brat helper modules
root + 'lib/brat/configuration.js',
root + 'lib/brat/util.js',
root + 'lib/brat/annotation_log.js',
root + 'lib/ext/webfont.js',
// brat modules
root + 'lib/brat/dispatcher.js',
root + 'lib/brat/url_monitor.js',
root + 'lib/brat/visualizer.js',
// embedding configuration
root + 'lib/local/config.js',
// project-specific collection data
root + 'lib/local/collections.js',
// Annodoc
root + 'lib/annodoc/annodoc.js',
// NOTE: non-local libraries
'https://spyysalo.github.io/conllu.js/conllu.js'
);
var webFontURLs = [
// root + 'static/fonts/Astloch-Bold.ttf',
root + 'static/fonts/PT_Sans-Caption-Web-Regular.ttf',
root + 'static/fonts/Liberation_Sans-Regular.ttf'
];
var setupTimeago = function() {
jQuery("time.timeago").timeago();
};
head.ready(function() {
setupTimeago();
// mark current collection (filled in by Jekyll)
Collections.listing['_current'] = '';
// perform all embedding and support functions
Annodoc.activate(Config.bratCollData, Collections.listing);
});
</script>
<!-- google analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-55233688-1', 'auto');
ga('send', 'pageview');
</script>
<div id="footer">
<p class="footer-text">© 2014–2021
<a href="http://universaldependencies.org/introduction.html#contributors" style="color:gray">Universal Dependencies contributors</a>.
Site powered by <a href="http://spyysalo.github.io/annodoc" style="color:gray">Annodoc</a> and <a href="http://brat.nlplab.org/" style="color:gray">brat</a></p>.
</div>
</div>
</body>
</html>
| {'content_hash': 'ea6893fd2c4b4788ef88b5f8d360a132', 'timestamp': '', 'source': 'github', 'line_count': 213, 'max_line_length': 523, 'avg_line_length': 48.93896713615023, 'alnum_prop': 0.6485993860322333, 'repo_name': 'UniversalDependencies/universaldependencies.github.io', 'id': 'd632450f472a3363a73123a964520b4f315bc90a', 'size': '10958', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'treebanks/ta_ttb/ta-dep-root.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '64420'}, {'name': 'HTML', 'bytes': '383191916'}, {'name': 'JavaScript', 'bytes': '687350'}, {'name': 'Perl', 'bytes': '7788'}, {'name': 'Python', 'bytes': '21203'}, {'name': 'Shell', 'bytes': '7253'}]} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
J. Arnold Arbor. 9:58. 1928
#### Original name
null
### Remarks
null | {'content_hash': '1a3affe1f9b0d477550e15b952bc3729', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 12.076923076923077, 'alnum_prop': 0.6878980891719745, 'repo_name': 'mdoering/backbone', 'id': '626813df335aee1692dfa3f2b4608ea7a63b2663', 'size': '212', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Crataegus/Crataegus kansuensis/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
Template.contacts.helpers({
users: function () {
var users = {};
console.log(Meteor.presences.find().fetch());
Meteor.presences.find().forEach(function (presence) {
if (presence.userId)
users[presence.userId] = Meteor.users.findOne(presence.userId);
});
Session.set('usersList', users);
return _.toArray(users);
}
});
Template.contacts.events({
'click a[data-op="chat"]': function (e) {
var $a = $(e.target);
// prevent user chat with himself
if (Meteor.userId() === $a.data('with')) return;
// find rooms for 2 users
var roomId = '';
var roomMems = [Meteor.userId(), $a.data('with')];
var room = Rooms.findOne({name: roomMems.join('_')});
if (!room) {
roomId = Rooms.insert({
name: roomMems.join('_'),
description: '',
created: new Date(),
changed: new Date(),
members: roomMems,
type: '1-on-1',
creator: Meteor.userId()
});
} else {
roomId = room._id;
}
// set room to active
if (Session.get('activeRoom') != roomId) {
Session.set('activeRoom', roomId);
}
}
}); | {'content_hash': 'b4f0776c4bec95e54381ec6e4721bd59', 'timestamp': '', 'source': 'github', 'line_count': 44, 'max_line_length': 67, 'avg_line_length': 24.0, 'alnum_prop': 0.6070075757575758, 'repo_name': 'olragon/meteorchat', 'id': '59dfd26b05f83679a9ee4e28993c227765e068ba', 'size': '1056', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'client/views/contacts.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '838'}, {'name': 'JavaScript', 'bytes': '42216'}]} |
namespace wgt
{
class ConnectionSlot;
class GraphNode
{
DECLARE_REFLECTED
public:
GraphNode();
~GraphNode();
struct Params
{
typedef ObjectHandleT<ConnectionSlot> TSlotPtr;
typedef std::vector<TSlotPtr> TSlotCollection;
TSlotCollection inputSlots;
TSlotCollection outputSlots;
std::string typeId;
};
void Init(Params&& params);
float GetPosX() const;
void SetPosX(float posX);
float GetPosY() const;
void SetPosY(float posY);
std::string const& GetTitle() const;
void SetTitle(std::string const& title);
size_t GetUID() const;
std::string const& GetType()
{
return typeId;
}
void Shift(float modelShiftX, float modelShiftY);
void ShiftImpl(float modelShiftX, float modelShiftY);
Signal<void(float x, float y)> MoveNodes;
Signal<void(GraphNode*)> Changed;
private:
IListModel* GetInputSlots() const;
IListModel* GetOutputSlots() const;
/// we need this method to call it through NGT reflection system and signal qml that value changed
void PosXChanged(const float& x);
void PosYChanged(const float& y);
private:
std::string title;
float modelX, modelY;
std::unique_ptr<IListModel> inputSlots;
std::unique_ptr<IListModel> outputSlots;
std::string typeId;
};
} // end namespace wgt
#endif // __GRAPHEDITOR_GRAPHNODE_H__
| {'content_hash': '79f17876ae2b4fe2179bd4ae180ed7a7', 'timestamp': '', 'source': 'github', 'line_count': 60, 'max_line_length': 102, 'avg_line_length': 23.35, 'alnum_prop': 0.6716630977872948, 'repo_name': 'dava/wgtf', 'id': '44e479fe465536533bea4c92364c39a8ee6448be', 'size': '1685', 'binary': False, 'copies': '1', 'ref': 'refs/heads/dava/development', 'path': 'src/core/plugins/plg_graph_editor/src/graph_node.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '3332'}, {'name': 'C', 'bytes': '586'}, {'name': 'C++', 'bytes': '4348584'}, {'name': 'CMake', 'bytes': '198187'}, {'name': 'JavaScript', 'bytes': '135317'}, {'name': 'Makefile', 'bytes': '936'}, {'name': 'Python', 'bytes': '32510'}, {'name': 'QML', 'bytes': '1293442'}, {'name': 'Shell', 'bytes': '8109'}]} |
package com.seedform.dfatester.app;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
* A <tt>FragmentPagerAdapter</tt> that returns a fragment corresponding to one
* of the primary sections of the <tt>Activity</tt> it is used for.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private Class<? extends Fragment>[] mFragments;
private String[] mTitles;
public SectionsPagerAdapter(FragmentManager fm, String[] titles,
Class<? extends Fragment>[] fragments) {
super(fm);
mFragments = fragments;
mTitles = titles;
}
@Override
public Fragment getItem(int i) {
try {
return mFragments[i].newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
@Override
public int getCount() {
return mFragments.length;
}
@Override
public CharSequence getPageTitle(int position) {
return mTitles[position];
}
}
| {'content_hash': 'bb39189550ceeb93985196389dd43138', 'timestamp': '', 'source': 'github', 'line_count': 47, 'max_line_length': 79, 'avg_line_length': 25.319148936170212, 'alnum_prop': 0.6521008403361345, 'repo_name': 'seedform/DFA-Tester', 'id': '6cc05a678ec4160dfe9377c540745efcf0ac707d', 'size': '1940', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'DFATester/src/com/seedform/dfatester/app/SectionsPagerAdapter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '280539'}]} |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BugTracker.WebServices")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BugTracker.WebServices")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("cc9f69a1-66f7-4d53-8c76-b5f39aa64053")]
// Version information for an assembly consists of the following four values:
// Major Version
// Minor Version
// Build Number
// Revision
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | {'content_hash': '95497f9b6d6aab871286d30ee225e5d4', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 84, 'avg_line_length': 41.4375, 'alnum_prop': 0.7541478129713424, 'repo_name': '2She2/WebSevices', 'id': 'c7a66660d939b17b096ec69fa1f787a2db61df38', 'size': '1329', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '07.Web-Services-Testing/BugTracker.WebServices/Properties/AssemblyInfo.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '1376'}, {'name': 'C#', 'bytes': '631763'}, {'name': 'CSS', 'bytes': '8514'}, {'name': 'JavaScript', 'bytes': '41864'}]} |
#import <iTunesStoreUI/SUScriptInterface.h>
@interface SUScriptInterface (SUScriptCalloutView)
- (id)makeCalloutView;
@end
| {'content_hash': 'ecfa37be0ba2ee4bdac530d2d291eee9', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 50, 'avg_line_length': 15.875, 'alnum_prop': 0.8031496062992126, 'repo_name': 'matthewsot/CocoaSharp', 'id': '601e197ac05c965827ffe17f1e604bdea26100cd', 'size': '267', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Headers/PrivateFrameworks/iTunesStoreUI/SUScriptInterface-SUScriptCalloutView.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '259784'}, {'name': 'C#', 'bytes': '2789005'}, {'name': 'C++', 'bytes': '252504'}, {'name': 'Objective-C', 'bytes': '24301417'}, {'name': 'Smalltalk', 'bytes': '167909'}]} |
import sys
import argparse
import ConfigParser
import smtplib
from email.mime.text import MIMEText
from email import utils
import datetime
import time
import uuid
EXIT_OK = 0
EXIT_WARNING = 1
EXIT_CRITICAL = 2
EXIT_UNKNOWN = 3
DEFAULT_PORT = 587
DEFAULT_PROFILECONFIG = '/etc/nagios-plugins/check_email_delivery_credentials.ini'
parser = argparse.ArgumentParser(description='This program sends a test email message over SMTP TLS.')
parser.add_argument('-H', dest='host', metavar='host', required=True, help='SMTP host')
parser.add_argument('--port', type=int, default=DEFAULT_PORT, help='SMTP port (default=%i)'%DEFAULT_PORT)
parser.add_argument('--profile', required=True, help='credential profile in config file')
parser.add_argument('--profileconfig', metavar='config.ini', default=DEFAULT_PROFILECONFIG, help='location of the config file (default=%s)'%DEFAULT_PROFILECONFIG)
parser.add_argument('--mailfrom', metavar='sender@host1', required=True, help='email address of the test message sender')
parser.add_argument('--mailto', metavar='receiver@host2', required=True, help='email address of the test message receiver')
try:
args = vars(parser.parse_args())
except SystemExit:
sys.exit(EXIT_UNKNOWN)
host = args['host']
port = args['port']
profile = args['profile']
profileconfig = args['profileconfig']
mailfrom = args['mailfrom']
mailto = args['mailto']
config = ConfigParser.SafeConfigParser()
config.read(profileconfig)
try:
username = config.get(profile,'username')
password = config.get(profile,'password')
except ConfigParser.NoSectionError:
print('Configuration error: profile %s does not exist' % profile)
sys.exit(EXIT_UNKNOWN)
except ConfigParser.NoOptionError:
print('Configuration error: profile %s does not contain username or password' % profile)
sys.exit(EXIT_UNKNOWN)
msg = MIMEText('This is a test message by the monitoring system to check if email delivery is running fine.')
msg['Subject'] = 'TEST'
msg['From'] = mailfrom
msg['To'] = mailto
msg['Message-ID'] = '<' + str(uuid.uuid4()) + '@' + host + '>'
nowdt = datetime.datetime.now()
nowtuple = nowdt.timetuple()
nowtimestamp = time.mktime(nowtuple)
msg['Date'] = utils.formatdate(nowtimestamp)
try:
smtp = smtplib.SMTP(host, port)
smtp.starttls()
smtp.login(username, password)
smtp.sendmail(mailfrom, mailto, msg.as_string())
except smtplib.SMTPServerDisconnected as e:
# This exception is raised when the server unexpectedly disconnects, or when an attempt is made to use the SMTP instance before connecting it to a server.
print e
sys.exit(EXIT_CRITICAL)
except smtplib.SMTPResponseException as e:
# Base class for all exceptions that include an SMTP error code. These exceptions are generated in some instances when the SMTP server returns an error code. The error code is stored in the smtp_code attribute of the error, and the smtp_error attribute is set to the error message.
print e
sys.exit(EXIT_CRITICAL)
except smtplib.SMTPSenderRefused as e:
# Sender address refused. In addition to the attributes set by on all SMTPResponseException exceptions, this sets 'sender' to the string that the SMTP server refused.
print e
sys.exit(EXIT_CRITICAL)
except smtplib.SMTPRecipientsRefused as e:
# All recipient addresses refused. The errors for each recipient are accessible through the attribute recipients, which is a dictionary of exactly the same sort as SMTP.sendmail() returns.
print e
sys.exit(EXIT_CRITICAL)
except smtplib.SMTPDataError as e:
# The SMTP server refused to accept the message data.
print e
sys.exit(EXIT_CRITICAL)
except smtplib.SMTPConnectError as e:
# Error occurred during establishment of a connection with the server.
print e
sys.exit(EXIT_CRITICAL)
except smtplib.SMTPHeloError as e:
# The server refused our HELO message.
print e
sys.exit(EXIT_CRITICAL)
except smtplib.SMTPAuthenticationError as e:
# SMTP authentication went wrong. Most probably the server didn't accept the username/password combination provided.
print e
sys.exit(EXIT_CRITICAL)
except smtplib.SMTPException as e:
# The base exception class for all the other exceptions provided by this module.
print e
sys.exit(EXIT_CRITICAL)
print('OK')
sys.exit(EXIT_OK)
| {'content_hash': '799871b0c4d1a0ebe1be80a991eb561d', 'timestamp': '', 'source': 'github', 'line_count': 109, 'max_line_length': 285, 'avg_line_length': 39.4954128440367, 'alnum_prop': 0.7491289198606271, 'repo_name': 'gtrs/check_email_delivery.py', 'id': 'f61b4404bff441fe56350a501193aa891fb0b4dc', 'size': '4328', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'check_smtp_send.py', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '8294'}]} |
namespace printing {
using WebKit::WebFrame;
using WebKit::WebNode;
bool PrintWebViewHelper::RenderPreviewPage(
int page_number,
const PrintMsg_Print_Params& print_params) {
PrintMsg_PrintPage_Params page_params;
page_params.params = print_params;
page_params.page_number = page_number;
scoped_ptr<Metafile> draft_metafile;
Metafile* initial_render_metafile = print_preview_context_.metafile();
if (print_preview_context_.IsModifiable() && is_print_ready_metafile_sent_) {
draft_metafile.reset(new PreviewMetafile);
initial_render_metafile = draft_metafile.get();
}
base::TimeTicks begin_time = base::TimeTicks::Now();
PrintPageInternal(page_params,
print_preview_context_.GetPrintCanvasSize(),
print_preview_context_.prepared_frame(),
initial_render_metafile);
print_preview_context_.RenderedPreviewPage(
base::TimeTicks::Now() - begin_time);
if (draft_metafile.get()) {
draft_metafile->FinishDocument();
} else if (print_preview_context_.IsModifiable() &&
print_preview_context_.generate_draft_pages()) {
DCHECK(!draft_metafile.get());
draft_metafile.reset(
print_preview_context_.metafile()->GetMetafileForCurrentPage());
}
return PreviewPageRendered(page_number, draft_metafile.get());
}
bool PrintWebViewHelper::PrintPagesNative(WebKit::WebFrame* frame,
const WebKit::WebNode& node,
int page_count,
const gfx::Size& canvas_size) {
NativeMetafile metafile;
if (!metafile.Init())
return false;
const PrintMsg_PrintPages_Params& params = *print_pages_params_;
std::vector<int> printed_pages;
if (params.pages.empty()) {
for (int i = 0; i < page_count; ++i) {
printed_pages.push_back(i);
}
} else {
// TODO(vitalybuka): redesign to make more code cross platform.
for (size_t i = 0; i < params.pages.size(); ++i) {
if (params.pages[i] >= 0 && params.pages[i] < page_count) {
printed_pages.push_back(params.pages[i]);
}
}
}
if (printed_pages.empty())
return false;
PrintMsg_PrintPage_Params page_params;
page_params.params = params.params;
for (size_t i = 0; i < printed_pages.size(); ++i) {
page_params.page_number = printed_pages[i];
PrintPageInternal(page_params, canvas_size, frame, &metafile);
}
metafile.FinishDocument();
// Get the size of the resulting metafile.
uint32 buf_size = metafile.GetDataSize();
DCHECK_GT(buf_size, 0u);
#if defined(OS_CHROMEOS)
int sequence_number = -1;
base::FileDescriptor fd;
// Ask the browser to open a file for us.
Send(new PrintHostMsg_AllocateTempFileForPrinting(&fd, &sequence_number));
if (!metafile.SaveToFD(fd))
return false;
// Tell the browser we've finished writing the file.
Send(new PrintHostMsg_TempFileForPrintingWritten(routing_id(),
sequence_number));
return true;
#else
PrintHostMsg_DidPrintPage_Params printed_page_params;
printed_page_params.data_size = 0;
printed_page_params.document_cookie = params.params.document_cookie;
{
scoped_ptr<base::SharedMemory> shared_mem(
content::RenderThread::Get()->HostAllocateSharedMemoryBuffer(
buf_size).release());
if (!shared_mem.get()) {
NOTREACHED() << "AllocateSharedMemoryBuffer failed";
return false;
}
if (!shared_mem->Map(buf_size)) {
NOTREACHED() << "Map failed";
return false;
}
metafile.GetData(shared_mem->memory(), buf_size);
printed_page_params.data_size = buf_size;
shared_mem->GiveToProcess(base::GetCurrentProcessHandle(),
&(printed_page_params.metafile_data_handle));
}
for (size_t i = 0; i < printed_pages.size(); ++i) {
printed_page_params.page_number = printed_pages[i];
Send(new PrintHostMsg_DidPrintPage(routing_id(), printed_page_params));
// Send the rest of the pages with an invalid metafile handle.
printed_page_params.metafile_data_handle.fd = -1;
}
return true;
#endif // defined(OS_CHROMEOS)
}
void PrintWebViewHelper::PrintPageInternal(
const PrintMsg_PrintPage_Params& params,
const gfx::Size& canvas_size,
WebFrame* frame,
Metafile* metafile) {
PageSizeMargins page_layout_in_points;
double scale_factor = 1.0f;
ComputePageLayoutInPointsForCss(frame, params.page_number, params.params,
ignore_css_margins_, &scale_factor,
&page_layout_in_points);
gfx::Size page_size;
gfx::Rect content_area;
GetPageSizeAndContentAreaFromPageLayout(page_layout_in_points, &page_size,
&content_area);
gfx::Rect canvas_area =
params.params.display_header_footer ? gfx::Rect(page_size) : content_area;
SkDevice* device = metafile->StartPageForVectorCanvas(page_size, canvas_area,
scale_factor);
if (!device)
return;
// The printPage method take a reference to the canvas we pass down, so it
// can't be a stack object.
skia::RefPtr<skia::VectorCanvas> canvas =
skia::AdoptRef(new skia::VectorCanvas(device));
MetafileSkiaWrapper::SetMetafileOnCanvas(*canvas, metafile);
skia::SetIsDraftMode(*canvas, is_print_ready_metafile_sent_);
if (params.params.display_header_footer) {
// |page_number| is 0-based, so 1 is added.
// TODO(vitalybuka) : why does it work only with 1.25?
PrintHeaderAndFooter(canvas.get(), params.page_number + 1,
print_preview_context_.total_page_count(),
scale_factor / 1.25,
page_layout_in_points, *header_footer_info_,
params.params);
}
RenderPageContent(frame, params.page_number, canvas_area, content_area,
scale_factor, canvas.get());
// Done printing. Close the device context to retrieve the compiled metafile.
if (!metafile->FinishPage())
NOTREACHED() << "metafile failed";
}
} // namespace printing
| {'content_hash': 'f2614e5f9dd53f7289bf3ceb5b79a524', 'timestamp': '', 'source': 'github', 'line_count': 170, 'max_line_length': 80, 'avg_line_length': 36.523529411764706, 'alnum_prop': 0.6377838621356096, 'repo_name': 'nacl-webkit/chrome_deps', 'id': 'eae3a7be6fbf45211cd851937690da6eb430237f', 'size': '7059', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'chrome/renderer/printing/print_web_view_helper_linux.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ASP', 'bytes': '853'}, {'name': 'AppleScript', 'bytes': '6973'}, {'name': 'Arduino', 'bytes': '464'}, {'name': 'Assembly', 'bytes': '1173441'}, {'name': 'Awk', 'bytes': '9519'}, {'name': 'C', 'bytes': '74568368'}, {'name': 'C#', 'bytes': '1132'}, {'name': 'C++', 'bytes': '156174457'}, {'name': 'DOT', 'bytes': '1559'}, {'name': 'F#', 'bytes': '381'}, {'name': 'Java', 'bytes': '3088381'}, {'name': 'JavaScript', 'bytes': '18179048'}, {'name': 'Logos', 'bytes': '4517'}, {'name': 'M', 'bytes': '2190'}, {'name': 'Matlab', 'bytes': '3044'}, {'name': 'Objective-C', 'bytes': '6965520'}, {'name': 'PHP', 'bytes': '97817'}, {'name': 'Perl', 'bytes': '932725'}, {'name': 'Python', 'bytes': '8458718'}, {'name': 'R', 'bytes': '262'}, {'name': 'Ragel in Ruby Host', 'bytes': '3621'}, {'name': 'Shell', 'bytes': '1526176'}, {'name': 'Tcl', 'bytes': '277077'}, {'name': 'XSLT', 'bytes': '13493'}]} |
#include "Internal.hpp"
#include <LuminoEngine/Graphics/RenderPass.hpp>
#include <LuminoEngine/Graphics/GraphicsContext.hpp>
#include <LuminoEngine/Rendering/RenderView.hpp>
#include "../Graphics/RenderTargetTextureCache.hpp"
#include "RenderingManager.hpp"
#include "ClusteredShadingSceneRenderer.hpp"
#include "RenderingPipeline.hpp"
#include "RenderStage.hpp"
namespace ln {
namespace detail {
#if 1
//==============================================================================
// DepthPrepass
DepthPrepass::DepthPrepass()
{
}
DepthPrepass::~DepthPrepass()
{
}
void DepthPrepass::init()
{
SceneRendererPass::init();
m_defaultShader = manager()->builtinShader(BuiltinShader::DepthPrepass);
}
void DepthPrepass::onBeginRender(SceneRenderer* sceneRenderer)
{
auto size = sceneRenderer->renderingPipeline()->renderingFrameBufferSize();
m_depthMap = RenderTargetTexture::getTemporary(size.width, size.height, TextureFormat::RGBA8, false);
m_depthBuffer = DepthBuffer::getTemporary(size.width, size.height);
m_renderPass = makeObject<RenderPass>();
}
void DepthPrepass::onEndRender(SceneRenderer* sceneRenderer)
{
RenderTargetTexture::releaseTemporary(m_depthMap);
DepthBuffer::releaseTemporary(m_depthBuffer);
m_depthMap = nullptr;
m_depthBuffer = nullptr;
}
void DepthPrepass::onBeginPass(GraphicsContext* context, RenderTargetTexture* renderTarget, DepthBuffer* depthBuffer)
{
m_renderPass->setRenderTarget(0, m_depthMap);
m_renderPass->setDepthBuffer(m_depthBuffer);
m_renderPass->setClearValues(ClearFlags::All, Color::Transparency, 1.0f, 0);
}
//void DepthPrepass::onBeginPass(GraphicsContext* context, FrameBuffer* frameBuffer)
//{
// frameBuffer->renderTarget[0] = m_depthMap;
// frameBuffer->depthBuffer = m_depthBuffer;
// m_renderPass->setRenderTarget(0, m_depthMap);
// m_renderPass->setDepthBuffer(m_depthBuffer);
// //context->setRenderTarget(0, m_depthMap);
// //context->setDepthBuffer(m_depthBuffer);
// //context->setRenderPass(m_renderPass);
// //context->clear(ClearFlags::All, Color::Transparency, 1.0f, 0); // TODO: renderPassに統合していいと思う
// m_renderPass->setRenderTarget(0, m_depthMap);
// m_renderPass->setDepthBuffer(m_depthBuffer);
// m_renderPass->setClearValues(ClearFlags::All, Color::Transparency, 1.0f, 0);
//}
RenderPass* DepthPrepass::renderPass() const
{
return m_renderPass;
}
ShaderTechnique* DepthPrepass::selectShaderTechnique(
ShaderTechniqueClass_MeshProcess requestedMeshProcess,
Shader* requestedShader,
ShadingModel requestedShadingModel)
{
// force default
return m_defaultShader->techniques()->front();
}
//==============================================================================
// LightOcclusionPass
LightOcclusionPass::LightOcclusionPass()
{
}
void LightOcclusionPass::init()
{
SceneRendererPass::init();
m_blackShader = detail::EngineDomain::renderingManager()->builtinShader(BuiltinShader::BlackShader);
m_blackShaderTechnique = m_blackShader->findTechnique(u"Default");
m_renderPass = makeObject<RenderPass>();
}
void LightOcclusionPass::onBeginRender(SceneRenderer* sceneRenderer)
{
auto size = sceneRenderer->renderingPipeline()->renderingFrameBufferSize();
acquireBuffers(size.width, size.height);
m_depthBuffer = DepthBuffer::getTemporary(size.width, size.height);
}
void LightOcclusionPass::onEndRender(SceneRenderer* sceneRenderer)
{
//RenderTargetTexture::releaseTemporary(m_lensflareOcclusionMap);
DepthBuffer::releaseTemporary(m_depthBuffer);
//m_lensflareOcclusionMap = nullptr;
m_depthBuffer = nullptr;
}
void LightOcclusionPass::onBeginPass(GraphicsContext* context, RenderTargetTexture* renderTarget, DepthBuffer* depthBuffer)
{
m_renderPass->setRenderTarget(0, m_lensflareOcclusionMap);
m_renderPass->setDepthBuffer(m_depthBuffer);
m_renderPass->setClearValues(ClearFlags::All, Color::Black, 1.0f, 0);
//m_renderPass->setClearValues(ClearFlags::All, Color::White, 1.0f, 0);
}
RenderPass* LightOcclusionPass::renderPass() const
{
return m_renderPass;
}
bool LightOcclusionPass::filterElement(RenderDrawElement* element) const
{
//return true;
//return SceneRendererPass::filterElement(element);
if (element->flags().hasFlag(RenderDrawElementTypeFlags::BackgroundSky)) return false;
return (element->flags() & (
RenderDrawElementTypeFlags::Opaque |
RenderDrawElementTypeFlags::Transparent |
RenderDrawElementTypeFlags::LightDisc)) != RenderDrawElementTypeFlags::None;
}
ShaderTechnique* LightOcclusionPass::selectShaderTechnique(
ShaderTechniqueClass_MeshProcess requestedMeshProcess,
Shader* requestedShader,
ShadingModel requestedShadingModel)
{
if (!requestedShader)
return m_blackShaderTechnique;
ShaderTechniqueClass classSet;
classSet.defaultTechnique = false;
classSet.ligiting = ShaderTechniqueClass_Ligiting::LightDisc;
classSet.phase = ShaderTechniqueClass_Phase::Geometry;
classSet.meshProcess = requestedMeshProcess;
classSet.shadingModel = tlanslateShadingModel(requestedShadingModel);
ShaderTechnique* technique = ShaderHelper::findTechniqueByClass(requestedShader, classSet);
if (technique)
return technique;
else
return m_blackShaderTechnique;
}
void LightOcclusionPass::acquireBuffers(int width, int height)
{
// TODO: getTemporary() 使った方がいいかも?
// ただ、SceneRenderer をまたいでポストエフェクトで使いたいので、get/releaseのスコープを Pipeline単位にしたりする必要がある。
if (!m_lensflareOcclusionMap || (m_lensflareOcclusionMap->width() != width || m_lensflareOcclusionMap->height() != height)) {
m_lensflareOcclusionMap = makeObject< RenderTargetTexture>(width, height, TextureFormat::RGBA8, false);
}
//if (!m_depthBuffer || (m_depthBuffer->width() != width || m_depthBuffer->height() != height)) {
// m_depthBuffer = DepthBuffer::getTemporary(width, height);
//}
}
//==============================================================================
// ClusteredShadingGeometryRenderingPass
static const String ClusteredShadingGeometryRenderingPass_TechniqueName = _T("Forward_Geometry");
//static const String ClusteredShadingGeometryRenderingPass_PassName = _T("Geometry");
ClusteredShadingGeometryRenderingPass::ClusteredShadingGeometryRenderingPass()
{
}
ClusteredShadingGeometryRenderingPass::~ClusteredShadingGeometryRenderingPass()
{
}
void ClusteredShadingGeometryRenderingPass::init(ClusteredShadingSceneRenderer* ownerRenderer)
{
SceneRendererPass::init();
m_ownerRenderer = ownerRenderer;
{
m_defaultShader = manager()->builtinShader(BuiltinShader::ClusteredShadingDefault);
}
// TODO: getPass 引数型
m_defaultShaderTechnique = m_defaultShader->findTechnique(ClusteredShadingGeometryRenderingPass_TechniqueName);
// {
// static const byte_t data[] =
// {
//#include "Resource/Unlit.fx.h"
// };
// static const size_t size = LN_ARRAY_SIZE_OF(data);
// m_unLightingShader = Shader::create((const char*)data, size, nullptr, ShaderCodeType::RawHLSL);
// }
// m_unLightingShaderTechnique = m_unLightingShader->getTechniques()[0];
m_renderPass = makeObject<RenderPass>();
}
void ClusteredShadingGeometryRenderingPass::onBeginPass(GraphicsContext* context, RenderTargetTexture* renderTarget, DepthBuffer* depthBuffer)
{
m_renderPass->setRenderTarget(0, renderTarget);
m_renderPass->setDepthBuffer(depthBuffer);
m_renderPass->setClearValues(ClearFlags::None, Color::Transparency, 1.0f, 0);
}
//void ClusteredShadingGeometryRenderingPass::onBeginPass(GraphicsContext* context, FrameBuffer* frameBuffer)
//{
// frameBuffer->renderTarget[0] = m_depthMap;
// frameBuffer->depthBuffer = m_depthBuffer;
// m_renderPass->setRenderTarget(0, m_depthMap);
// m_renderPass->setDepthBuffer(m_depthBuffer);
// //context->setRenderTarget(0, m_depthMap);
// //context->setDepthBuffer(m_depthBuffer);
// //context->setRenderPass(m_renderPass);
// //context->clear(ClearFlags::All, Color::Transparency, 1.0f, 0); // TODO: renderPassに統合していいと思う
// m_renderPass->setRenderTarget(0, m_depthMap);
// m_renderPass->setDepthBuffer(m_depthBuffer);
// m_renderPass->setClearValues(ClearFlags::All, Color::Transparency, 1.0f, 0);
//}
RenderPass* ClusteredShadingGeometryRenderingPass::renderPass() const
{
return m_renderPass;
}
//bool ClusteredShadingGeometryRenderingPass::filterElement(RenderDrawElement* element) const
//{
// return element->elementType == RenderDrawElementType::LightDisc;
//}
ShaderTechnique* ClusteredShadingGeometryRenderingPass::selectShaderTechnique(
ShaderTechniqueClass_MeshProcess requestedMeshProcess,
Shader* requestedShader,
ShadingModel requestedShadingModel)
{
Shader* shader = requestedShader;
if (!shader) shader = m_defaultShader;
// ライトがひとつもない場合はライティングなしを選択
if (!m_ownerRenderer->lightClusters().hasLight()) {
requestedShadingModel = ShadingModel::Unlit;
// TODO: わざわざ Unlit テクニック用意しないとならないので面倒というか忘れやすい
}
ShaderTechniqueClass classSet;
classSet.defaultTechnique = false;
classSet.ligiting = ShaderTechniqueClass_Ligiting::Forward;
classSet.phase = ShaderTechniqueClass_Phase::Geometry;
classSet.meshProcess = requestedMeshProcess;
classSet.shadingModel = tlanslateShadingModel(requestedShadingModel);
ShaderTechnique* technique = ShaderHelper::findTechniqueByClass(shader, classSet);
if (technique)
return technique;
else
return m_defaultShaderTechnique;
}
//void ClusteredShadingGeometryRenderingPass::selectElementRenderingPolicy(DrawElement* element, const RenderStageFinalData& stageData, ElementRenderingPolicy* outPolicy)
//{
//
// //if (stageData.shadingModel == ShadingModel::Unlit)
// //{
// // classSet.shadingModel = ShaderTechniqueClass_ShadingModel::Unlit;
// // outPolicy->shaderTechnique = stageData.shader->findTechniqueByClass(classSet);
// // if (!outPolicy->shaderTechnique)
// // {
// // outPolicy->shaderTechnique = m_unLightingShaderTechnique;
// // }
// //}
// //else
// //{
// // classSet.shadingModel = ShaderTechniqueClass_ShadingModel::Default;
// // outPolicy->shaderTechnique = stageData.shader->findTechniqueByClass(classSet);
// // if (!outPolicy->shaderTechnique)
// // {
// // outPolicy->shaderTechnique = m_defaultShaderTechnique;
// // }
// //}
//
// outPolicy->shader = outPolicy->shaderTechnique->getOwnerShader();
// outPolicy->visible = true;
//
//}
//RenderTargetTexture* g_m_normalRenderTarget = nullptr;
//void ClusteredShadingGeometryRenderingPass::onBeginPass(DefaultStatus* defaultStatus, RenderView* renderView)
//{
// //g_m_normalRenderTarget = m_normalRenderTarget;
// //defaultStatus->defaultRenderTarget[1] = m_normalRenderTarget;
//}
//ShaderPass* ClusteredShadingGeometryRenderingPass::selectShaderPass(Shader* shader)
//{
// //ShaderPass* pass = nullptr;
// //ShaderTechnique* tech = shader->findTechnique(_T("ClusteredForward"));
// //if (tech)
// //{
// // pass = tech->getPass(_T("Geometry"));
// // if (pass)
// // {
// // return pass;
// // }
// //}
//
// return RenderingPass2::selectShaderPass(shader);
//}
//==============================================================================
// ShadowCasterPass
//==============================================================================
ShadowCasterPass::ShadowCasterPass()
{
}
ShadowCasterPass::~ShadowCasterPass()
{
}
//RenderTargetTexture* g_m_shadowMap = nullptr;
void ShadowCasterPass::init()
{
SceneRendererPass::init();
m_defaultShader = manager()->builtinShader(BuiltinShader::ShadowCaster);
m_shadowMap = makeObject<RenderTargetTexture>(1024, 1024, TextureFormat::RGBA32F, false);
m_depthBuffer = makeObject<DepthBuffer>(1024, 1024);
m_renderPass = makeObject<RenderPass>();
//g_m_shadowMap = m_shadowMap;
}
//Shader* ShadowCasterPass::getDefaultShader() const
//{
// return m_defaultShader;
//}
void ShadowCasterPass::onBeginPass(GraphicsContext* context, RenderTargetTexture* renderTarget, DepthBuffer* depthBuffer)
{
m_renderPass->setRenderTarget(0, m_shadowMap);
m_renderPass->setDepthBuffer(m_depthBuffer);
m_renderPass->setClearValues(ClearFlags::All, Color::Transparency, 1.0f, 0);
}
//void ShadowCasterPass::onBeginPass(GraphicsContext* context, FrameBuffer* frameBuffer)
//{
// frameBuffer->renderTarget[0] = m_shadowMap;
// frameBuffer->depthBuffer = m_depthBuffer;
// //context->setRenderTarget(0, m_shadowMap);
// //context->setDepthBuffer(m_depthBuffer);
// //m_renderPass->setRenderTarget(0, m_shadowMap);
// //m_renderPass->setDepthBuffer(m_depthBuffer);
// //context->setRenderPass(m_renderPass);
// //context->clear(ClearFlags::All, Color::Transparency, 1.0f, 0);
// m_renderPass->setRenderTarget(0, m_shadowMap);
// m_renderPass->setDepthBuffer(m_depthBuffer);
// m_renderPass->setClearValues(ClearFlags::All, Color::Transparency, 1.0f, 0);
//}
//
RenderPass* ShadowCasterPass::renderPass() const
{
return m_renderPass;
}
ShaderTechnique* ShadowCasterPass::selectShaderTechnique(
ShaderTechniqueClass_MeshProcess requestedMeshProcess,
Shader* requestedShader,
ShadingModel requestedShadingModel)
{
// force default
return m_defaultShader->techniques()->front();
}
//void ShadowCasterPass::overrideCameraInfo(detail::CameraInfo* cameraInfo)
//{
// *cameraInfo = view;
//}
//ShaderPass* ShadowCasterPass::selectShaderPass(Shader* shader)
//{
// return RenderingPass2::selectShaderPass(shader);
//}
//==============================================================================
// ClusteredShadingSceneRenderer
//==============================================================================
ClusteredShadingSceneRenderer::ClusteredShadingSceneRenderer()
{
}
ClusteredShadingSceneRenderer::~ClusteredShadingSceneRenderer()
{
}
void ClusteredShadingSceneRenderer::init(RenderingManager* manager)
{
SceneRenderer::init();
m_depthPrepass = makeObject<DepthPrepass>();
//addPass(m_depthPrepass);
m_lightOcclusionPass = makeObject<LightOcclusionPass>();
addPass(m_lightOcclusionPass);
// pass "Geometry"
auto geometryPass = makeObject<ClusteredShadingGeometryRenderingPass>(this);
addPass(geometryPass);
m_lightClusters.init();
// TODO: Test
//m_renderSettings.ambientColor = Color(1, 0, 0, 1);
}
//void ClusteredShadingSceneRenderer::onBeginRender()
//{
//
//}
//
//void ClusteredShadingSceneRenderer::onEndRender()
//{
//
//}
void ClusteredShadingSceneRenderer::collect(const detail::CameraInfo& cameraInfo)
{
m_lightClusters.beginMakeClusters(cameraInfo.viewMatrix, cameraInfo.projMatrix, cameraInfo.viewPosition, cameraInfo.nearClip, cameraInfo.farClip);
SceneRenderer::collect(cameraInfo);
m_lightClusters.endMakeClusters();
}
// TODO: Vector3 クラスへ
static Vector3 transformDirection(const Vector3& vec, const Matrix& mat)
{
return Vector3(
(((vec.x * mat.m11) + (vec.y * mat.m21)) + (vec.z * mat.m31)),
(((vec.x * mat.m12) + (vec.y * mat.m22)) + (vec.z * mat.m32)),
(((vec.x * mat.m13) + (vec.y * mat.m23)) + (vec.z * mat.m33)));
}
void ClusteredShadingSceneRenderer::onCollectLight(const DynamicLightInfo& light)
{
const CameraInfo& view = mainCameraInfo();
Color color = light.m_color;
color *= light.m_intensity;
switch (light.m_type)
{
case LightType::Ambient:
m_lightClusters.addAmbientLight(color);
break;
case LightType::Hemisphere:
m_lightClusters.addHemisphereLight(color, light.m_color2 * light.m_intensity);
break;
case LightType::Directional:
m_lightClusters.addDirectionalLight(transformDirection(-light.m_direction, view.viewMatrix), color);
break;
case LightType::Point:
m_lightClusters.addPointLight(light.m_position, light.m_range, light.m_attenuation, color);
break;
case LightType::Spot:
m_lightClusters.addSpotLight(light.m_position, light.m_range, light.m_attenuation, color, light.m_direction, light.m_spotAngle, light.m_spotPenumbra);
break;
default:
LN_UNREACHABLE();
break;
}
}
void ClusteredShadingSceneRenderer::onSetAdditionalShaderPassVariables(Shader* shader)
{
ShaderParameter* v;
detail::ShaderSemanticsManager* ssm = detail::ShaderHelper::semanticsManager(shader);
// TODO:
// 毎回 findParameter していたのをテーブル対応にしたことで 50us → 1us 以下にできた。
// ただ、もう少し最適化の余地はある。以下のパラメータはシーン全体でひとつなので、
// 今 onSetAdditionalShaderPassVariables は DrawElement ごとに呼び出されているが、
// 事前に描画で使うシェーダを集めておいて Scene 単位はまとめて設定する。
#if 1
v = ssm->getParameterBySemantics(BuiltinSemantics::GlobalLightInfoTexture);
if (v) v->setTexture(m_lightClusters.getGlobalLightInfoTexture());
v = ssm->getParameterBySemantics(BuiltinSemantics::LocalLightInfoTexture);
if (v) v->setTexture(m_lightClusters.getLightInfoTexture());
v = ssm->getParameterBySemantics(BuiltinSemantics::LightClustersTexture);
if (v) v->setTexture(m_lightClusters.getClustersVolumeTexture());
v = ssm->getParameterBySemantics(BuiltinSemantics::NearClip2);
if (v) v->setFloat(m_lightClusters.m_nearClip);
v = ssm->getParameterBySemantics(BuiltinSemantics::FarClip2);
if (v) v->setFloat(m_lightClusters.m_farClip);
v = ssm->getParameterBySemantics(BuiltinSemantics::CameraPosition2);
if (v) v->setVector(Vector4(m_lightClusters.m_cameraPos, 0));
if (const auto* params = sceneGlobalParams()) {
v = ssm->getParameterBySemantics(BuiltinSemantics::FogColorAndDensity);
if (v) v->setVector(Vector4(params->fogColor.rgb() * params->fogColor.a, params->fogDensity));
v = ssm->getParameterBySemantics(BuiltinSemantics::FogParams);
if (v) v->setVector(Vector4(params->startDistance, params->lowerHeight, params->upperHeight, params->heightFogDensity));
// TODO: Test
if (mainLightInfo()) {
v = shader->findParameter(u"ln_MainLightDirection");
if (v) v->setVector(Vector4(mainLightInfo()->m_direction, 0.0f));
}
}
// TODO: Test
v = shader->findParameter(u"_LensflareOcclusionMap");
if (v) {
v->setTexture(m_lightOcclusionPass->m_lensflareOcclusionMap);
}
#else
//static Shader* lastShader = nullptr;
//if (lastShader == shader) return;
//lastShader = shader;
v = shader->findParameter(_T("ln_GlobalLightInfoTexture"));
if (v) v->setTexture(m_lightClusters.getGlobalLightInfoTexture());
v = shader->findParameter(_T("ln_pointLightInfoTexture"));
if (v) v->setTexture(m_lightClusters.getLightInfoTexture());
v = shader->findParameter(_T("ln_clustersTexture"));
if (v) v->setTexture(m_lightClusters.getClustersVolumeTexture());
v = shader->findParameter(_T("ln_nearClip"));
if (v) v->setFloat(m_lightClusters.m_nearClip);
v = shader->findParameter(_T("ln_farClip"));
if (v) v->setFloat(m_lightClusters.m_farClip);
v = shader->findParameter(_T("ln_cameraPos"));
if (v) v->setVector(Vector4(m_lightClusters.m_cameraPos, 0));
//v = shader->findParameter(_T("ln_AmbientColor"));
//if (v) v->setVector(Vector4(m_renderSettings.ambientColor)); // TODO: Color 直接渡しできるようにしてもいいと思う
//v = shader->findParameter(_T("ln_AmbientSkyColor"));
//if (v) v->setVector(Vector4(m_renderSettings.ambientSkyColor));
//v = shader->findParameter(_T("ln_AmbientGroundColor"));
//if (v) v->setVector(Vector4(m_renderSettings.ambientGroundColor));
v = shader->findParameter(_T("ln_FogParams"));
if (v) v->setVector(Vector4(m_fogParams.color.rgb() * m_fogParams.color.a, m_fogParams.density));
#endif
}
#endif
} // namespace detail
} // namespace ln
| {'content_hash': '60e1512eaf17f9de277ca402fc89d52e', 'timestamp': '', 'source': 'github', 'line_count': 592, 'max_line_length': 170, 'avg_line_length': 32.111486486486484, 'alnum_prop': 0.735718043135192, 'repo_name': 'lriki/Lumino', 'id': 'e107eb0cd8d3d8f2819b8f393d175b570561e3cf', 'size': '19548', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/LuminoEngine/src/Rendering/ClusteredShadingSceneRenderer.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '222'}, {'name': 'C', 'bytes': '180957'}, {'name': 'C#', 'bytes': '138778'}, {'name': 'C++', 'bytes': '16548116'}, {'name': 'CMake', 'bytes': '73239'}, {'name': 'GLSL', 'bytes': '2703'}, {'name': 'HLSL', 'bytes': '127631'}, {'name': 'JavaScript', 'bytes': '1219'}, {'name': 'Objective-C', 'bytes': '693'}, {'name': 'Objective-C++', 'bytes': '11186'}, {'name': 'Python', 'bytes': '205'}, {'name': 'QML', 'bytes': '6390'}, {'name': 'QMake', 'bytes': '1138'}, {'name': 'Ruby', 'bytes': '64617'}, {'name': 'Shell', 'bytes': '228'}, {'name': 'Vim Snippet', 'bytes': '2017'}]} |
namespace SortSequence
{
using System;
using System.Collections.Generic;
public class Startup
{
// Write a program that reads a sequence of integers (List<int>) ending with an empty line and sorts them in an increasing order.
public static void Main()
{
var sequence = new List<int>();
var sum = 0;
while (true)
{
var input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input))
{
break;
}
var number = int.Parse(input);
sequence.Add(number);
}
sequence.Sort();
Console.WriteLine(string.Join(", ", sequence));
}
}
}
| {'content_hash': 'd8378fe871f1e8d5d75e30ca17829973', 'timestamp': '', 'source': 'github', 'line_count': 34, 'max_line_length': 137, 'avg_line_length': 23.0, 'alnum_prop': 0.4859335038363171, 'repo_name': 'NikitoG/TelerikAcademyHomeworks', 'id': '23fce98100e40e416ab877332025062acbd89a05', 'size': '784', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'DSA/LinearDataStructuresHomework/SortSequence/Startup.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '86318'}, {'name': 'C#', 'bytes': '2324116'}, {'name': 'CSS', 'bytes': '7973'}, {'name': 'HTML', 'bytes': '44796'}, {'name': 'JavaScript', 'bytes': '3041024'}, {'name': 'PLSQL', 'bytes': '6714'}, {'name': 'XSLT', 'bytes': '4697'}]} |
package org.opentosca.toscana.api;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import org.opentosca.toscana.api.exceptions.PlatformNotFoundException;
import org.opentosca.toscana.api.utils.HALRelationUtils;
import org.opentosca.toscana.core.BaseSpringTest;
import org.opentosca.toscana.core.csar.Csar;
import org.opentosca.toscana.core.csar.CsarImpl;
import org.opentosca.toscana.core.csar.CsarService;
import org.opentosca.toscana.core.testdata.ByteArrayUtils;
import org.opentosca.toscana.core.testdata.TestCsars;
import org.opentosca.toscana.core.transformation.Transformation;
import org.opentosca.toscana.core.transformation.TransformationImpl;
import org.opentosca.toscana.core.transformation.TransformationService;
import org.opentosca.toscana.core.transformation.TransformationState;
import org.opentosca.toscana.core.transformation.artifacts.TargetArtifact;
import org.opentosca.toscana.core.transformation.logging.Log;
import org.opentosca.toscana.core.transformation.logging.LogEntry;
import org.opentosca.toscana.core.transformation.platform.Platform;
import org.opentosca.toscana.core.transformation.platform.PlatformService;
import org.opentosca.toscana.core.transformation.properties.OutputProperty;
import org.opentosca.toscana.core.transformation.properties.PlatformInput;
import org.opentosca.toscana.core.transformation.properties.PropertyType;
import ch.qos.logback.classic.Level;
import com.google.common.collect.Lists;
import com.jayway.jsonpath.JsonPath;
import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class TransformationControllerTest extends BaseSpringTest {
//<editor-fold desc="Constant Definition">
private final static String INPUTS_VALID = "{\n" +
" \"inputs\": [\n" +
" {\n" +
" \"key\": \"text_input\",\n" +
" \"type\": \"text\",\n" +
" \"required\": true,\n" +
" \"description\": \"\",\n" +
" \"value\": \"Hallo\"\n" +
" },\n" +
" {\n" +
" \"key\": \"name_input\",\n" +
" \"type\": \"name\",\n" +
" \"required\": true,\n" +
" \"description\": \"\",\n" +
" \"value\": \"myname\"\n" +
" }\n" +
" ],\n" +
" \"_links\": {\n" +
" \"self\": {\n" +
" \"href\": \"http://localhost:8080/csars/mongo-db/transformations/p-a/inputs\"\n" +
" }\n" +
" } " +
"}";
private final static String INPUTS_INVALID = "{\n" +
" \"inputs\": [\n" +
" {\n" +
" \"key\": \"text_input\",\n" +
" \"type\": \"text\",\n" +
" \"required\": true,\n" +
" \"description\": \"\",\n" +
" \"value\": \"Hallo\"\n" +
" },\n" +
" {\n" +
" \"key\": \"unsigned_integer\",\n" +
" \"type\": \"unsigned_integer\",\n" +
" \"required\": true,\n" +
" \"description\": \"\",\n" +
" \"value\": \"-111\"\n" +
" }\n" +
" ],\n" +
" \"_links\": {\n" +
" \"self\": {\n" +
" \"href\": \"http://localhost:8080/csars/mongo-db/transformations/p-a/inputs\"\n" +
" }\n" +
" } " +
"}";
private final static String INPUTS_MISSING_VALUE = "{\n" +
" \"inputs\": [\n" +
" {\n" +
" \"key\": \"text_input\",\n" +
" \"type\": \"text\",\n" +
" \"required\": true,\n" +
" \"description\": \"\",\n" +
" },\n" +
" ],\n" +
" \"_links\": {\n" +
" \"self\": {\n" +
" \"href\": \"http://localhost:8080/csars/mongo-db/transformations/p-a/inputs\"\n" +
" }\n" +
" } " +
"}";
private final static String VALID_CSAR_NAME = "kubernetes-cluster";
private final static String VALID_PLATFORM_NAME = "p-a";
private final static String START_TRANSFORMATION_VALID_URL = "/api/csars/kubernetes-cluster/transformations/p-a/start";
private final static String INPUTS_VALID_URL = "/api/csars/kubernetes-cluster/transformations/p-a/inputs";
private final static String DEFAULT_CHARSET_HAL_JSON = "application/hal+json;charset=UTF-8";
private final static String ARTIFACT_RESPONSE_EXPECTED_URL = "http://localhost/api/csars/kubernetes-cluster/transformations/p-a/artifact";
private final static String GET_ARTIFACTS_VALID_URL = "/api/csars/kubernetes-cluster/transformations/p-a/artifact";
private final static String GET_LOGS_AT_START_ZERO_VALID_URL = "/api/csars/kubernetes-cluster/transformations/p-a/logs?start=0";
private final static String GET_LOGS_NEGATIVE_START_URL = "/api/csars/kubernetes-cluster/transformations/p-a/logs?start=-1";
private final static String DELETE_TRANSFORMATION_VALID_URL = "/api/csars/kubernetes-cluster/transformations/p-a/delete";
private final static String TRANSFORMATION_DETAILS_VALID_URL = "/api/csars/kubernetes-cluster/transformations/p-a";
private final static String APPLICATION_HAL_JSON_MIME_TYPE = "application/hal+json";
private final static String LIST_TRANSFORMATIONS_VALID_URL = "/api/csars/kubernetes-cluster/transformations/";
private final static String LIST_TRANSFORMATIONS_EXPECTED_URL = "http://localhost/api/csars/kubernetes-cluster/transformations/";
private final static String CREATE_CSAR_VALID_URL = "/api/csars/kubernetes-cluster/transformations/p-a/create";
private final static String PLATFORM_NOT_FOUND_URL = "/api/csars/kubernetes-cluster/transformations/p-z";
private final static String GET_OUTPUT_URL = "/api/csars/kubernetes-cluster/transformations/p-a/outputs";
private final static String CSAR_NOT_FOUND_URL = "/api/csars/keinechtescsar/transformations";
private static final String[] CSAR_NAMES = new String[]{"kubernetes-cluster", "apache-test", "mongo-db"};
private static final String SECOND_VALID_PLATFORM_NAME = "p-b";
private static final String INPUT_TEST_DEFAULT_VALUE = "Test-Default-Value";
private static final String PROPERTY_TEST_DEFAULT_VALUE_KEY = "default_value_property";
//</editor-fold>
private CsarService csarService;
private TransformationService transformationService;
private PlatformService platformService;
private MockMvc mvc;
//<editor-fold desc="Initialization">
@Before
public void setUp() throws Exception {
//Create Objects
mockCsarService();
mockPlatformService();
mockTransformationService();
TransformationController controller = new TransformationController(csarService, transformationService, platformService);
mvc = MockMvcBuilders.standaloneSetup(controller).build();
}
private void mockCsarService() {
csarService = mock(CsarService.class);
List<Csar> csars = new ArrayList<>();
when(csarService.getCsar(anyString())).thenReturn(Optional.empty());
for (String name : CSAR_NAMES) {
Csar csar = new CsarImpl(TestCsars.Testing.EMPTY_TOPOLOGY_TEMPLATE, name, logMock());
when(csarService.getCsar(name)).thenReturn(Optional.of(csar));
}
when(csarService.getCsars()).thenReturn(csars);
}
private void mockPlatformService() {
platformService = mock(PlatformService.class);
Set<Platform> platforms = new HashSet<>();
for (int i = 0; i < 5; i++) {
HashSet<PlatformInput> inputs = new HashSet<>();
for (PropertyType type : PropertyType.values()) {
inputs.add(new PlatformInput(type.getTypeName() + "_input", type));
}
char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
if (i == 0) {
inputs.add(new PlatformInput(
PROPERTY_TEST_DEFAULT_VALUE_KEY,
PropertyType.TEXT,
"",
false,
INPUT_TEST_DEFAULT_VALUE
));
}
platforms.add(new Platform("p-" + chars[i], "platform-" + (i + 1), inputs));
}
when(platformService.getSupportedPlatforms()).thenReturn(platforms);
when(platformService.isSupported(any(Platform.class))).thenReturn(false);
when(platformService.findPlatformById(anyString())).thenReturn(Optional.empty());
for (Platform platform : platforms) {
when(platformService.findPlatformById(platform.id)).thenReturn(Optional.of(platform));
when(platformService.isSupported(platform)).thenReturn(true);
}
}
private void mockTransformationService() {
transformationService = mock(TransformationService.class);
when(transformationService.createTransformation(any(Csar.class), any(Platform.class))).then(iom -> {
Csar csar = (Csar) iom.getArguments()[0];
Platform platform = (Platform) iom.getArguments()[1];
Transformation t = new TransformationImpl(csar, platform, logMock(), modelMock());
csar.getTransformations().put(platform.id, t);
return t;
});
}
//</editor-fold>
//<editor-fold desc="Output Tests">
@Test
public void testGetOutputs() throws Exception {
List<Transformation> transformations = preInitNonCreationTests();
Transformation t = transformations.get(0);
when(t.getState()).thenReturn(TransformationState.DONE);
String outputKey = "test_output";
List<OutputProperty> outputs = Lists.newArrayList(new PlatformInput(
outputKey,
PropertyType.TEXT,
"",
true,
"some value"
));
when(t.getOutputs()).thenReturn(outputs);
mvc.perform(get(GET_OUTPUT_URL))
.andDo(print())
.andExpect(status().is(200))
.andExpect(jsonPath("$.outputs").isArray())
.andExpect(jsonPath("$.links[0].href").value("http://localhost" + GET_OUTPUT_URL))
.andExpect(jsonPath("$.outputs[0].key").value(outputKey))
.andReturn();
}
@Test
public void testGetOutputsEmptyOutputs() throws Exception {
List<Transformation> transformations = preInitNonCreationTests();
Transformation t = transformations.get(0);
when(t.getState()).thenReturn(TransformationState.DONE);
when(t.getOutputs()).thenReturn(new ArrayList<>());
mvc.perform(get(GET_OUTPUT_URL))
.andDo(print())
.andExpect(status().is(200))
.andExpect(jsonPath("$.outputs").isArray())
.andExpect(jsonPath("$.links[0].href").value("http://localhost/api/csars/kubernetes-cluster/transformations/p-a/outputs"))
.andReturn();
}
@Test
public void testGetOutputsInvalidState() throws Exception {
List<Transformation> transformations = preInitNonCreationTests();
Transformation t = transformations.get(0);
when(t.getState()).thenReturn(TransformationState.TRANSFORMING);
mvc.perform(get(GET_OUTPUT_URL)).andDo(print()).andExpect(status().is(400)).andReturn();
}
@Test
public void testOutputInvalidPlatform() throws Exception {
mvc.perform(get(PLATFORM_NOT_FOUND_URL + "/outputs"))
.andDo(print()).andExpect(status().isNotFound()).andReturn();
}
@Test
public void testOutputInvalidCsar() throws Exception {
mvc.perform(get(CSAR_NOT_FOUND_URL + "/p-a/outputs"))
.andDo(print()).andExpect(status().isNotFound()).andReturn();
}
//</editor-fold>
//<editor-fold desc="Start transformation tests">
@Test
public void testStartTransformationSuccess() throws Exception {
preInitNonCreationTests();
when(transformationService.startTransformation(any(Transformation.class))).thenReturn(true);
mvc.perform(
post(START_TRANSFORMATION_VALID_URL)
.contentType(MediaType.APPLICATION_JSON)
.content(INPUTS_VALID)
).andDo(print())
.andExpect(status().is(200))
.andExpect(content().bytes(new byte[0]))
.andReturn();
}
@Test
public void testStartTransformationFail() throws Exception {
preInitNonCreationTests();
when(transformationService.startTransformation(any(Transformation.class))).thenReturn(false);
mvc.perform(
post(START_TRANSFORMATION_VALID_URL)
.contentType(MediaType.APPLICATION_JSON)
.content(INPUTS_VALID)
).andDo(print())
.andExpect(status().is(400))
.andExpect(content().bytes(new byte[0]))
.andReturn();
assertNotEquals(TransformationState.TRANSFORMING,
csarService.getCsar(VALID_CSAR_NAME).get().getTransformation(VALID_PLATFORM_NAME).get().getState());
}
//</editor-fold>
//<editor-fold desc="SimpleProperty tests">
@Test
public void setTransformationProperties() throws Exception {
preInitNonCreationTests();
mvc.perform(
put(INPUTS_VALID_URL)
.contentType(MediaType.APPLICATION_JSON)
.content(INPUTS_VALID)
).andDo(print())
.andExpect(status().is(200))
.andExpect(content().bytes(new byte[0]))
.andReturn();
}
@Test
public void setTransformationPropertiesInvalidInput() throws Exception {
preInitNonCreationTests();
mvc.perform(
put(INPUTS_VALID_URL)
.contentType(MediaType.APPLICATION_JSON)
.content(INPUTS_INVALID)
).andDo(print())
.andExpect(status().is(406))
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.inputs[0].valid").isBoolean())
.andExpect(jsonPath("$.inputs[0].key").isString())
.andExpect(jsonPath("$.inputs[1].valid").isBoolean())
.andExpect(jsonPath("$.inputs[1].key").isString())
.andReturn();
}
@Test
public void setTransformationPropertiesMissingValueInvalidInput() throws Exception {
preInitNonCreationTests();
mvc.perform(
put(INPUTS_VALID_URL)
.contentType(MediaType.APPLICATION_JSON)
.content(INPUTS_MISSING_VALUE)
).andDo(print())
.andExpect(status().is(400))
.andReturn();
}
@Test
public void getInputsTest() throws Exception {
preInitNonCreationTests();
MvcResult result = mvc.perform(
get(INPUTS_VALID_URL)
).andDo(print())
.andExpect(status().is(200))
.andExpect(content().contentType(DEFAULT_CHARSET_HAL_JSON))
.andExpect(jsonPath("$.inputs").isArray())
.andExpect(jsonPath("$.inputs").isNotEmpty())
.andExpect(jsonPath("$.inputs[0].key").isString())
.andExpect(jsonPath("$.inputs[0].type").isString())
.andExpect(jsonPath("$.inputs[0].description").isString())
.andExpect(jsonPath("$.inputs[0].required").isBoolean())
.andExpect(jsonPath("$.links[0].rel").value("self"))
.andExpect(jsonPath("$.links[0].href")
.value("http://localhost/api/csars/kubernetes-cluster/transformations/p-a/inputs"))
.andReturn();
MockHttpServletResponse response = result.getResponse();
String responseJson = new String(response.getContentAsByteArray());
String[] values = JsonPath.parse(responseJson).read("$.inputs[*].value", String[].class);
long nullCount = Arrays.asList(values).stream().filter(Objects::isNull).count();
long testCount = Arrays.asList(values).stream().filter(e -> e != null && e.equals(INPUT_TEST_DEFAULT_VALUE)).count();
assertEquals(8, nullCount);
assertEquals(1, testCount);
}
@Test
public void getInputsTest2() throws Exception {
preInitNonCreationTests();
//Set a SimpleProperty value
String inputKey = "secret_input";
String inputValue = "geheim";
csarService.getCsar(VALID_CSAR_NAME)
.get().getTransformation(VALID_PLATFORM_NAME).get()
.getInputs().set(inputKey, inputValue);
//Perform a request
MvcResult result = mvc.perform(
get(INPUTS_VALID_URL)
).andDo(print())
.andExpect(status().is(200))
.andExpect(content().contentType(DEFAULT_CHARSET_HAL_JSON))
.andReturn();
// Check if only one value is set (the one that has been set above) and the others are not!
JSONArray obj = new JSONObject(result.getResponse().getContentAsString()).getJSONArray("inputs");
boolean valueFound = false;
boolean restNull = true;
for (int i = 0; i < obj.length(); i++) {
JSONObject content = obj.getJSONObject(i);
if (content.getString("key").equals(inputKey)) {
valueFound = content.getString("value").equals(inputValue);
} else {
restNull = restNull && (content.isNull("value")
|| content.getString("value").equals(INPUT_TEST_DEFAULT_VALUE));
}
}
assertTrue("Could not find valid value in property list", valueFound);
assertTrue("Not all other values in property list are null or equal to the default value", restNull);
}
//</editor-fold>
//<editor-fold desc="Test Artifact Retrieval">
@Test
public void retrieveArtifact() throws Exception {
preInitNonCreationTests();
File dummyFile = new File(tmpdir, "test.bin");
dummyFile.delete();
byte[] data = ByteArrayUtils.generateRandomByteArray(new Random(123), 2048);
FileUtils.writeByteArrayToFile(dummyFile, data);
when(csarService.getCsar(VALID_CSAR_NAME).get().getTransformation(VALID_PLATFORM_NAME).get().getTargetArtifact())
.thenReturn(Optional.of(new TargetArtifact(dummyFile)));
mvc.perform(
get(GET_ARTIFACTS_VALID_URL)
)
.andExpect(status().is(200))
.andExpect(content().contentType("application/octet-stream"))
.andExpect(content().bytes(data))
.andReturn();
}
@Test
public void retrieveArtifactNotFinished() throws Exception {
preInitNonCreationTests();
when(
csarService.getCsar(VALID_CSAR_NAME).get()
.getTransformation(VALID_PLATFORM_NAME).get().getTargetArtifact()
).thenReturn(Optional.empty());
mvc.perform(
get(GET_ARTIFACTS_VALID_URL)
).andDo(print())
.andExpect(status().is(400))
.andReturn();
}
//</editor-fold>
//<editor-fold desc="Test Transformation Logs">
@Test
public void retrieveTransformationLogs() throws Exception {
preInitNonCreationTests();
mvc.perform(
get(GET_LOGS_AT_START_ZERO_VALID_URL)
).andDo(print())
.andExpect(status().is(200))
.andExpect(content().contentType(DEFAULT_CHARSET_HAL_JSON))
.andExpect(jsonPath("$.start").value(0))
.andExpect(jsonPath("$.end").isNumber())
.andExpect(jsonPath("$.logs").isArray())
.andExpect(jsonPath("$.logs[0]").exists())
.andExpect(jsonPath("$.logs[0].timestamp").isNumber())
.andExpect(jsonPath("$.logs[0].level").isString())
.andExpect(jsonPath("$.logs[0].message").isString())
.andReturn();
}
@Test
public void retrieveLogsNegativeIndex() throws Exception {
preInitNonCreationTests();
mvc.perform(
get(GET_LOGS_NEGATIVE_START_URL)
).andDo(print())
.andExpect(status().is(400));
}
//</editor-fold>
//<editor-fold desc="Delete Transformation Tests">
@Test
public void deleteTransformation() throws Exception {
preInitNonCreationTests();
//Set the return value of the delete method
when(transformationService.deleteTransformation(any(Transformation.class))).thenReturn(true);
//Execute Request
mvc.perform(
delete(DELETE_TRANSFORMATION_VALID_URL)
).andDo(print())
.andExpect(status().is(200))
.andReturn();
}
@Test
public void deleteTransformationStillRunning() throws Exception {
preInitNonCreationTests();
//Set the return value of the delete method
when(transformationService.deleteTransformation(any(Transformation.class))).thenReturn(false);
//Execute Request
mvc.perform(
delete(DELETE_TRANSFORMATION_VALID_URL)
).andDo(print())
.andExpect(status().is(400))
.andReturn();
}
//</editor-fold>
//<editor-fold desc="Transformation Details Test">
@Test
public void transformationDetails() throws Exception {
preInitNonCreationTests();
MvcResult result = mvc.perform(
get(TRANSFORMATION_DETAILS_VALID_URL).accept(APPLICATION_HAL_JSON_MIME_TYPE)
)
.andDo(print())
.andExpect(status().is(200))
.andExpect(content().contentType(DEFAULT_CHARSET_HAL_JSON))
.andExpect(jsonPath("$.phases").isArray())
.andExpect(jsonPath("$.phases").isEmpty())
.andExpect(jsonPath("$.platform").value(VALID_PLATFORM_NAME))
.andExpect(jsonPath("$.state").value("INPUT_REQUIRED"))
.andReturn();
JSONObject object = new JSONObject(result.getResponse().getContentAsString());
HALRelationUtils.validateRelations(
object.getJSONArray("links"),
getLinkRelationsForTransformationDetails(),
VALID_CSAR_NAME,
VALID_PLATFORM_NAME
);
}
private Map<String, String> getLinkRelationsForTransformationDetails() {
HashMap<String, String> map = new HashMap<>();
map.put("self", "http://localhost/api/csars/%s/transformations/%s");
map.put("logs", "http://localhost/api/csars/%s/transformations/%s/logs?start=0");
map.put("platform", "http://localhost/api/platforms/p-a");
map.put("artifact", "http://localhost/api/csars/%s/transformations/%s/artifact");
map.put("inputs", "http://localhost/api/csars/%s/transformations/%s/inputs");
map.put("delete", "http://localhost/api/csars/%s/transformations/%s/delete");
return map;
}
//</editor-fold>
//<editor-fold desc="List Transformation Tests">
@Test
public void listTransformations() throws Exception {
preInitNonCreationTests();
mvc.perform(
get(LIST_TRANSFORMATIONS_VALID_URL).accept(APPLICATION_HAL_JSON_MIME_TYPE)
)
.andDo(print())
.andExpect(status().is(200))
.andExpect(content().contentType(DEFAULT_CHARSET_HAL_JSON))
.andExpect(jsonPath("$.content").isArray())
.andExpect(jsonPath("$.content[0]").exists())
.andExpect(jsonPath("$.content[1]").exists())
.andExpect(jsonPath("$.content[2]").doesNotExist())
.andExpect(jsonPath("$.links[0].href")
.value(LIST_TRANSFORMATIONS_EXPECTED_URL))
.andExpect(jsonPath("$.links[0].rel").value("self"))
.andExpect(jsonPath("$.links[1]").doesNotExist())
.andReturn();
}
@Test
public void listEmptyTransformations() throws Exception {
mvc.perform(
get(LIST_TRANSFORMATIONS_VALID_URL).accept(DEFAULT_CHARSET_HAL_JSON)
)
.andDo(print())
.andExpect(status().is(200))
.andExpect(content().contentType(DEFAULT_CHARSET_HAL_JSON))
.andExpect(jsonPath("$.content").isArray())
.andExpect(jsonPath("$.content[0]").doesNotExist())
.andExpect(jsonPath("$.links[0].href")
.value(LIST_TRANSFORMATIONS_EXPECTED_URL))
.andExpect(jsonPath("$.links[0].rel").value("self"))
.andExpect(jsonPath("$.links[1]").doesNotExist())
.andReturn();
}
//</editor-fold>
//<editor-fold desc="Create Transformation Tests">
@Test
public void createTransformation() throws Exception {
//Make sure no previous transformations are present
assertEquals(0, csarService.getCsar(VALID_CSAR_NAME).get().getTransformations().size());
//Call creation Request
mvc.perform(put(CREATE_CSAR_VALID_URL))
.andDo(print())
.andExpect(status().is(200))
.andExpect(content().bytes(new byte[0]))
.andReturn();
//Check if the transformation has been added to the archive
assertEquals(1, csarService.getCsar(VALID_CSAR_NAME).get().getTransformations().size());
assertTrue(csarService.getCsar(VALID_CSAR_NAME).get().getTransformation(VALID_PLATFORM_NAME).isPresent());
}
@Test
public void createTransformationTwice() throws Exception {
//call the first time
mvc.perform(put(CREATE_CSAR_VALID_URL))
.andDo(print())
.andExpect(status().is(200))
.andExpect(content().bytes(new byte[0]))
.andReturn();
//Call the second time
mvc.perform(put(CREATE_CSAR_VALID_URL))
.andDo(print())
.andExpect(status().is(400))
.andExpect(content().bytes(new byte[0]))
.andReturn();
}
//</editor-fold>
//<editor-fold desc="Platform Not found Tests">
@Test
public void newTransformationPlatformNotFound() throws Exception {
mvc.perform(put(PLATFORM_NOT_FOUND_URL + "/create"))
.andDo(print()).andExpect(status().isNotFound()).andReturn();
}
@Test
public void transformationInfoPlatformNotFound() throws Exception {
mvc.perform(get(PLATFORM_NOT_FOUND_URL + ""))
.andDo(print()).andExpect(status().isNotFound()).andReturn();
}
@Test
public void transformationLogsPlatformNotFound() throws Exception {
mvc.perform(get(PLATFORM_NOT_FOUND_URL + "/logs"))
.andDo(print()).andExpect(status().isNotFound()).andReturn();
}
@Test
public void transformationArtifactPlatformNotFound() throws Exception {
mvc.perform(get(PLATFORM_NOT_FOUND_URL + "/artifacts"))
.andDo(print()).andExpect(status().isNotFound()).andReturn();
}
@Test
public void transformationPropertiesGetPlatformNotFound() throws Exception {
mvc.perform(get(PLATFORM_NOT_FOUND_URL + "/inputs"))
.andDo(print()).andExpect(status().isNotFound()).andReturn();
}
@Test
public void transformationInputsPutPlatformNotFound() throws Exception {
mvc.perform(
put(PLATFORM_NOT_FOUND_URL + "/inputs")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"inputs\": [{}]}")
).andDo(print()).andExpect(status().isNotFound()).andReturn();
}
@Test
public void transformationDeletePlatformNotFound() throws Exception {
mvc.perform(delete(PLATFORM_NOT_FOUND_URL + "/delete"))
.andDo(print()).andExpect(status().isNotFound()).andReturn();
}
@Test
public void transformationStartPlatformNotFound() throws Exception {
mvc.perform(delete(PLATFORM_NOT_FOUND_URL + "/delete"))
.andDo(print()).andExpect(status().isNotFound()).andReturn();
}
//</editor-fold>
//<editor-fold desc="CSAR Not found Tests">
@Test
public void listTransformationsCsarNotFound() throws Exception {
mvc.perform(get(CSAR_NOT_FOUND_URL + ""))
.andDo(print()).andExpect(status().isNotFound()).andReturn();
}
@Test
public void newTransformationCsarNotFound() throws Exception {
mvc.perform(put(CSAR_NOT_FOUND_URL + "/p-a/create"))
.andDo(print()).andExpect(status().isNotFound()).andReturn();
}
@Test
public void transformationInfoCsarNotFound() throws Exception {
mvc.perform(get(CSAR_NOT_FOUND_URL + "/p-a"))
.andDo(print()).andExpect(status().isNotFound()).andReturn();
}
@Test
public void transformationLogsCsarNotFound() throws Exception {
mvc.perform(get(CSAR_NOT_FOUND_URL + "/p-a/logs"))
.andDo(print()).andExpect(status().isNotFound()).andReturn();
}
@Test
public void transformationArtifactCsarNotFound() throws Exception {
mvc.perform(get(CSAR_NOT_FOUND_URL + "/p-a/artifacts"))
.andDo(print()).andExpect(status().isNotFound()).andReturn();
}
@Test
public void transformationInputsGetCsarNotFound() throws Exception {
mvc.perform(get(CSAR_NOT_FOUND_URL + "/p-a/inputs"))
.andDo(print()).andExpect(status().isNotFound()).andReturn();
}
@Test
public void transformationInputsPutCsarNotFound() throws Exception {
mvc.perform(
put(CSAR_NOT_FOUND_URL + "/p-a/inputs")
.content("{\"inputs\": [{}]}")
.contentType(MediaType.APPLICATION_JSON)
).andDo(print()).andExpect(status().isNotFound()).andReturn();
}
@Test
public void transformationDeleteCsarNotFound() throws Exception {
mvc.perform(delete(CSAR_NOT_FOUND_URL + "/p-a/delete"))
.andDo(print()).andExpect(status().isNotFound()).andReturn();
}
@Test
public void transformationStartCsarNotFound() throws Exception {
mvc.perform(post(CSAR_NOT_FOUND_URL + "/p-a/start"))
.andDo(print()).andExpect(status().isNotFound()).andReturn();
}
//</editor-fold>
//<editor-fold desc="Util Methods">
public List<Transformation> preInitNonCreationTests() throws PlatformNotFoundException {
//add a transformation
Optional<Csar> csar = csarService.getCsar(VALID_CSAR_NAME);
assertTrue(csar.isPresent());
String[] pnames = {VALID_PLATFORM_NAME, SECOND_VALID_PLATFORM_NAME};
List<Transformation> transformations = new ArrayList<>();
for (String pname : pnames) {
LogEntry entry = new LogEntry(0, "Test Context", "Test Message", Level.DEBUG);
Log mockLog = logMock();
when(mockLog.getLogEntries(0)).thenReturn(Collections.singletonList(entry));
Transformation transformation = new TransformationImpl(
csar.get(),
platformService.findPlatformById(pname).get(),
mockLog, modelMock()
);
transformation = spy(transformation);
transformations.add(transformation);
csar.get().getTransformations().put(pname, transformation);
}
return transformations;
}
//</editor-fold>
}
| {'content_hash': '81623e14df26ee586250d4945ec2c72e', 'timestamp': '', 'source': 'github', 'line_count': 777, 'max_line_length': 142, 'avg_line_length': 42.316602316602314, 'alnum_prop': 0.6213199513381995, 'repo_name': 'StuPro-TOSCAna/TOSCAna', 'id': '0500c444513648693775793998d01616987ccba5', 'size': '32880', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'server/src/test/java/org/opentosca/toscana/api/TransformationControllerTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '8990'}, {'name': 'HTML', 'bytes': '13048'}, {'name': 'Java', 'bytes': '1354530'}, {'name': 'JavaScript', 'bytes': '1645'}, {'name': 'PHP', 'bytes': '8242'}, {'name': 'Python', 'bytes': '7794'}, {'name': 'Shell', 'bytes': '18091'}, {'name': 'TypeScript', 'bytes': '157482'}]} |
Pelican theme based on Materialize starter
| {'content_hash': '1a7250411af4447589681378ac94415e', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 42, 'avg_line_length': 15.0, 'alnum_prop': 0.8222222222222222, 'repo_name': 'Bleno/pelican-materialize-parallax', 'id': 'c91b749d9b10642b97f2a7bda8e29caaddd32f2f', 'size': '76', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '192708'}, {'name': 'HTML', 'bytes': '7156'}, {'name': 'JavaScript', 'bytes': '278785'}]} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>pymatgen.analysis.interface_reactions module — pymatgen 2017.11.6 documentation</title>
<link rel="stylesheet" href="_static/proBlue.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '2017.11.6',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<link rel="shortcut icon" href="_static/favicon.ico"/>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Search" href="search.html" />
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-33990148-1']);
_gaq.push(['_trackPageview']);
</script>
</head>
<body>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="nav-item nav-item-0"><a href="index.html">pymatgen 2017.11.6 documentation</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="module-pymatgen.analysis.interface_reactions">
<span id="pymatgen-analysis-interface-reactions-module"></span><h1>pymatgen.analysis.interface_reactions module<a class="headerlink" href="#module-pymatgen.analysis.interface_reactions" title="Permalink to this headline">¶</a></h1>
<dl class="class">
<dt id="pymatgen.analysis.interface_reactions.InterfacialReactivity">
<em class="property">class </em><code class="descname">InterfacialReactivity</code><span class="sig-paren">(</span><em>c1</em>, <em>c2</em>, <em>pd</em>, <em>norm=True</em>, <em>include_no_mixing_energy=False</em>, <em>pd_non_grand=None</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/pymatgen/analysis/interface_reactions.html#InterfacialReactivity"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pymatgen.analysis.interface_reactions.InterfacialReactivity" title="Permalink to this definition">¶</a></dt>
<dd><p>Bases: <code class="xref py py-class docutils literal"><span class="pre">object</span></code></p>
<p>An object encompassing all relevant data for interface reactions.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>c1</strong> (<a class="reference internal" href="pymatgen.core.composition.html#pymatgen.core.composition.Composition" title="pymatgen.core.composition.Composition"><em>Composition</em></a>) – Composition object for reactant 1.</li>
<li><strong>c2</strong> (<a class="reference internal" href="pymatgen.core.composition.html#pymatgen.core.composition.Composition" title="pymatgen.core.composition.Composition"><em>Composition</em></a>) – Composition object for reactant 2.</li>
<li><strong>pd</strong> (<a class="reference internal" href="pymatgen.analysis.phase_diagram.html#pymatgen.analysis.phase_diagram.PhaseDiagram" title="pymatgen.analysis.phase_diagram.PhaseDiagram"><em>PhaseDiagram</em></a>) – PhaseDiagram object or GrandPotentialPhaseDiagram
object built from all elements in composition c1 and c2.</li>
<li><strong>norm</strong> (<em>bool</em>) – Whether or not the total number of atoms in composition
of reactant will be normalized to 1.</li>
<li><strong>include_no_mixing_energy</strong> (<em>bool</em>) – No_mixing_energy for a reactant is the
opposite number of its energy above grand potential convex hull. In
cases where reactions involve elements reservoir, this param
determines whether no_mixing_energy of reactants will be included
in the final reaction energy calculation. By definition, if pd is
not a GrandPotentialPhaseDiagram object, this param is False.</li>
<li><strong>pd_non_grand</strong> (<a class="reference internal" href="pymatgen.analysis.phase_diagram.html#pymatgen.analysis.phase_diagram.PhaseDiagram" title="pymatgen.analysis.phase_diagram.PhaseDiagram"><em>PhaseDiagram</em></a>) – PhaseDiagram object but not
GrandPotentialPhaseDiagram object built from elements in c1 and c2.</li>
</ul>
</td>
</tr>
</tbody>
</table>
<dl class="method">
<dt id="pymatgen.analysis.interface_reactions.InterfacialReactivity.get_kinks">
<code class="descname">get_kinks</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pymatgen/analysis/interface_reactions.html#InterfacialReactivity.get_kinks"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pymatgen.analysis.interface_reactions.InterfacialReactivity.get_kinks" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds all the kinks in mixing ratio where reaction products changes
along the tie line of composition self.c1 and composition self.c2.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Returns:</th><td class="field-body"><dl class="docutils">
<dt>Zip object of tuples (index, mixing ratio,</dt>
<dd>reaction energy, reaction formula).</dd>
</dl>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="method">
<dt id="pymatgen.analysis.interface_reactions.InterfacialReactivity.get_no_mixing_energy">
<code class="descname">get_no_mixing_energy</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pymatgen/analysis/interface_reactions.html#InterfacialReactivity.get_no_mixing_energy"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pymatgen.analysis.interface_reactions.InterfacialReactivity.get_no_mixing_energy" title="Permalink to this definition">¶</a></dt>
<dd><p>Generates the opposite number of energy above grand potential
convex hull for both reactants.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Returns:</th><td class="field-body">[(reactant1, no_mixing_energy1),(reactant2,no_mixing_energy2)].</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="method">
<dt id="pymatgen.analysis.interface_reactions.InterfacialReactivity.get_products">
<code class="descname">get_products</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pymatgen/analysis/interface_reactions.html#InterfacialReactivity.get_products"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pymatgen.analysis.interface_reactions.InterfacialReactivity.get_products" title="Permalink to this definition">¶</a></dt>
<dd><p>List of formulas of potential products. E.g., [‘Li’,’O2’,’Mn’].</p>
</dd></dl>
<dl class="method">
<dt id="pymatgen.analysis.interface_reactions.InterfacialReactivity.labels">
<code class="descname">labels</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pymatgen/analysis/interface_reactions.html#InterfacialReactivity.labels"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pymatgen.analysis.interface_reactions.InterfacialReactivity.labels" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a dictionary containing kink information:
{index: ‘x= mixing_ratio energy= reaction_energy reaction_equation’}.
E.g., {1: ‘x= 0.0 energy = 0.0 Mn -> Mn’,</p>
<blockquote>
<div>2: ‘x= 0.5 energy = -15.0 O2 + Mn -> MnO2’,
3: ‘x= 1.0 energy = 0.0 O2 -> O2’}.</div></blockquote>
</dd></dl>
<dl class="method">
<dt id="pymatgen.analysis.interface_reactions.InterfacialReactivity.minimum">
<code class="descname">minimum</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pymatgen/analysis/interface_reactions.html#InterfacialReactivity.minimum"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pymatgen.analysis.interface_reactions.InterfacialReactivity.minimum" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds the minimum reaction energy E_min and corresponding
mixing ratio x_min.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Returns:</th><td class="field-body">Tuple (x_min, E_min).</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="method">
<dt id="pymatgen.analysis.interface_reactions.InterfacialReactivity.plot">
<code class="descname">plot</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/pymatgen/analysis/interface_reactions.html#InterfacialReactivity.plot"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#pymatgen.analysis.interface_reactions.InterfacialReactivity.plot" title="Permalink to this definition">¶</a></dt>
<dd><p>Plots reaction energy as a function of mixing ratio x in
self.c1 - self.c2 tie line using pylab.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Returns:</th><td class="field-body">Pylab object that plots reaction energy as a function of
mixing ratio x.</td>
</tr>
</tbody>
</table>
</dd></dl>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="_sources/pymatgen.analysis.interface_reactions.rst.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3>Quick search</h3>
<form class="search" action="search.html" method="get">
<div><input type="text" name="q" /></div>
<div><input type="submit" value="Go" /></div>
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="nav-item nav-item-0"><a href="index.html">pymatgen 2017.11.6 documentation</a> »</li>
</ul>
</div>
<div class="footer" role="contentinfo">
© Copyright 2011, Pymatgen Development Team.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.5.
</div>
<div class="footer">This page uses <a href="http://analytics.google.com/">
Google Analytics</a> to collect statistics. You can disable it by blocking
the JavaScript coming from www.google-analytics.com.
<script type="text/javascript">
(function() {
var ga = document.createElement('script');
ga.src = ('https:' == document.location.protocol ?
'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
ga.setAttribute('async', 'true');
document.documentElement.firstChild.appendChild(ga);
})();
</script>
</div>
</body>
</html> | {'content_hash': 'fb95344fd689153d49322f05c1916cab', 'timestamp': '', 'source': 'github', 'line_count': 230, 'max_line_length': 568, 'avg_line_length': 55.995652173913044, 'alnum_prop': 0.6961720630483733, 'repo_name': 'Bismarrck/pymatgen', 'id': '15f8ece7d7bd49e03afd4180e877a66a368e43bc', 'size': '12928', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'docs/pymatgen.analysis.interface_reactions.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '5938'}, {'name': 'C', 'bytes': '1278109'}, {'name': 'CSS', 'bytes': '7550'}, {'name': 'Common Lisp', 'bytes': '3029065'}, {'name': 'HTML', 'bytes': '4913914'}, {'name': 'Makefile', 'bytes': '5573'}, {'name': 'Perl', 'bytes': '229104'}, {'name': 'Propeller Spin', 'bytes': '4026362'}, {'name': 'Python', 'bytes': '6094090'}, {'name': 'Roff', 'bytes': '868'}]} |
using UnityEngine;
using System.Collections;
public class Disco : MonoBehaviour {
private Rigidbody2D body;
public float GOAL_POSITION_MIN;
public float GOAL_POSITION_MAX;
public GameController gameController;
// Use this for initialization
void Start () {
this.body = this.GetComponent<Rigidbody2D> ();
}
void FixedUpdate() {
if (transform.position.x < GOAL_POSITION_MIN) {
// Gol do segundo time!
gameController.UpdateScore(GameController.TEAM_2);
ResetPostion();
}
else if (transform.position.x > GOAL_POSITION_MAX) {
// Gol do primeiro time!
gameController.UpdateScore(GameController.TEAM_1);
ResetPostion();
}
}
private void ResetPostion() {
transform.position = new Vector2 (0.037f, -0.027f);
body.velocity = new Vector3 (0, 0, 0);
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter(Collider other) {
if (other.gameObject.tag == "Border") {
}
}
void OnCollisionEnter2D(Collision2D coll) {
}
}
| {'content_hash': 'a9a9240760a25d6f037bd5b97466490b', 'timestamp': '', 'source': 'github', 'line_count': 49, 'max_line_length': 54, 'avg_line_length': 20.285714285714285, 'alnum_prop': 0.6961770623742455, 'repo_name': 'rogersdk/airhockeymundy', 'id': '0ae5399186d3c3f3d4e642fc724064b42049caad', 'size': '996', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Assets/Scripts/Disco.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '5031'}]} |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _content = require('./content');
var _content2 = _interopRequireDefault(_content);
var _util = require('./util');
var Util = _interopRequireWildcard(_util);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var debug = require('debug')('tibbar:request');
var Request = function () {
function Request(msg) {
_classCallCheck(this, Request);
debug('.constructor() msg=' + JSON.stringify(msg));
this._msg = msg;
}
_createClass(Request, [{
key: 'message',
get: function get() {
return this._msg;
}
}, {
key: 'content',
get: function get() {
return new _content2.default(this._msg.content);
}
}]);
return Request;
}();
exports.default = Request; | {'content_hash': 'eeccf5ec533fbe6f8005a050ad71da09', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 564, 'avg_line_length': 37.520833333333336, 'alnum_prop': 0.6918378678511938, 'repo_name': 'brendan-myers/tibbar', 'id': '735fb4e17d6894cc6866aae1f00010e5e654477c', 'size': '1801', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/request.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '54963'}]} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_74) on Fri Apr 01 14:42:06 CDT 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Uses of Class org.apache.solr.core.ConfigSet (Solr 6.0.0 API)</title>
<meta name="date" content="2016-04-01">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.solr.core.ConfigSet (Solr 6.0.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/solr/core/ConfigSet.html" title="class in org.apache.solr.core">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/solr/core/class-use/ConfigSet.html" target="_top">Frames</a></li>
<li><a href="ConfigSet.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.solr.core.ConfigSet" class="title">Uses of Class<br>org.apache.solr.core.ConfigSet</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../org/apache/solr/core/ConfigSet.html" title="class in org.apache.solr.core">ConfigSet</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.apache.solr.core">org.apache.solr.core</a></td>
<td class="colLast">
<div class="block">Core classes implementin Solr internals and the management of <a href="../../../../../org/apache/solr/core/SolrCore.html" title="class in org.apache.solr.core"><code>SolrCore</code></a>s</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.apache.solr.core">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../org/apache/solr/core/ConfigSet.html" title="class in org.apache.solr.core">ConfigSet</a> in <a href="../../../../../org/apache/solr/core/package-summary.html">org.apache.solr.core</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../org/apache/solr/core/package-summary.html">org.apache.solr.core</a> that return <a href="../../../../../org/apache/solr/core/ConfigSet.html" title="class in org.apache.solr.core">ConfigSet</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../org/apache/solr/core/ConfigSet.html" title="class in org.apache.solr.core">ConfigSet</a></code></td>
<td class="colLast"><span class="typeNameLabel">ConfigSetService.</span><code><span class="memberNameLink"><a href="../../../../../org/apache/solr/core/ConfigSetService.html#getConfig-org.apache.solr.core.CoreDescriptor-">getConfig</a></span>(<a href="../../../../../org/apache/solr/core/CoreDescriptor.html" title="class in org.apache.solr.core">CoreDescriptor</a> dcore)</code>
<div class="block">Load the ConfigSet for a core</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../org/apache/solr/core/package-summary.html">org.apache.solr.core</a> with parameters of type <a href="../../../../../org/apache/solr/core/ConfigSet.html" title="class in org.apache.solr.core">ConfigSet</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../org/apache/solr/core/SolrCore.html" title="class in org.apache.solr.core">SolrCore</a></code></td>
<td class="colLast"><span class="typeNameLabel">SolrCore.</span><code><span class="memberNameLink"><a href="../../../../../org/apache/solr/core/SolrCore.html#reload-org.apache.solr.core.ConfigSet-">reload</a></span>(<a href="../../../../../org/apache/solr/core/ConfigSet.html" title="class in org.apache.solr.core">ConfigSet</a> coreConfig)</code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation">
<caption><span>Constructors in <a href="../../../../../org/apache/solr/core/package-summary.html">org.apache.solr.core</a> with parameters of type <a href="../../../../../org/apache/solr/core/ConfigSet.html" title="class in org.apache.solr.core">ConfigSet</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/apache/solr/core/SolrCore.html#SolrCore-org.apache.solr.core.CoreDescriptor-org.apache.solr.core.ConfigSet-">SolrCore</a></span>(<a href="../../../../../org/apache/solr/core/CoreDescriptor.html" title="class in org.apache.solr.core">CoreDescriptor</a> cd,
<a href="../../../../../org/apache/solr/core/ConfigSet.html" title="class in org.apache.solr.core">ConfigSet</a> coreConfig)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/solr/core/ConfigSet.html" title="class in org.apache.solr.core">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/solr/core/class-use/ConfigSet.html" target="_top">Frames</a></li>
<li><a href="ConfigSet.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright © 2000-2016 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
| {'content_hash': 'e652604ea5218a55d20a110dd555e74c', 'timestamp': '', 'source': 'github', 'line_count': 209, 'max_line_length': 384, 'avg_line_length': 45.44497607655502, 'alnum_prop': 0.6320277953253316, 'repo_name': 'Velaya/gbol_solr', 'id': 'a463d0f18e8ae7b39a4c6368173db115d8c7be03', 'size': '9498', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/solr-core/org/apache/solr/core/class-use/ConfigSet.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AMPL', 'bytes': '291'}, {'name': 'Batchfile', 'bytes': '51479'}, {'name': 'CSS', 'bytes': '240144'}, {'name': 'HTML', 'bytes': '214928'}, {'name': 'JavaScript', 'bytes': '1209383'}, {'name': 'Python', 'bytes': '20489'}, {'name': 'Shell', 'bytes': '80760'}, {'name': 'XSLT', 'bytes': '49889'}]} |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sites', '0001_initial'),
('coop_cms', '0010_auto_20170320_1349'),
]
operations = [
migrations.AddField(
model_name='link',
name='sites',
field=models.ManyToManyField(to='sites.Site', blank=True),
),
]
| {'content_hash': 'ccda8b0e36541d9db7e75cf75d4479d0', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 70, 'avg_line_length': 22.823529411764707, 'alnum_prop': 0.5618556701030928, 'repo_name': 'ljean/coop_cms', 'id': '01c755bbc8f70104d7eac658b70ce0c6c13c2262', 'size': '413', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'coop_cms/migrations/0011_auto_20170502_1124.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '54725'}, {'name': 'HTML', 'bytes': '98489'}, {'name': 'JavaScript', 'bytes': '296202'}, {'name': 'Python', 'bytes': '985749'}]} |
namespace blink {
class InterpolationEnvironment;
// Subclasses of InterpolationType implement the logic for a specific value type
// of a specific PropertyHandle to:
// - Convert PropertySpecificKeyframe values to (Pairwise)?InterpolationValues:
// maybeConvertPairwise() and maybeConvertSingle()
// - Convert the target Element's property value to an InterpolationValue:
// maybeConvertUnderlyingValue()
// - Apply an InterpolationValue to a target Element's property: apply().
class InterpolationType {
USING_FAST_MALLOC(InterpolationType);
WTF_MAKE_NONCOPYABLE(InterpolationType);
public:
PropertyHandle getProperty() const { return m_property; }
// ConversionCheckers are returned from calls to maybeConvertPairwise() and
// maybeConvertSingle() to enable the caller to check whether the result is
// still valid given changes in the InterpolationEnvironment and underlying
// InterpolationValue.
class ConversionChecker {
USING_FAST_MALLOC(ConversionChecker);
WTF_MAKE_NONCOPYABLE(ConversionChecker);
public:
virtual ~ConversionChecker() {}
void setType(const InterpolationType& type) { m_type = &type; }
const InterpolationType& type() const { return *m_type; }
virtual bool isValid(const InterpolationEnvironment&,
const InterpolationValue& underlying) const = 0;
protected:
ConversionChecker() : m_type(nullptr) {}
const InterpolationType* m_type;
};
using ConversionCheckers = Vector<std::unique_ptr<ConversionChecker>>;
virtual PairwiseInterpolationValue maybeConvertPairwise(
const PropertySpecificKeyframe& startKeyframe,
const PropertySpecificKeyframe& endKeyframe,
const InterpolationEnvironment& environment,
const InterpolationValue& underlying,
ConversionCheckers& conversionCheckers) const {
InterpolationValue start = maybeConvertSingle(
startKeyframe, environment, underlying, conversionCheckers);
if (!start)
return nullptr;
InterpolationValue end = maybeConvertSingle(endKeyframe, environment,
underlying, conversionCheckers);
if (!end)
return nullptr;
return maybeMergeSingles(std::move(start), std::move(end));
}
virtual InterpolationValue maybeConvertSingle(
const PropertySpecificKeyframe&,
const InterpolationEnvironment&,
const InterpolationValue& underlying,
ConversionCheckers&) const = 0;
virtual InterpolationValue maybeConvertUnderlyingValue(
const InterpolationEnvironment&) const = 0;
virtual void composite(UnderlyingValueOwner& underlyingValueOwner,
double underlyingFraction,
const InterpolationValue& value,
double interpolationFraction) const {
DCHECK(!underlyingValueOwner.value().nonInterpolableValue);
DCHECK(!value.nonInterpolableValue);
underlyingValueOwner.mutableValue().interpolableValue->scaleAndAdd(
underlyingFraction, *value.interpolableValue);
}
virtual void apply(const InterpolableValue&,
const NonInterpolableValue*,
InterpolationEnvironment&) const = 0;
// Implement reference equality checking via pointer equality checking as
// these are singletons.
bool operator==(const InterpolationType& other) const {
return this == &other;
}
bool operator!=(const InterpolationType& other) const {
return this != &other;
}
protected:
InterpolationType(PropertyHandle property) : m_property(property) {}
virtual PairwiseInterpolationValue maybeMergeSingles(
InterpolationValue&& start,
InterpolationValue&& end) const {
DCHECK(!start.nonInterpolableValue);
DCHECK(!end.nonInterpolableValue);
return PairwiseInterpolationValue(std::move(start.interpolableValue),
std::move(end.interpolableValue),
nullptr);
}
const PropertyHandle m_property;
};
} // namespace blink
#endif // InterpolationType_h
| {'content_hash': '3007efe9e8011ea28672f9616a71dcab', 'timestamp': '', 'source': 'github', 'line_count': 107, 'max_line_length': 80, 'avg_line_length': 38.08411214953271, 'alnum_prop': 0.7131288343558282, 'repo_name': 'google-ar/WebARonARCore', 'id': 'd11a8af2c7175b13af6f0f6bbc3d4b75c28d7db5', 'size': '4660', 'binary': False, 'copies': '2', 'ref': 'refs/heads/webarcore_57.0.2987.5', 'path': 'third_party/WebKit/Source/core/animation/InterpolationType.h', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
namespace content {
class SitePerProcessWebContentsObserver: public WebContentsObserver {
public:
explicit SitePerProcessWebContentsObserver(WebContents* web_contents)
: WebContentsObserver(web_contents),
navigation_succeeded_(true) {}
virtual ~SitePerProcessWebContentsObserver() {}
virtual void DidFailProvisionalLoad(
int64 frame_id,
bool is_main_frame,
const GURL& validated_url,
int error_code,
const string16& error_description,
RenderViewHost* render_view_host) OVERRIDE {
navigation_url_ = validated_url;
navigation_succeeded_ = false;
}
virtual void DidCommitProvisionalLoadForFrame(
int64 frame_id,
bool is_main_frame,
const GURL& url,
PageTransition transition_type,
RenderViewHost* render_view_host) OVERRIDE{
navigation_url_ = url;
navigation_succeeded_ = true;
}
const GURL& navigation_url() const {
return navigation_url_;
}
int navigation_succeeded() const { return navigation_succeeded_; }
private:
GURL navigation_url_;
bool navigation_succeeded_;
DISALLOW_COPY_AND_ASSIGN(SitePerProcessWebContentsObserver);
};
class RedirectNotificationObserver : public NotificationObserver {
public:
// Register to listen for notifications of the given type from either a
// specific source, or from all sources if |source| is
// NotificationService::AllSources().
RedirectNotificationObserver(int notification_type,
const NotificationSource& source);
virtual ~RedirectNotificationObserver();
// Wait until the specified notification occurs. If the notification was
// emitted between the construction of this object and this call then it
// returns immediately.
void Wait();
// Returns NotificationService::AllSources() if we haven't observed a
// notification yet.
const NotificationSource& source() const {
return source_;
}
const NotificationDetails& details() const {
return details_;
}
// NotificationObserver:
virtual void Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) OVERRIDE;
private:
bool seen_;
bool seen_twice_;
bool running_;
NotificationRegistrar registrar_;
NotificationSource source_;
NotificationDetails details_;
scoped_refptr<MessageLoopRunner> message_loop_runner_;
DISALLOW_COPY_AND_ASSIGN(RedirectNotificationObserver);
};
RedirectNotificationObserver::RedirectNotificationObserver(
int notification_type,
const NotificationSource& source)
: seen_(false),
running_(false),
source_(NotificationService::AllSources()) {
registrar_.Add(this, notification_type, source);
}
RedirectNotificationObserver::~RedirectNotificationObserver() {}
void RedirectNotificationObserver::Wait() {
if (seen_ && seen_twice_)
return;
running_ = true;
message_loop_runner_ = new MessageLoopRunner;
message_loop_runner_->Run();
EXPECT_TRUE(seen_);
}
void RedirectNotificationObserver::Observe(
int type,
const NotificationSource& source,
const NotificationDetails& details) {
source_ = source;
details_ = details;
seen_twice_ = seen_;
seen_ = true;
if (!running_)
return;
message_loop_runner_->Quit();
running_ = false;
}
class SitePerProcessBrowserTest : public ContentBrowserTest {
public:
SitePerProcessBrowserTest() {}
bool NavigateIframeToURL(Shell* window,
const GURL& url,
std::string iframe_id) {
std::string script = base::StringPrintf(
"var iframes = document.getElementById('%s');iframes.src='%s';",
iframe_id.c_str(), url.spec().c_str());
WindowedNotificationObserver load_observer(
NOTIFICATION_LOAD_STOP,
Source<NavigationController>(
&shell()->web_contents()->GetController()));
bool result = ExecuteScript(window->web_contents(), script);
load_observer.Wait();
return result;
}
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
command_line->AppendSwitch(switches::kSitePerProcess);
}
};
// TODO(nasko): Disable this test until out-of-process iframes is ready and the
// security checks are back in place.
IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, DISABLED_CrossSiteIframe) {
ASSERT_TRUE(test_server()->Start());
net::SpawnedTestServer https_server(
net::SpawnedTestServer::TYPE_HTTPS,
net::SpawnedTestServer::kLocalhost,
base::FilePath(FILE_PATH_LITERAL("content/test/data")));
ASSERT_TRUE(https_server.Start());
GURL main_url(test_server()->GetURL("files/site_per_process_main.html"));
NavigateToURL(shell(), main_url);
SitePerProcessWebContentsObserver observer(shell()->web_contents());
{
// Load same-site page into Iframe.
GURL http_url(test_server()->GetURL("files/title1.html"));
EXPECT_TRUE(NavigateIframeToURL(shell(), http_url, "test"));
EXPECT_EQ(observer.navigation_url(), http_url);
EXPECT_TRUE(observer.navigation_succeeded());
}
{
// Load cross-site page into Iframe.
GURL https_url(https_server.GetURL("files/title1.html"));
EXPECT_TRUE(NavigateIframeToURL(shell(), https_url, "test"));
EXPECT_EQ(observer.navigation_url(), https_url);
EXPECT_FALSE(observer.navigation_succeeded());
}
}
// TODO(nasko): Disable this test until out-of-process iframes is ready and the
// security checks are back in place.
IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
DISABLED_CrossSiteIframeRedirectOnce) {
ASSERT_TRUE(test_server()->Start());
net::SpawnedTestServer https_server(
net::SpawnedTestServer::TYPE_HTTPS,
net::SpawnedTestServer::kLocalhost,
base::FilePath(FILE_PATH_LITERAL("content/test/data")));
ASSERT_TRUE(https_server.Start());
GURL main_url(test_server()->GetURL("files/site_per_process_main.html"));
GURL http_url(test_server()->GetURL("files/title1.html"));
GURL https_url(https_server.GetURL("files/title1.html"));
NavigateToURL(shell(), main_url);
SitePerProcessWebContentsObserver observer(shell()->web_contents());
{
// Load cross-site client-redirect page into Iframe.
// Should be blocked.
GURL client_redirect_https_url(https_server.GetURL(
"client-redirect?files/title1.html"));
EXPECT_TRUE(NavigateIframeToURL(shell(),
client_redirect_https_url, "test"));
// DidFailProvisionalLoad when navigating to client_redirect_https_url.
EXPECT_EQ(observer.navigation_url(), client_redirect_https_url);
EXPECT_FALSE(observer.navigation_succeeded());
}
{
// Load cross-site server-redirect page into Iframe,
// which redirects to same-site page.
GURL server_redirect_http_url(https_server.GetURL(
"server-redirect?" + http_url.spec()));
EXPECT_TRUE(NavigateIframeToURL(shell(),
server_redirect_http_url, "test"));
EXPECT_EQ(observer.navigation_url(), http_url);
EXPECT_TRUE(observer.navigation_succeeded());
}
{
// Load cross-site server-redirect page into Iframe,
// which redirects to cross-site page.
GURL server_redirect_http_url(https_server.GetURL(
"server-redirect?files/title1.html"));
EXPECT_TRUE(NavigateIframeToURL(shell(),
server_redirect_http_url, "test"));
// DidFailProvisionalLoad when navigating to https_url.
EXPECT_EQ(observer.navigation_url(), https_url);
EXPECT_FALSE(observer.navigation_succeeded());
}
{
// Load same-site server-redirect page into Iframe,
// which redirects to cross-site page.
GURL server_redirect_http_url(test_server()->GetURL(
"server-redirect?" + https_url.spec()));
EXPECT_TRUE(NavigateIframeToURL(shell(),
server_redirect_http_url, "test"));
EXPECT_EQ(observer.navigation_url(), https_url);
EXPECT_FALSE(observer.navigation_succeeded());
}
{
// Load same-site client-redirect page into Iframe,
// which redirects to cross-site page.
GURL client_redirect_http_url(test_server()->GetURL(
"client-redirect?" + https_url.spec()));
RedirectNotificationObserver load_observer2(
NOTIFICATION_LOAD_STOP,
Source<NavigationController>(
&shell()->web_contents()->GetController()));
EXPECT_TRUE(NavigateIframeToURL(shell(),
client_redirect_http_url, "test"));
// Same-site Client-Redirect Page should be loaded successfully.
EXPECT_EQ(observer.navigation_url(), client_redirect_http_url);
EXPECT_TRUE(observer.navigation_succeeded());
// Redirecting to Cross-site Page should be blocked.
load_observer2.Wait();
EXPECT_EQ(observer.navigation_url(), https_url);
EXPECT_FALSE(observer.navigation_succeeded());
}
{
// Load same-site server-redirect page into Iframe,
// which redirects to same-site page.
GURL server_redirect_http_url(test_server()->GetURL(
"server-redirect?files/title1.html"));
EXPECT_TRUE(NavigateIframeToURL(shell(),
server_redirect_http_url, "test"));
EXPECT_EQ(observer.navigation_url(), http_url);
EXPECT_TRUE(observer.navigation_succeeded());
}
{
// Load same-site client-redirect page into Iframe,
// which redirects to same-site page.
GURL client_redirect_http_url(test_server()->GetURL(
"client-redirect?" + http_url.spec()));
RedirectNotificationObserver load_observer2(
NOTIFICATION_LOAD_STOP,
Source<NavigationController>(
&shell()->web_contents()->GetController()));
EXPECT_TRUE(NavigateIframeToURL(shell(),
client_redirect_http_url, "test"));
// Same-site Client-Redirect Page should be loaded successfully.
EXPECT_EQ(observer.navigation_url(), client_redirect_http_url);
EXPECT_TRUE(observer.navigation_succeeded());
// Redirecting to Same-site Page should be loaded successfully.
load_observer2.Wait();
EXPECT_EQ(observer.navigation_url(), http_url);
EXPECT_TRUE(observer.navigation_succeeded());
}
}
// TODO(nasko): Disable this test until out-of-process iframes is ready and the
// security checks are back in place.
IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest,
DISABLED_CrossSiteIframeRedirectTwice) {
ASSERT_TRUE(test_server()->Start());
net::SpawnedTestServer https_server(
net::SpawnedTestServer::TYPE_HTTPS,
net::SpawnedTestServer::kLocalhost,
base::FilePath(FILE_PATH_LITERAL("content/test/data")));
ASSERT_TRUE(https_server.Start());
GURL main_url(test_server()->GetURL("files/site_per_process_main.html"));
GURL http_url(test_server()->GetURL("files/title1.html"));
GURL https_url(https_server.GetURL("files/title1.html"));
NavigateToURL(shell(), main_url);
SitePerProcessWebContentsObserver observer(shell()->web_contents());
{
// Load client-redirect page pointing to a cross-site client-redirect page,
// which eventually redirects back to same-site page.
GURL client_redirect_https_url(https_server.GetURL(
"client-redirect?" + http_url.spec()));
GURL client_redirect_http_url(test_server()->GetURL(
"client-redirect?" + client_redirect_https_url.spec()));
// We should wait until second client redirect get cancelled.
RedirectNotificationObserver load_observer2(
NOTIFICATION_LOAD_STOP,
Source<NavigationController>(
&shell()->web_contents()->GetController()));
EXPECT_TRUE(NavigateIframeToURL(shell(), client_redirect_http_url, "test"));
// DidFailProvisionalLoad when navigating to client_redirect_https_url.
load_observer2.Wait();
EXPECT_EQ(observer.navigation_url(), client_redirect_https_url);
EXPECT_FALSE(observer.navigation_succeeded());
}
{
// Load server-redirect page pointing to a cross-site server-redirect page,
// which eventually redirect back to same-site page.
GURL server_redirect_https_url(https_server.GetURL(
"server-redirect?" + http_url.spec()));
GURL server_redirect_http_url(test_server()->GetURL(
"server-redirect?" + server_redirect_https_url.spec()));
EXPECT_TRUE(NavigateIframeToURL(shell(),
server_redirect_http_url, "test"));
EXPECT_EQ(observer.navigation_url(), http_url);
EXPECT_TRUE(observer.navigation_succeeded());
}
{
// Load server-redirect page pointing to a cross-site server-redirect page,
// which eventually redirects back to cross-site page.
GURL server_redirect_https_url(https_server.GetURL(
"server-redirect?" + https_url.spec()));
GURL server_redirect_http_url(test_server()->GetURL(
"server-redirect?" + server_redirect_https_url.spec()));
EXPECT_TRUE(NavigateIframeToURL(shell(), server_redirect_http_url, "test"));
// DidFailProvisionalLoad when navigating to https_url.
EXPECT_EQ(observer.navigation_url(), https_url);
EXPECT_FALSE(observer.navigation_succeeded());
}
{
// Load server-redirect page pointing to a cross-site client-redirect page,
// which eventually redirects back to same-site page.
GURL client_redirect_http_url(https_server.GetURL(
"client-redirect?" + http_url.spec()));
GURL server_redirect_http_url(test_server()->GetURL(
"server-redirect?" + client_redirect_http_url.spec()));
EXPECT_TRUE(NavigateIframeToURL(shell(), server_redirect_http_url, "test"));
// DidFailProvisionalLoad when navigating to client_redirect_http_url.
EXPECT_EQ(observer.navigation_url(), client_redirect_http_url);
EXPECT_FALSE(observer.navigation_succeeded());
}
}
}
| {'content_hash': 'f45e6024afff69839a917c3593addcad', 'timestamp': '', 'source': 'github', 'line_count': 383, 'max_line_length': 80, 'avg_line_length': 36.112271540469976, 'alnum_prop': 0.6830308726773191, 'repo_name': 'mogoweb/chromium-crosswalk', 'id': 'e37ac97cce8c36d84da18942b1816e0b5ff3fc48', 'size': '14698', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'content/browser/site_per_process_browsertest.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ASP', 'bytes': '853'}, {'name': 'AppleScript', 'bytes': '6973'}, {'name': 'Arduino', 'bytes': '464'}, {'name': 'Assembly', 'bytes': '54831'}, {'name': 'Awk', 'bytes': '8660'}, {'name': 'C', 'bytes': '40940503'}, {'name': 'C#', 'bytes': '1132'}, {'name': 'C++', 'bytes': '182703853'}, {'name': 'CSS', 'bytes': '799795'}, {'name': 'DOT', 'bytes': '1873'}, {'name': 'Java', 'bytes': '4807735'}, {'name': 'JavaScript', 'bytes': '20714038'}, {'name': 'Mercury', 'bytes': '10299'}, {'name': 'Objective-C', 'bytes': '985558'}, {'name': 'Objective-C++', 'bytes': '6205987'}, {'name': 'PHP', 'bytes': '97817'}, {'name': 'Perl', 'bytes': '1213389'}, {'name': 'Python', 'bytes': '9735121'}, {'name': 'Rebol', 'bytes': '262'}, {'name': 'Shell', 'bytes': '1305641'}, {'name': 'Tcl', 'bytes': '277091'}, {'name': 'TypeScript', 'bytes': '1560024'}, {'name': 'XSLT', 'bytes': '13493'}, {'name': 'nesC', 'bytes': '14650'}]} |
package com.kambeeng.cordova.FileBufferedReader;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import android.os.Environment;
import org.apache.cordova.LOG;
public class FileBufferedReader extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("read")) {
try{
final JSONObject options = args.getJSONObject(0);
final CallbackContext cb = callbackContext;
cordova.getThreadPool().execute(new Runnable() {
public void run() {
read(options, cb);
}
});
}catch(JSONException ex){}
return true;
}
return false;
}
private void read(JSONObject options, CallbackContext callbackContext) {
File path = null;
File pathFile = null;
String contentString = null;
try {
if(options.getBoolean("publicDirectory")) {
} else {
if("EXTERNAL".equals(options.getString("environment"))) {
path = Environment.getExternalStorageDirectory();
pathFile = new File(path, options.getString("src"));
} else if("INTERNAL".equals(options.getString("environment"))) {
} else {
}
}
contentString = convertStreamToString(new FileInputStream(pathFile));
if("json".equals(options.getString("readAs"))) {
JSONObject jsonResult = new JSONObject(contentString);
callbackContext.success(jsonResult);
}
} catch(JSONException ex){
try {
JSONArray jsonResult = new JSONArray(contentString);
callbackContext.success(jsonResult);
} catch(JSONException exerr){}
} catch (FileNotFoundException e){
// LOG.d("::FileBufferedReader::", "file not found");
} catch(Exception e){
// LOG.d("::FileBufferedReader::", "Exception");
} finally {}
}
private static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
return sb.toString();
}
} | {'content_hash': 'b1bafcc6b45c60a893f15448a2e006fd', 'timestamp': '', 'source': 'github', 'line_count': 92, 'max_line_length': 113, 'avg_line_length': 31.565217391304348, 'alnum_prop': 0.6015840220385675, 'repo_name': 'faridlab/cordova-plugin-fileBufferedReader', 'id': 'f06857c501a8f60294ccaf391597c6c8fd29b1ad', 'size': '2904', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/android/FileBufferedReader.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '2904'}, {'name': 'JavaScript', 'bytes': '1656'}]} |
<!DOCTYPE animal [
<!ELEMENT animal ANY>
<?῭ an illegal char #x1fed
in PITarget ?>
]>
<animal/>
| {'content_hash': '1d7bf684cbe0909760c9e6ca182aac26', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 26, 'avg_line_length': 17.166666666666668, 'alnum_prop': 0.6116504854368932, 'repo_name': 'FranklinChen/hugs98-plus-Sep2006', 'id': '7bf497a69183552a7bbcb0c3467b1b4d683c39d9', 'size': '105', 'binary': False, 'copies': '16', 'ref': 'refs/heads/master', 'path': 'packages/HaXml/tests/xml-conformance/ibm/not-wf/P85/ibm85n189.xml', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'AMPL', 'bytes': '4371'}, {'name': 'Batchfile', 'bytes': '7319'}, {'name': 'C', 'bytes': '2196193'}, {'name': 'C#', 'bytes': '35267'}, {'name': 'C++', 'bytes': '276328'}, {'name': 'CSS', 'bytes': '8051'}, {'name': 'GDB', 'bytes': '67'}, {'name': 'Groff', 'bytes': '7777'}, {'name': 'HTML', 'bytes': '2987334'}, {'name': 'Haskell', 'bytes': '7363914'}, {'name': 'LilyPond', 'bytes': '22441'}, {'name': 'M', 'bytes': '1151'}, {'name': 'M4', 'bytes': '81267'}, {'name': 'Makefile', 'bytes': '235831'}, {'name': 'NSIS', 'bytes': '8221'}, {'name': 'Objective-C', 'bytes': '1427'}, {'name': 'R', 'bytes': '40181'}, {'name': 'Shell', 'bytes': '111759'}, {'name': 'TeX', 'bytes': '148785'}, {'name': 'Web Ontology Language', 'bytes': '3511'}, {'name': 'XQuery', 'bytes': '19265'}, {'name': 'XSLT', 'bytes': '26542'}, {'name': 'Yacc', 'bytes': '41267'}]} |
package salama.approvalflow.junittest;
import java.util.ArrayList;
import java.util.List;
import MetoXML.XmlDeserializer;
import MetoXML.XmlSerializer;
import com.salama.approvalflow.meta.designer.ApprovalActivity;
import com.salama.approvalflow.meta.designer.ApprovalActivityNames;
import com.salama.approvalflow.meta.designer.ApprovalFlow;
import com.salama.approvalflow.meta.designer.ApprovalState;
import com.salama.workflow.core.meta.RelevantData;
import com.salama.workflow.core.meta.Role;
import com.salama.workflow.core.meta.State;
import com.salama.workflow.core.meta.StateDataFieldUISetting;
import com.salama.workflow.core.meta.StateDataUISetting;
import com.salama.workflow.core.meta.UISetting;
public class ApprovalMetaTest {
public static void main(String[] args) {
try {
outputApprovalFlow();
} catch(Exception e) {
error("main()", e);
}
}
private static void outputApprovalFlow() throws Exception {
ApprovalFlow flow = createTestApprovalMeta();
XmlSerializer xmlSer = new XmlSerializer();
xmlSer.Serialize("ApprovalFlow01.xml", flow, ApprovalFlow.class, XmlDeserializer.DefaultCharset, true);
}
private static ApprovalFlow createTestApprovalMeta() {
List<Role> roleList = new ArrayList<Role>();
Role role1 = new Role();
role1.setName("role1");
role1.setDescription("审批1");
Role role2 = new Role();
role2.setName("role2");
role2.setDescription("审批2");
Role role3 = new Role();
role3.setName("role3");
role3.setDescription("审批3");
roleList.add(role1);
roleList.add(role2);
roleList.add(role3);
ApprovalFlow flow = new ApprovalFlow();
flow.setAllRoles(roleList);
ApprovalActivity approveActivity = new ApprovalActivity();
approveActivity.setName(ApprovalActivityNames.Approve);
approveActivity.setToState("state2");
ApprovalActivity disapproveActivity = new ApprovalActivity();
disapproveActivity.setName(ApprovalActivityNames.Disapprove);
disapproveActivity.setToState("state1");
RelevantData stateData = new RelevantData();
stateData.setDataClass("xxxx.xxx.Data");
StateDataUISetting dataUISetting = new StateDataUISetting();
StateDataFieldUISetting fieldUISetting = new StateDataFieldUISetting();
fieldUISetting.setFieldNameExpression("feild1");
UISetting uiSetting = new UISetting();
uiSetting.setName("readOnly");
uiSetting.setValue("true");
fieldUISetting.getUiSettings().add(uiSetting);
dataUISetting.getFieldUISettings().add(fieldUISetting);
ApprovalState state1 = new ApprovalState();
state1.setName("state1");
state1.setStateData(stateData);
state1.setStateDataUISetting(dataUISetting);
state1.setStateType(State.StateType_Normal);
state1.getActivityList().add(approveActivity);
state1.getActivityList().add(disapproveActivity);
state1.getAccessibleRoles().add(role1);
ApprovalState state2 = new ApprovalState();
state2.setName("state2");
state2.setStateData(stateData);
state2.setStateDataUISetting(dataUISetting);
state2.setStateType(State.StateType_Completed);
state2.getAccessibleRoles().add(role2);
state2.getAccessibleRoles().add(role3);
flow.getAllStates().add(state1);
flow.getAllStates().add(state2);
return flow;
}
protected static void error(String msg, Throwable e) {
System.out.println(msg);
e.printStackTrace();
}
}
| {'content_hash': '4ee294fb87bec763e6c82f645042056d', 'timestamp': '', 'source': 'github', 'line_count': 112, 'max_line_length': 105, 'avg_line_length': 30.875, 'alnum_prop': 0.7400231347599768, 'repo_name': 'SalamaSoft/workflow', 'id': '03b12afccaeedabb52ea01a3b522fc59c9a5ed06', 'size': '3470', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/SalamaApprovalFlow/src/salama/approvalflow/junittest/ApprovalMetaTest.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '174253'}]} |
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { DeleteModule } from './DeleteModule';
export type WriteSetChange_DeleteModule = ({
type: string;
} & DeleteModule);
| {'content_hash': 'd20fa1912486a8e5f7cb1fdc452219a2', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 51, 'avg_line_length': 20.6, 'alnum_prop': 0.6796116504854369, 'repo_name': 'aptos-labs/aptos-core', 'id': '3c4252969f572066cb2ece9cf15379bcfd22b611', 'size': '206', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'ecosystem/typescript/sdk/src/generated/models/WriteSetChange_DeleteModule.ts', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Boogie', 'bytes': '62'}, {'name': 'CSS', 'bytes': '31355'}, {'name': 'Dockerfile', 'bytes': '10300'}, {'name': 'Go', 'bytes': '1308'}, {'name': 'HCL', 'bytes': '190756'}, {'name': 'HTML', 'bytes': '2168'}, {'name': 'JavaScript', 'bytes': '48386'}, {'name': 'Makefile', 'bytes': '2632'}, {'name': 'Move', 'bytes': '1354163'}, {'name': 'Mustache', 'bytes': '21042'}, {'name': 'PLpgSQL', 'bytes': '1145'}, {'name': 'PowerShell', 'bytes': '842'}, {'name': 'Python', 'bytes': '240445'}, {'name': 'Rust', 'bytes': '10592521'}, {'name': 'Shell', 'bytes': '69203'}, {'name': 'Smarty', 'bytes': '1224'}, {'name': 'TypeScript', 'bytes': '513895'}]} |
<?php
namespace { require_once __DIR__.'/autoload.php'; }
namespace Symfony\Component\HttpKernel
{
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
use Symfony\Component\Config\Loader\LoaderInterface;
interface KernelInterface extends HttpKernelInterface, \Serializable
{
function registerRootDir();
function registerBundles();
function registerContainerConfiguration(LoaderInterface $loader);
function boot();
function shutdown();
function getBundles();
function isClassInActiveBundle($class);
function getBundle($name, $first = true);
function locateResource($name, $dir = null, $first = true);
function getName();
function getEnvironment();
function isDebug();
function getRootDir();
function getContainer();
function getStartTime();
function getCacheDir();
function getLogDir();
}
}
namespace Symfony\Component\HttpKernel
{
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
use Symfony\Component\DependencyInjection\Loader\ClosureLoader;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
use Symfony\Component\HttpKernel\Config\FileLocator;
use Symfony\Component\Config\Loader\LoaderResolver;
use Symfony\Component\Config\Loader\DelegatingLoader;
use Symfony\Component\Config\ConfigCache;
abstract class Kernel implements KernelInterface
{
protected $bundles;
protected $bundleMap;
protected $container;
protected $rootDir;
protected $environment;
protected $debug;
protected $booted;
protected $name;
protected $startTime;
const VERSION = '2.0.0-DEV';
public function __construct($environment, $debug)
{
$this->environment = $environment;
$this->debug = (Boolean) $debug;
$this->booted = false;
$this->rootDir = realpath($this->registerRootDir());
$this->name = preg_replace('/[^a-zA-Z0-9_]+/', '', basename($this->rootDir));
if ($this->debug) {
ini_set('display_errors', 1);
error_reporting(-1);
$this->startTime = microtime(true);
} else {
ini_set('display_errors', 0);
}
}
public function __clone()
{
if ($this->debug) {
$this->startTime = microtime(true);
}
$this->booted = false;
$this->container = null;
}
public function boot()
{
if (true === $this->booted) {
return;
}
$this->initializeBundles();
$this->initializeContainer();
foreach ($this->getBundles() as $bundle) {
$bundle->setContainer($this->container);
$bundle->boot();
}
$this->booted = true;
}
public function shutdown()
{
$this->booted = false;
foreach ($this->getBundles() as $bundle) {
$bundle->shutdown();
$bundle->setContainer(null);
}
$this->container = null;
}
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
{
if (false === $this->booted) {
$this->boot();
}
return $this->getHttpKernel()->handle($request, $type, $catch);
}
protected function getHttpKernel()
{
return $this->container->get('http_kernel');
}
public function getBundles()
{
return $this->bundles;
}
public function isClassInActiveBundle($class)
{
foreach ($this->getBundles() as $bundle) {
if (0 === strpos($class, $bundle->getNamespace())) {
return true;
}
}
return false;
}
public function getBundle($name, $first = true)
{
if (!isset($this->bundleMap[$name])) {
throw new \InvalidArgumentException(sprintf('Bundle "%s" does not exist or it is not enabled. Maybe you forgot to add it in the registerBundles() function of your %s.php file?', $name, get_class($this)));
}
if (true === $first) {
return $this->bundleMap[$name][0];
} elseif (false === $first) {
return $this->bundleMap[$name];
}
}
public function locateResource($name, $dir = null, $first = true)
{
if ('@' !== $name[0]) {
throw new \InvalidArgumentException(sprintf('A resource name must start with @ ("%s" given).', $name));
}
if (false !== strpos($name, '..')) {
throw new \RuntimeException(sprintf('File name "%s" contains invalid characters (..).', $name));
}
$name = substr($name, 1);
list($bundle, $path) = explode('/', $name, 2);
$isResource = 0 === strpos($path, 'Resources');
$files = array();
if (true === $isResource && null !== $dir && file_exists($file = $dir.'/'.$bundle.'/'.substr($path, 10))) {
if ($first) {
return $file;
}
$files[] = $file;
}
foreach ($this->getBundle($bundle, false) as $bundle) {
if (file_exists($file = $bundle->getPath().'/'.$path)) {
if ($first) {
return $file;
}
$files[] = $file;
}
}
if ($files) {
return $files;
}
throw new \InvalidArgumentException(sprintf('Unable to find file "@%s".', $name));
}
public function getName()
{
return $this->name;
}
public function getEnvironment()
{
return $this->environment;
}
public function isDebug()
{
return $this->debug;
}
public function getRootDir()
{
return $this->rootDir;
}
public function getContainer()
{
return $this->container;
}
public function getStartTime()
{
return $this->debug ? $this->startTime : -INF;
}
public function getCacheDir()
{
return $this->rootDir.'/cache/'.$this->environment;
}
public function getLogDir()
{
return $this->rootDir.'/logs';
}
protected function initializeBundles()
{
$this->bundles = array();
$topMostBundles = array();
$directChildren = array();
foreach ($this->registerBundles() as $bundle) {
$name = $bundle->getName();
if (isset($this->bundles[$name])) {
throw new \LogicException(sprintf('Trying to register two bundles with the same name "%s"', $name));
}
$this->bundles[$name] = $bundle;
if ($parentName = $bundle->getParent()) {
if (isset($directChildren[$parentName])) {
throw new \LogicException(sprintf('Bundle "%s" is directly extended by two bundles "%s" and "%s".', $parentName, $name, $directChildren[$parentName]));
}
$directChildren[$parentName] = $name;
} else {
$topMostBundles[$name] = $bundle;
}
}
if (count($diff = array_values(array_diff(array_keys($directChildren), array_keys($this->bundles))))) {
throw new \LogicException(sprintf('Bundle "%s" extends bundle "%s", which is not registered.', $directChildren[$diff[0]], $diff[0]));
}
$this->bundleMap = array();
foreach ($topMostBundles as $name => $bundle) {
$bundleMap = array($bundle);
$hierarchy = array($name);
while (isset($directChildren[$name])) {
$name = $directChildren[$name];
array_unshift($bundleMap, $this->bundles[$name]);
$hierarchy[] = $name;
}
foreach ($hierarchy as $bundle) {
$this->bundleMap[$bundle] = $bundleMap;
array_pop($bundleMap);
}
}
}
protected function initializeContainer()
{
$class = $this->name.ucfirst($this->environment).($this->debug ? 'Debug' : '').'ProjectContainer';
$cache = new ConfigCache($this->getCacheDir(), $class, $this->debug);
$fresh = false;
if (!$cache->isFresh()) {
$container = $this->buildContainer();
$this->dumpContainer($cache, $container, $class);
$fresh = true;
}
require_once $cache;
$this->container = new $class();
$this->container->set('kernel', $this);
if ($fresh && 'cli' !== php_sapi_name()) {
$this->container->get('cache_warmer')->warmUp($this->container->getParameter('kernel.cache_dir'));
}
}
protected function getKernelParameters()
{
$bundles = array();
foreach ($this->bundles as $name => $bundle) {
$bundles[$name] = get_class($bundle);
}
return array_merge(
array(
'kernel.root_dir' => $this->rootDir,
'kernel.environment' => $this->environment,
'kernel.debug' => $this->debug,
'kernel.name' => $this->name,
'kernel.cache_dir' => $this->getCacheDir(),
'kernel.logs_dir' => $this->getLogDir(),
'kernel.bundles' => $bundles,
'kernel.charset' => 'UTF-8',
),
$this->getEnvParameters()
);
}
protected function getEnvParameters()
{
$parameters = array();
foreach ($_SERVER as $key => $value) {
if ('SYMFONY__' === substr($key, 0, 9)) {
$parameters[strtolower(str_replace('__', '.', substr($key, 9)))] = $value;
}
}
return $parameters;
}
protected function buildContainer()
{
$parameterBag = new ParameterBag($this->getKernelParameters());
$container = new ContainerBuilder($parameterBag);
foreach ($this->bundles as $bundle) {
$bundle->build($container);
if ($this->debug) {
$container->addObjectResource($bundle);
}
}
$container->addObjectResource($this);
if (null !== $cont = $this->registerContainerConfiguration($this->getContainerLoader($container))) {
$container->merge($cont);
}
$container->compile();
return $container;
}
protected function dumpContainer(ConfigCache $cache, ContainerBuilder $container, $class)
{
foreach (array('cache', 'logs') as $name) {
$dir = $container->getParameter(sprintf('kernel.%s_dir', $name));
if (!is_dir($dir)) {
if (false === @mkdir($dir, 0777, true)) {
die(sprintf("Unable to create the %s directory (%s)\n", $name, dirname($dir)));
}
} elseif (!is_writable($dir)) {
die(sprintf("Unable to write in the %s directory (%s)\n", $name, $dir));
}
}
$dumper = new PhpDumper($container);
$content = $dumper->dump(array('class' => $class));
if (!$this->debug) {
$content = self::stripComments($content);
}
$cache->write($content, $container->getResources());
}
protected function getContainerLoader(ContainerInterface $container)
{
$resolver = new LoaderResolver(array(
new XmlFileLoader($container, new FileLocator($this)),
new YamlFileLoader($container, new FileLocator($this)),
new IniFileLoader($container, new FileLocator($this)),
new PhpFileLoader($container, new FileLocator($this)),
new ClosureLoader($container, new FileLocator($this)),
));
return new DelegatingLoader($resolver);
}
static public function stripComments($source)
{
if (!function_exists('token_get_all')) {
return $source;
}
$output = '';
foreach (token_get_all($source) as $token) {
if (is_string($token)) {
$output .= $token;
} elseif (!in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
$output .= $token[1];
}
}
$output = preg_replace(array('/\s+$/Sm', '/\n+/S'), "\n", $output);
return $output;
}
public function serialize()
{
return serialize(array($this->environment, $this->debug));
}
public function unserialize($data)
{
list($environment, $debug) = unserialize($data);
$this->__construct($environment, $debug);
}
}
}
namespace Symfony\Component\HttpKernel
{
use Symfony\Component\HttpFoundation\Request;
interface HttpKernelInterface
{
const MASTER_REQUEST = 1;
const SUB_REQUEST = 2;
function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true);
}
}
namespace Symfony\Component\HttpKernel\HttpCache
{
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class HttpCache implements HttpKernelInterface
{
protected $kernel;
protected $traces;
protected $store;
protected $request;
protected $esi;
protected $esiCacheStrategy;
public function __construct(HttpKernelInterface $kernel, StoreInterface $store, Esi $esi = null, array $options = array())
{
$this->store = $store;
$this->kernel = $kernel;
register_shutdown_function(array($this->store, 'cleanup'));
$this->options = array_merge(array(
'debug' => false,
'default_ttl' => 0,
'private_headers' => array('Authorization', 'Cookie'),
'allow_reload' => false,
'allow_revalidate' => false,
'stale_while_revalidate' => 2,
'stale_if_error' => 60,
), $options);
$this->esi = $esi;
}
public function getTraces()
{
return $this->traces;
}
public function getLog()
{
$log = array();
foreach ($this->traces as $request => $traces) {
$log[] = sprintf('%s: %s', $request, implode(', ', $traces));
}
return implode('; ', $log);
}
public function getRequest()
{
return $this->request;
}
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
{
if (HttpKernelInterface::MASTER_REQUEST === $type) {
$this->traces = array();
$this->request = $request;
if (null !== $this->esi) {
$this->esiCacheStrategy = $this->esi->createCacheStrategy();
}
}
$path = $request->getPathInfo();
if ($qs = $request->getQueryString()) {
$path .= '?'.$qs;
}
$this->traces[$request->getMethod().' '.$path] = array();
if (!$request->isMethodSafe()) {
$response = $this->invalidate($request, $catch);
} elseif ($request->headers->has('expect')) {
$response = $this->pass($request, $catch);
} else {
$response = $this->lookup($request, $catch);
}
$response->isNotModified($request);
$this->restoreResponseBody($request, $response);
if (HttpKernelInterface::MASTER_REQUEST === $type && $this->options['debug']) {
$response->headers->set('X-Symfony-Cache', $this->getLog());
}
if (null !== $this->esi) {
$this->esiCacheStrategy->add($response);
if (HttpKernelInterface::MASTER_REQUEST === $type) {
$this->esiCacheStrategy->update($response);
}
}
return $response;
}
protected function pass(Request $request, $catch = false)
{
$this->record($request, 'pass');
return $this->forward($request, $catch);
}
protected function invalidate(Request $request, $catch = false)
{
$response = $this->pass($request, $catch);
if ($response->isSuccessful() || $response->isRedirect()) {
try {
$this->store->invalidate($request, $catch);
$this->record($request, 'invalidate');
} catch (\Exception $e) {
$this->record($request, 'invalidate-failed');
if ($this->options['debug']) {
throw $e;
}
}
}
return $response;
}
protected function lookup(Request $request, $catch = false)
{
if ($this->options['allow_reload'] && $request->isNoCache()) {
$this->record($request, 'reload');
return $this->fetch($request);
}
try {
$entry = $this->store->lookup($request);
} catch (\Exception $e) {
$this->record($request, 'lookup-failed');
if ($this->options['debug']) {
throw $e;
}
return $this->pass($request, $catch);
}
if (null === $entry) {
$this->record($request, 'miss');
return $this->fetch($request, $catch);
}
if (!$this->isFreshEnough($request, $entry)) {
$this->record($request, 'stale');
return $this->validate($request, $entry);
}
$this->record($request, 'fresh');
$entry->headers->set('Age', $entry->getAge());
return $entry;
}
protected function validate(Request $request, Response $entry)
{
$subRequest = clone $request;
$subRequest->setMethod('get');
$subRequest->headers->set('if_modified_since', $entry->headers->get('Last-Modified'));
$cachedEtags = array($entry->getEtag());
$requestEtags = $request->getEtags();
$etags = array_unique(array_merge($cachedEtags, $requestEtags));
$subRequest->headers->set('if_none_match', $etags ? implode(', ', $etags) : '');
$response = $this->forward($subRequest, false, $entry);
if (304 == $response->getStatusCode()) {
$this->record($request, 'valid');
$etag = $response->getEtag();
if ($etag && in_array($etag, $requestEtags) && !in_array($etag, $cachedEtags)) {
return $response;
}
$entry = clone $entry;
$entry->headers->remove('Date');
foreach (array('Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified') as $name) {
if ($response->headers->has($name)) {
$entry->headers->set($name, $response->headers->get($name));
}
}
$response = $entry;
} else {
$this->record($request, 'invalid');
}
if ($response->isCacheable()) {
$this->store($request, $response);
}
return $response;
}
protected function fetch(Request $request, $catch = false)
{
$subRequest = clone $request;
$subRequest->setMethod('get');
$subRequest->headers->remove('if_modified_since');
$subRequest->headers->remove('if_none_match');
$response = $this->forward($subRequest, $catch);
if ($this->isPrivateRequest($request) && !$response->headers->hasCacheControlDirective('public')) {
$response->setPrivate(true);
} elseif ($this->options['default_ttl'] > 0 && null === $response->getTtl() && !$response->headers->getCacheControlDirective('must-revalidate')) {
$response->setTtl($this->options['default_ttl']);
}
if ($response->isCacheable()) {
$this->store($request, $response);
}
return $response;
}
protected function forward(Request $request, $catch = false, Response $entry = null)
{
if ($this->esi) {
$this->esi->addSurrogateEsiCapability($request);
}
$response = $this->kernel->handle($request, HttpKernelInterface::MASTER_REQUEST, $catch);
if (null !== $entry && in_array($response->getStatusCode(), array(500, 502, 503, 504))) {
if (null === $age = $entry->headers->getCacheControlDirective('stale-if-error')) {
$age = $this->options['stale_if_error'];
}
if (abs($entry->getTtl()) < $age) {
$this->record($request, 'stale-if-error');
return $entry;
}
}
$this->processResponseBody($request, $response);
return $response;
}
protected function isFreshEnough(Request $request, Response $entry)
{
if (!$entry->isFresh()) {
return $this->lock($request, $entry);
}
if ($this->options['allow_revalidate'] && null !== $maxAge = $request->headers->getCacheControlDirective('max-age')) {
return $maxAge > 0 && $maxAge >= $entry->getAge();
}
return true;
}
protected function lock(Request $request, Response $entry)
{
$lock = $this->store->lock($request, $entry);
if (true !== $lock) {
if (null === $age = $entry->headers->getCacheControlDirective('stale-while-revalidate')) {
$age = $this->options['stale_while_revalidate'];
}
if (abs($entry->getTtl()) < $age) {
$this->record($request, 'stale-while-revalidate');
return true;
}
$wait = 0;
while (file_exists($lock) && $wait < 5000000) {
usleep($wait += 50000);
}
if ($wait < 2000000) {
$new = $this->lookup($request);
$entry->headers = $new->headers;
$entry->setContent($new->getContent());
$entry->setStatusCode($new->getStatusCode());
$entry->setProtocolVersion($new->getProtocolVersion());
$entry->setCookies($new->getCookies());
} else {
$entry->setStatusCode(503);
$entry->setContent('503 Service Unavailable');
$entry->headers->set('Retry-After', 10);
}
return true;
}
return false;
}
protected function store(Request $request, Response $response)
{
try {
$this->store->write($request, $response);
$this->record($request, 'store');
$response->headers->set('Age', $response->getAge());
} catch (\Exception $e) {
$this->record($request, 'store-failed');
if ($this->options['debug']) {
throw $e;
}
}
$this->store->unlock($request);
}
protected function restoreResponseBody(Request $request, Response $response)
{
if ('head' === strtolower($request->getMethod())) {
$response->setContent('');
$response->headers->remove('X-Body-Eval');
$response->headers->remove('X-Body-File');
return;
}
if ($response->headers->has('X-Body-Eval')) {
ob_start();
if ($response->headers->has('X-Body-File')) {
include $response->headers->get('X-Body-File');
} else {
eval('; ?>'.$response->getContent().'<?php ;');
}
$response->setContent(ob_get_clean());
$response->headers->remove('X-Body-Eval');
} elseif ($response->headers->has('X-Body-File')) {
$response->setContent(file_get_contents($response->headers->get('X-Body-File')));
} else {
return;
}
$response->headers->remove('X-Body-File');
if (!$response->headers->has('Transfer-Encoding')) {
$response->headers->set('Content-Length', strlen($response->getContent()));
}
}
protected function processResponseBody(Request $request, Response $response)
{
if (null !== $this->esi && $this->esi->needsEsiParsing($response)) {
$this->esi->process($request, $response);
}
}
protected function isPrivateRequest(Request $request)
{
foreach ($this->options['private_headers'] as $key) {
$key = strtolower(str_replace('HTTP_', '', $key));
if ('cookie' === $key) {
if (count($request->cookies->all())) {
return true;
}
} elseif ($request->headers->has($key)) {
return true;
}
}
return false;
}
protected function record(Request $request, $event)
{
$path = $request->getPathInfo();
if ($qs = $request->getQueryString()) {
$path .= '?'.$qs;
}
$this->traces[$request->getMethod().' '.$path][] = $event;
}
}
}
namespace Symfony\Component\HttpKernel\HttpCache
{
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\HeaderBag;
interface StoreInterface
{
function lookup(Request $request);
function write(Request $request, Response $response);
function invalidate(Request $request);
function lock(Request $request);
function unlock(Request $request);
function purge($url);
function cleanup();
}
}
namespace Symfony\Component\HttpKernel\HttpCache
{
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\HeaderBag;
class Store implements StoreInterface
{
protected $root;
protected $keyCache;
protected $locks;
public function __construct($root)
{
$this->root = $root;
if (!is_dir($this->root)) {
mkdir($this->root, 0777, true);
}
$this->keyCache = new \SplObjectStorage();
$this->locks = array();
}
public function cleanup()
{
foreach ($this->locks as $lock) {
@unlink($lock);
}
$error = error_get_last();
if (1 === $error['type'] && false === headers_sent()) {
header('HTTP/1.0 503 Service Unavailable');
header('Retry-After: 10');
echo '503 Service Unavailable';
}
}
public function lock(Request $request)
{
if (false !== $lock = @fopen($path = $this->getPath($this->getCacheKey($request).'.lck'), 'x')) {
fclose($lock);
$this->locks[] = $path;
return true;
}
return $path;
}
public function unlock(Request $request)
{
return @unlink($this->getPath($this->getCacheKey($request).'.lck'));
}
public function lookup(Request $request)
{
$key = $this->getCacheKey($request);
if (!$entries = $this->getMetadata($key)) {
return null;
}
$match = null;
foreach ($entries as $entry) {
if ($this->requestsMatch(isset($entry[1]['vary']) ? $entry[1]['vary'][0] : '', $request->headers->all(), $entry[0])) {
$match = $entry;
break;
}
}
if (null === $match) {
return null;
}
list($req, $headers) = $match;
if (file_exists($body = $this->getPath($headers['x-content-digest'][0]))) {
return $this->restoreResponse($headers, $body);
}
return null;
}
public function write(Request $request, Response $response)
{
$key = $this->getCacheKey($request);
$storedEnv = $this->persistRequest($request);
if (!$response->headers->has('X-Content-Digest')) {
$digest = 'en'.sha1($response->getContent());
if (false === $this->save($digest, $response->getContent())) {
throw new \RuntimeException('Unable to store the entity.');
}
$response->headers->set('X-Content-Digest', $digest);
if (!$response->headers->has('Transfer-Encoding')) {
$response->headers->set('Content-Length', strlen($response->getContent()));
}
}
$entries = array();
$vary = $response->headers->get('vary');
foreach ($this->getMetadata($key) as $entry) {
if (!isset($entry[1]['vary'])) {
$entry[1]['vary'] = array('');
}
if ($vary != $entry[1]['vary'][0] || !$this->requestsMatch($vary, $entry[0], $storedEnv)) {
$entries[] = $entry;
}
}
$headers = $this->persistResponse($response);
unset($headers['age']);
array_unshift($entries, array($storedEnv, $headers));
if (false === $this->save($key, serialize($entries))) {
throw new \RuntimeException('Unable to store the metadata.');
}
return $key;
}
public function invalidate(Request $request)
{
$modified = false;
$key = $this->getCacheKey($request);
$entries = array();
foreach ($this->getMetadata($key) as $entry) {
$response = $this->restoreResponse($entry[1]);
if ($response->isFresh()) {
$response->expire();
$modified = true;
$entries[] = array($entry[0], $this->persistResponse($response));
} else {
$entries[] = $entry;
}
}
if ($modified) {
if (false === $this->save($key, serialize($entries))) {
throw new \RuntimeException('Unable to store the metadata.');
}
}
foreach (array('Location', 'Content-Location') as $header) {
if ($uri = $request->headers->get($header)) {
$subRequest = Request::create($uri, 'get', array(), array(), array(), $request->server->all());
$this->invalidate($subRequest);
}
}
}
protected function requestsMatch($vary, $env1, $env2)
{
if (empty($vary)) {
return true;
}
foreach (preg_split('/[\s,]+/', $vary) as $header) {
$key = strtr(strtolower($header), '_', '-');
$v1 = isset($env1[$key]) ? $env1[$key] : null;
$v2 = isset($env2[$key]) ? $env2[$key] : null;
if ($v1 !== $v2) {
return false;
}
}
return true;
}
protected function getMetadata($key)
{
if (false === $entries = $this->load($key)) {
return array();
}
return unserialize($entries);
}
public function purge($url)
{
if (file_exists($path = $this->getPath($this->getCacheKey(Request::create($url))))) {
unlink($path);
return true;
}
return false;
}
protected function load($key)
{
$path = $this->getPath($key);
return file_exists($path) ? file_get_contents($path) : false;
}
protected function save($key, $data)
{
$path = $this->getPath($key);
if (!is_dir(dirname($path)) && false === @mkdir(dirname($path), 0777, true)) {
return false;
}
$tmpFile = tempnam(dirname($path), basename($path));
if (false === $fp = @fopen($tmpFile, 'wb')) {
return false;
}
@fwrite($fp, $data);
@fclose($fp);
if ($data != file_get_contents($tmpFile)) {
return false;
}
if (false === @rename($tmpFile, $path)) {
return false;
}
chmod($path, 0644);
}
public function getPath($key)
{
return $this->root.DIRECTORY_SEPARATOR.substr($key, 0, 2).DIRECTORY_SEPARATOR.substr($key, 2, 2).DIRECTORY_SEPARATOR.substr($key, 4, 2).DIRECTORY_SEPARATOR.substr($key, 6);
}
protected function getCacheKey(Request $request)
{
if (isset($this->keyCache[$request])) {
return $this->keyCache[$request];
}
return $this->keyCache[$request] = 'md'.sha1($request->getUri());
}
protected function persistRequest(Request $request)
{
return $request->headers->all();
}
protected function persistResponse(Response $response)
{
$headers = $response->headers->all();
$headers['X-Status'] = array($response->getStatusCode());
return $headers;
}
protected function restoreResponse($headers, $body = null)
{
$status = $headers['X-Status'][0];
unset($headers['X-Status']);
if (null !== $body) {
$headers['X-Body-File'] = array($body);
}
return new Response($body, $status, $headers);
}
}
}
namespace Symfony\Component\HttpKernel\HttpCache
{
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class Esi
{
protected $contentTypes;
public function __construct(array $contentTypes = array('text/html', 'text/xml', 'application/xml'))
{
$this->contentTypes = $contentTypes;
}
public function createCacheStrategy()
{
return new EsiResponseCacheStrategy();
}
public function hasSurrogateEsiCapability(Request $request)
{
if (null === $value = $request->headers->get('Surrogate-Capability')) {
return false;
}
return (Boolean) preg_match('#ESI/1.0#', $value);
}
public function addSurrogateEsiCapability(Request $request)
{
$current = $request->headers->get('Surrogate-Capability');
$new = 'symfony2="ESI/1.0"';
$request->headers->set('Surrogate-Capability', $current ? $current.', '.$new : $new);
}
public function addSurrogateControl(Response $response)
{
if (false !== strpos($response->getContent(), '<esi:include')) {
$response->headers->set('Surrogate-Control', 'content="ESI/1.0"');
}
}
public function needsEsiParsing(Response $response)
{
if (!$control = $response->headers->get('Surrogate-Control')) {
return false;
}
return (Boolean) preg_match('#content="[^"]*ESI/1.0[^"]*"#', $control);
}
public function renderIncludeTag($uri, $alt = null, $ignoreErrors = true, $comment = '')
{
$html = sprintf('<esi:include src="%s"%s%s />',
$uri,
$ignoreErrors ? ' onerror="continue"' : '',
$alt ? sprintf(' alt="%s"', $alt) : ''
);
if (!empty($comment)) {
return sprintf("<esi:comment text=\"%s\" />\n%s", $comment, $html);
}
return $html;
}
public function process(Request $request, Response $response)
{
$this->request = $request;
$type = $response->headers->get('Content-Type');
if (empty($type)) {
$type = 'text/html';
}
$parts = explode(';', $type);
if (!in_array($parts[0], $this->contentTypes)) {
return $response;
}
$content = $response->getContent();
$content = preg_replace_callback('#<esi\:include\s+(.*?)\s*/>#', array($this, 'handleEsiIncludeTag'), $content);
$content = preg_replace('#<esi\:comment[^>]*/>#', '', $content);
$content = preg_replace('#<esi\:remove>.*?</esi\:remove>#', '', $content);
$response->setContent($content);
$response->headers->set('X-Body-Eval', 'ESI');
if ($response->headers->has('Surrogate-Control')) {
$value = $response->headers->get('Surrogate-Control');
if ('content="ESI/1.0"' == $value) {
$response->headers->remove('Surrogate-Control');
} elseif (preg_match('#,\s*content="ESI/1.0"#', $value)) {
$response->headers->set('Surrogate-Control', preg_replace('#,\s*content="ESI/1.0"#', '', $value));
} elseif (preg_match('#content="ESI/1.0",\s*#', $value)) {
$response->headers->set('Surrogate-Control', preg_replace('#content="ESI/1.0",\s*#', '', $value));
}
}
}
public function handle(HttpCache $cache, $uri, $alt, $ignoreErrors)
{
$subRequest = Request::create($uri, 'get', array(), $cache->getRequest()->cookies->all(), array(), $cache->getRequest()->server->all());
try {
$response = $cache->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true);
if (!$response->isSuccessful()) {
throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %s).', $subRequest->getUri(), $response->getStatusCode()));
}
return $response->getContent();
} catch (\Exception $e) {
if ($alt) {
return $this->handle($cache, $alt, '', $ignoreErrors);
}
if (!$ignoreErrors) {
throw $e;
}
}
}
protected function handleEsiIncludeTag($attributes)
{
$options = array();
preg_match_all('/(src|onerror|alt)="([^"]*?)"/', $attributes[1], $matches, PREG_SET_ORDER);
foreach ($matches as $set) {
$options[$set[1]] = $set[2];
}
if (!isset($options['src'])) {
throw new \RuntimeException('Unable to process an ESI tag without a "src" attribute.');
}
return sprintf('<?php echo $this->esi->handle($this, \'%s\', \'%s\', %s) ?>'."\n",
$options['src'],
isset($options['alt']) ? $options['alt'] : null,
isset($options['onerror']) && 'continue' == $options['onerror'] ? 'true' : 'false'
);
}
}
}
namespace Symfony\Component\HttpFoundation
{
class ParameterBag
{
protected $parameters;
public function __construct(array $parameters = array())
{
$this->parameters = $parameters;
}
public function all()
{
return $this->parameters;
}
public function keys()
{
return array_keys($this->parameters);
}
public function replace(array $parameters = array())
{
$this->parameters = $parameters;
}
public function add(array $parameters = array())
{
$this->parameters = array_replace($this->parameters, $parameters);
}
public function get($key, $default = null)
{
return array_key_exists($key, $this->parameters) ? $this->parameters[$key] : $default;
}
public function set($key, $value)
{
$this->parameters[$key] = $value;
}
public function has($key)
{
return array_key_exists($key, $this->parameters);
}
public function remove($key)
{
unset($this->parameters[$key]);
}
public function getAlpha($key, $default = '')
{
return preg_replace('/[^[:alpha:]]/', '', $this->get($key, $default));
}
public function getAlnum($key, $default = '')
{
return preg_replace('/[^[:alnum:]]/', '', $this->get($key, $default));
}
public function getDigits($key, $default = '')
{
return preg_replace('/[^[:digit:]]/', '', $this->get($key, $default));
}
public function getInt($key, $default = 0)
{
return (int) $this->get($key, $default);
}
}
}
namespace Symfony\Component\HttpFoundation
{
use Symfony\Component\HttpFoundation\File\UploadedFile;
class FileBag extends ParameterBag
{
private $fileKeys = array('error', 'name', 'size', 'tmp_name', 'type');
public function __construct(array $parameters = array())
{
$this->replace($parameters);
}
public function replace(array $files = array())
{
$this->parameters = array();
$this->add($files);
}
public function set($key, $value)
{
if (is_array($value) || $value instanceof UploadedFile) {
parent::set($key, $this->convertFileInformation($value));
}
}
public function add(array $files = array())
{
foreach ($files as $key => $file) {
$this->set($key, $file);
}
}
protected function convertFileInformation($file)
{
if ($file instanceof UploadedFile) {
return $file;
}
$file = $this->fixPhpFilesArray($file);
if (is_array($file)) {
$keys = array_keys($file);
sort($keys);
if ($keys == $this->fileKeys) {
$file['error'] = (int) $file['error'];
}
if ($keys != $this->fileKeys) {
$file = array_map(array($this, 'convertFileInformation'), $file);
} else {
if ($file['error'] === UPLOAD_ERR_NO_FILE) {
$file = null;
} else {
$file = new UploadedFile($file['tmp_name'], $file['name'],
$file['type'], $file['size'], $file['error']);
}
}
}
return $file;
}
protected function fixPhpFilesArray($data)
{
if (! is_array($data)) {
return $data;
}
$keys = array_keys($data);
sort($keys);
if ($this->fileKeys != $keys || ! isset($data['name']) ||
! is_array($data['name'])) {
return $data;
}
$files = $data;
foreach ($this->fileKeys as $k) {
unset($files[$k]);
}
foreach (array_keys($data['name']) as $key) {
$files[$key] = $this->fixPhpFilesArray(array(
'error' => $data['error'][$key],
'name' => $data['name'][$key], 'type' => $data['type'][$key],
'tmp_name' => $data['tmp_name'][$key],
'size' => $data['size'][$key]
));
}
return $files;
}
}
}
namespace Symfony\Component\HttpFoundation
{
class ServerBag extends ParameterBag
{
public function getHeaders()
{
$headers = array();
foreach ($this->parameters as $key => $value) {
if ('HTTP_' === substr($key, 0, 5)) {
$headers[substr($key, 5)] = $value;
}
}
return $headers;
}
}
}
namespace Symfony\Component\HttpFoundation
{
class HeaderBag
{
protected $headers;
protected $cookies;
protected $cacheControl;
public function __construct(array $headers = array())
{
$this->cacheControl = array();
$this->cookies = array();
$this->headers = array();
foreach ($headers as $key => $values) {
$this->set($key, $values);
}
}
public function all()
{
return $this->headers;
}
public function keys()
{
return array_keys($this->headers);
}
public function replace(array $headers = array())
{
$this->headers = array();
$this->add($headers);
}
public function add(array $headers)
{
foreach ($headers as $key => $values) {
$this->set($key, $values);
}
}
public function get($key, $default = null, $first = true)
{
$key = strtr(strtolower($key), '_', '-');
if (!array_key_exists($key, $this->headers)) {
if (null === $default) {
return $first ? null : array();
}
return $first ? $default : array($default);
}
if ($first) {
return count($this->headers[$key]) ? $this->headers[$key][0] : $default;
}
return $this->headers[$key];
}
public function set($key, $values, $replace = true)
{
$key = strtr(strtolower($key), '_', '-');
if (!is_array($values)) {
$values = array($values);
}
if (true === $replace || !isset($this->headers[$key])) {
$this->headers[$key] = $values;
} else {
$this->headers[$key] = array_merge($this->headers[$key], $values);
}
if ('cache-control' === $key) {
$this->cacheControl = $this->parseCacheControl($values[0]);
}
}
public function has($key)
{
return array_key_exists(strtr(strtolower($key), '_', '-'), $this->headers);
}
public function contains($key, $value)
{
return in_array($value, $this->get($key, null, false));
}
public function remove($key)
{
$key = strtr(strtolower($key), '_', '-');
unset($this->headers[$key]);
if ('cache-control' === $key) {
$this->cacheControl = array();
}
}
public function setCookie(Cookie $cookie)
{
$this->cookies[$cookie->getName()] = $cookie;
}
public function removeCookie($name)
{
unset($this->cookies[$name]);
}
public function hasCookie($name)
{
return isset($this->cookies[$name]);
}
public function getCookie($name)
{
if (!$this->hasCookie($name)) {
throw new \InvalidArgumentException(sprintf('There is no cookie with name "%s".', $name));
}
return $this->cookies[$name];
}
public function getCookies()
{
return $this->cookies;
}
public function getDate($key, \DateTime $default = null)
{
if (null === $value = $this->get($key)) {
return $default;
}
if (false === $date = \DateTime::createFromFormat(DATE_RFC2822, $value)) {
throw new \RuntimeException(sprintf('The %s HTTP header is not parseable (%s).', $key, $value));
}
return $date;
}
public function addCacheControlDirective($key, $value = true)
{
$this->cacheControl[$key] = $value;
$this->set('Cache-Control', $this->getCacheControlHeader());
}
public function hasCacheControlDirective($key)
{
return array_key_exists($key, $this->cacheControl);
}
public function getCacheControlDirective($key)
{
return array_key_exists($key, $this->cacheControl) ? $this->cacheControl[$key] : null;
}
public function removeCacheControlDirective($key)
{
unset($this->cacheControl[$key]);
$this->set('Cache-Control', $this->getCacheControlHeader());
}
protected function getCacheControlHeader()
{
$parts = array();
ksort($this->cacheControl);
foreach ($this->cacheControl as $key => $value) {
if (true === $value) {
$parts[] = $key;
} else {
if (preg_match('#[^a-zA-Z0-9._-]#', $value)) {
$value = '"'.$value.'"';
}
$parts[] = "$key=$value";
}
}
return implode(', ', $parts);
}
protected function parseCacheControl($header)
{
$cacheControl = array();
preg_match_all('#([a-zA-Z][a-zA-Z_-]*)\s*(?:=(?:"([^"]*)"|([^ \t",;]*)))?#', $header, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
$cacheControl[strtolower($match[1])] = isset($match[2]) && $match[2] ? $match[2] : (isset($match[3]) ? $match[3] : true);
}
return $cacheControl;
}
}
}
namespace Symfony\Component\HttpFoundation
{
use Symfony\Component\HttpFoundation\SessionStorage\NativeSessionStorage;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class Request
{
public $attributes;
public $request;
public $query;
public $server;
public $files;
public $cookies;
public $headers;
protected $content;
protected $languages;
protected $charsets;
protected $acceptableContentTypes;
protected $pathInfo;
protected $requestUri;
protected $baseUrl;
protected $basePath;
protected $method;
protected $format;
protected $session;
static protected $formats;
public function __construct(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
{
$this->initialize($query, $request, $attributes, $cookies, $files, $server, $content);
}
public function initialize(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
{
$this->request = new ParameterBag($request);
$this->query = new ParameterBag($query);
$this->attributes = new ParameterBag($attributes);
$this->cookies = new ParameterBag($cookies);
$this->files = new FileBag($files);
$this->server = new ServerBag($server);
$this->headers = new HeaderBag($this->server->getHeaders());
$this->content = $content;
$this->languages = null;
$this->charsets = null;
$this->acceptableContentTypes = null;
$this->pathInfo = null;
$this->requestUri = null;
$this->baseUrl = null;
$this->basePath = null;
$this->method = null;
$this->format = null;
}
static public function createfromGlobals()
{
return new static($_GET, $_POST, array(), $_COOKIE, $_FILES, $_SERVER);
}
static public function create($uri, $method = 'GET', $parameters = array(), $cookies = array(), $files = array(), $server = array(), $content = null)
{
$defaults = array(
'SERVER_NAME' => 'localhost',
'SERVER_PORT' => 80,
'HTTP_HOST' => 'localhost',
'HTTP_USER_AGENT' => 'Symfony/2.X',
'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'HTTP_ACCEPT_LANGUAGE' => 'en-us,en;q=0.5',
'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'REMOTE_ADDR' => '127.0.0.1',
'SCRIPT_NAME' => '',
'SCRIPT_FILENAME' => '',
);
$components = parse_url($uri);
if (isset($components['host'])) {
$defaults['SERVER_NAME'] = $components['host'];
$defaults['HTTP_HOST'] = $components['host'];
}
if (isset($components['scheme'])) {
if ('https' === $components['scheme']) {
$defaults['HTTPS'] = 'on';
$defaults['SERVER_PORT'] = 443;
}
}
if (isset($components['port'])) {
$defaults['SERVER_PORT'] = $components['port'];
$defaults['HTTP_HOST'] = $defaults['HTTP_HOST'].':'.$components['port'];
}
if (in_array(strtoupper($method), array('POST', 'PUT', 'DELETE'))) {
$request = $parameters;
$query = array();
$defaults['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
} else {
$request = array();
$query = $parameters;
if (false !== $pos = strpos($uri, '?')) {
$qs = substr($uri, $pos + 1);
parse_str($qs, $params);
$query = array_merge($params, $query);
}
}
$queryString = isset($components['query']) ? html_entity_decode($components['query']) : '';
parse_str($queryString, $qs);
if (is_array($qs)) {
$query = array_replace($qs, $query);
}
$uri = $components['path'] . ($queryString ? '?'.$queryString : '');
$server = array_replace($defaults, $server, array(
'REQUEST_METHOD' => strtoupper($method),
'PATH_INFO' => '',
'REQUEST_URI' => $uri,
'QUERY_STRING' => $queryString,
));
return new static($query, $request, array(), $cookies, $files, $server, $content);
}
public function duplicate(array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null)
{
$dup = clone $this;
if ($query !== null) {
$dup->query = new ParameterBag($query);
}
if ($request !== null) {
$dup->request = new ParameterBag($request);
}
if ($attributes !== null) {
$dup->attributes = new ParameterBag($attributes);
}
if ($cookies !== null) {
$dup->cookies = new ParameterBag($cookies);
}
if ($files !== null) {
$dup->files = new FileBag($files);
}
if ($server !== null) {
$dup->server = new ServerBag($server);
$dup->headers = new HeaderBag($dup->server->getHeaders());
}
$this->languages = null;
$this->charsets = null;
$this->acceptableContentTypes = null;
$this->pathInfo = null;
$this->requestUri = null;
$this->baseUrl = null;
$this->basePath = null;
$this->method = null;
$this->format = null;
return $dup;
}
public function __clone()
{
$this->query = clone $this->query;
$this->request = clone $this->request;
$this->attributes = clone $this->attributes;
$this->cookies = clone $this->cookies;
$this->files = clone $this->files;
$this->server = clone $this->server;
$this->headers = clone $this->headers;
}
public function overrideGlobals()
{
$_GET = $this->query->all();
$_POST = $this->request->all();
$_SERVER = $this->server->all();
$_COOKIE = $this->cookies->all();
foreach ($this->headers->all() as $key => $value) {
$_SERVER['HTTP_'.strtoupper(str_replace('-', '_', $key))] = implode(', ', $value);
}
$_REQUEST = array_merge($_GET, $_POST);
}
public function get($key, $default = null)
{
return $this->query->get($key, $this->attributes->get($key, $this->request->get($key, $default)));
}
public function getSession()
{
return $this->session;
}
public function hasSession()
{
return $this->cookies->has(session_name());
}
public function setSession(Session $session)
{
$this->session = $session;
}
public function getClientIp($proxy = false)
{
if ($proxy) {
if ($this->server->has('HTTP_CLIENT_IP')) {
return $this->server->get('HTTP_CLIENT_IP');
} elseif ($this->server->has('HTTP_X_FORWARDED_FOR')) {
return $this->server->get('HTTP_X_FORWARDED_FOR');
}
}
return $this->server->get('REMOTE_ADDR');
}
public function getScriptName()
{
return $this->server->get('SCRIPT_NAME', $this->server->get('ORIG_SCRIPT_NAME', ''));
}
public function getPathInfo()
{
if (null === $this->pathInfo) {
$this->pathInfo = $this->preparePathInfo();
}
return $this->pathInfo;
}
public function getBasePath()
{
if (null === $this->basePath) {
$this->basePath = $this->prepareBasePath();
}
return $this->basePath;
}
public function getBaseUrl()
{
if (null === $this->baseUrl) {
$this->baseUrl = $this->prepareBaseUrl();
}
return $this->baseUrl;
}
public function getScheme()
{
return ($this->server->get('HTTPS') == 'on') ? 'https' : 'http';
}
public function getPort()
{
return $this->server->get('SERVER_PORT');
}
public function getHttpHost()
{
$host = $this->headers->get('HOST');
if (!empty($host)) {
return $host;
}
$scheme = $this->getScheme();
$name = $this->server->get('SERVER_NAME');
$port = $this->getPort();
if (('http' == $scheme && $port == 80) || ('https' == $scheme && $port == 443)) {
return $name;
}
return $name.':'.$port;
}
public function getRequestUri()
{
if (null === $this->requestUri) {
$this->requestUri = $this->prepareRequestUri();
}
return $this->requestUri;
}
public function getUri()
{
$qs = $this->getQueryString();
if (null !== $qs) {
$qs = '?'.$qs;
}
return $this->getScheme().'://'.$this->getHttpHost().$this->getBaseUrl().$this->getPathInfo().$qs;
}
public function getUriForPath($path)
{
return $this->getScheme().'://'.$this->getHttpHost().$this->getBaseUrl().$path;
}
public function getQueryString()
{
if (!$qs = $this->server->get('QUERY_STRING')) {
return null;
}
$parts = array();
$order = array();
foreach (explode('&', $qs) as $segment) {
if (false === strpos($segment, '=')) {
$parts[] = $segment;
$order[] = $segment;
} else {
$tmp = explode('=', urldecode($segment), 2);
$parts[] = urlencode($tmp[0]).'='.urlencode($tmp[1]);
$order[] = $tmp[0];
}
}
array_multisort($order, SORT_ASC, $parts);
return implode('&', $parts);
}
public function isSecure()
{
return (
(strtolower($this->server->get('HTTPS')) == 'on' || $this->server->get('HTTPS') == 1)
||
(strtolower($this->headers->get('SSL_HTTPS')) == 'on' || $this->headers->get('SSL_HTTPS') == 1)
||
(strtolower($this->headers->get('X_FORWARDED_PROTO')) == 'https')
);
}
public function getHost()
{
if ($host = $this->headers->get('X_FORWARDED_HOST')) {
$elements = explode(',', $host);
$host = trim($elements[count($elements) - 1]);
} else {
if (!$host = $this->headers->get('HOST')) {
if (!$host = $this->server->get('SERVER_NAME')) {
$host = $this->server->get('SERVER_ADDR', '');
}
}
}
$elements = explode(':', $host);
return trim($elements[0]);
}
public function setMethod($method)
{
$this->method = null;
$this->server->set('REQUEST_METHOD', $method);
}
public function getMethod()
{
if (null === $this->method) {
$this->method = strtoupper($this->server->get('REQUEST_METHOD', 'GET'));
if ('POST' === $this->method) {
$this->method = strtoupper($this->request->get('_method', 'POST'));
}
}
return $this->method;
}
public function getMimeType($format)
{
if (null === static::$formats) {
static::initializeFormats();
}
return isset(static::$formats[$format]) ? static::$formats[$format][0] : null;
}
public function getFormat($mimeType)
{
if (null === static::$formats) {
static::initializeFormats();
}
foreach (static::$formats as $format => $mimeTypes) {
if (in_array($mimeType, (array) $mimeTypes)) {
return $format;
}
}
return null;
}
public function setFormat($format, $mimeTypes)
{
if (null === static::$formats) {
static::initializeFormats();
}
static::$formats[$format] = is_array($mimeTypes) ? $mimeTypes : array($mimeTypes);
}
public function getRequestFormat()
{
if (null === $this->format) {
$this->format = $this->get('_format', 'html');
}
return $this->format;
}
public function setRequestFormat($format)
{
$this->format = $format;
}
public function isMethodSafe()
{
return in_array($this->getMethod(), array('GET', 'HEAD'));
}
public function getContent($asResource = false)
{
if (false === $this->content || (true === $asResource && null !== $this->content)) {
throw new \LogicException('getContent() can only be called once when using the resource return type.');
}
if (true === $asResource) {
$this->content = false;
return fopen('php://input', 'rb');
}
if (null === $this->content) {
$this->content = file_get_contents('php://input');
}
return $this->content;
}
public function getETags()
{
return preg_split('/\s*,\s*/', $this->headers->get('if_none_match'), null, PREG_SPLIT_NO_EMPTY);
}
public function isNoCache()
{
return $this->headers->hasCacheControlDirective('no-cache') || 'no-cache' == $this->headers->get('Pragma');
}
public function getPreferredLanguage(array $locales = null)
{
$preferredLanguages = $this->getLanguages();
if (null === $locales) {
return isset($preferredLanguages[0]) ? $preferredLanguages[0] : null;
}
if (!$preferredLanguages) {
return $locales[0];
}
$preferredLanguages = array_values(array_intersect($preferredLanguages, $locales));
return isset($preferredLanguages[0]) ? $preferredLanguages[0] : $locales[0];
}
public function getLanguages()
{
if (null !== $this->languages) {
return $this->languages;
}
$languages = $this->splitHttpAcceptHeader($this->headers->get('Accept-Language'));
foreach ($languages as $lang) {
if (strstr($lang, '-')) {
$codes = explode('-', $lang);
if ($codes[0] == 'i') {
if (count($codes) > 1) {
$lang = $codes[1];
}
} else {
for ($i = 0, $max = count($codes); $i < $max; $i++) {
if ($i == 0) {
$lang = strtolower($codes[0]);
} else {
$lang .= '_'.strtoupper($codes[$i]);
}
}
}
}
$this->languages[] = $lang;
}
return $this->languages;
}
public function getCharsets()
{
if (null !== $this->charsets) {
return $this->charsets;
}
return $this->charsets = $this->splitHttpAcceptHeader($this->headers->get('Accept-Charset'));
}
public function getAcceptableContentTypes()
{
if (null !== $this->acceptableContentTypes) {
return $this->acceptableContentTypes;
}
return $this->acceptableContentTypes = $this->splitHttpAcceptHeader($this->headers->get('Accept'));
}
public function isXmlHttpRequest()
{
return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
}
public function splitHttpAcceptHeader($header)
{
if (!$header) {
return array();
}
$values = array();
foreach (array_filter(explode(',', $header)) as $value) {
if ($pos = strpos($value, ';')) {
$q = (float) trim(substr($value, strpos($value, '=') + 1));
$value = trim(substr($value, 0, $pos));
} else {
$q = 1;
}
if (0 < $q) {
$values[trim($value)] = $q;
}
}
arsort($values);
return array_keys($values);
}
protected function prepareRequestUri()
{
$requestUri = '';
if ($this->headers->has('X_REWRITE_URL')) {
$requestUri = $this->headers->get('X_REWRITE_URL');
} elseif ($this->server->get('IIS_WasUrlRewritten') == '1' && $this->server->get('UNENCODED_URL') != '') {
$requestUri = $this->server->get('UNENCODED_URL');
} elseif ($this->server->has('REQUEST_URI')) {
$requestUri = $this->server->get('REQUEST_URI');
$schemeAndHttpHost = $this->getScheme().'://'.$this->getHttpHost();
if (strpos($requestUri, $schemeAndHttpHost) === 0) {
$requestUri = substr($requestUri, strlen($schemeAndHttpHost));
}
} elseif ($this->server->has('ORIG_PATH_INFO')) {
$requestUri = $this->server->get('ORIG_PATH_INFO');
if ($this->server->get('QUERY_STRING')) {
$requestUri .= '?'.$this->server->get('QUERY_STRING');
}
}
return $requestUri;
}
protected function prepareBaseUrl()
{
$filename = basename($this->server->get('SCRIPT_FILENAME'));
if (basename($this->server->get('SCRIPT_NAME')) === $filename) {
$baseUrl = $this->server->get('SCRIPT_NAME');
} elseif (basename($this->server->get('PHP_SELF')) === $filename) {
$baseUrl = $this->server->get('PHP_SELF');
} elseif (basename($this->server->get('ORIG_SCRIPT_NAME')) === $filename) {
$baseUrl = $this->server->get('ORIG_SCRIPT_NAME'); } else {
$path = $this->server->get('PHP_SELF', '');
$file = $this->server->get('SCRIPT_FILENAME', '');
$segs = explode('/', trim($file, '/'));
$segs = array_reverse($segs);
$index = 0;
$last = count($segs);
$baseUrl = '';
do {
$seg = $segs[$index];
$baseUrl = '/'.$seg.$baseUrl;
++$index;
} while (($last > $index) && (false !== ($pos = strpos($path, $baseUrl))) && (0 != $pos));
}
$requestUri = $this->getRequestUri();
if ($baseUrl && 0 === strpos($requestUri, $baseUrl)) {
return $baseUrl;
}
if ($baseUrl && 0 === strpos($requestUri, dirname($baseUrl))) {
return rtrim(dirname($baseUrl), '/');
}
$truncatedRequestUri = $requestUri;
if (($pos = strpos($requestUri, '?')) !== false) {
$truncatedRequestUri = substr($requestUri, 0, $pos);
}
$basename = basename($baseUrl);
if (empty($basename) || !strpos($truncatedRequestUri, $basename)) {
return '';
}
if ((strlen($requestUri) >= strlen($baseUrl)) && ((false !== ($pos = strpos($requestUri, $baseUrl))) && ($pos !== 0))) {
$baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl));
}
return rtrim($baseUrl, '/');
}
protected function prepareBasePath()
{
$filename = basename($this->server->get('SCRIPT_FILENAME'));
$baseUrl = $this->getBaseUrl();
if (empty($baseUrl)) {
return '';
}
if (basename($baseUrl) === $filename) {
$basePath = dirname($baseUrl);
} else {
$basePath = $baseUrl;
}
if ('\\' === DIRECTORY_SEPARATOR) {
$basePath = str_replace('\\', '/', $basePath);
}
return rtrim($basePath, '/');
}
protected function preparePathInfo()
{
$baseUrl = $this->getBaseUrl();
if (null === ($requestUri = $this->getRequestUri())) {
return '';
}
$pathInfo = '';
if ($pos = strpos($requestUri, '?')) {
$requestUri = substr($requestUri, 0, $pos);
}
if ((null !== $baseUrl) && (false === ($pathInfo = substr($requestUri, strlen($baseUrl))))) {
return '';
} elseif (null === $baseUrl) {
return $requestUri;
}
return (string) $pathInfo;
}
static protected function initializeFormats()
{
static::$formats = array(
'txt' => array('text/plain'),
'js' => array('application/javascript', 'application/x-javascript', 'text/javascript'),
'css' => array('text/css'),
'json' => array('application/json', 'application/x-json'),
'xml' => array('text/xml', 'application/xml', 'application/x-xml'),
'rdf' => array('application/rdf+xml'),
'atom' => array('application/atom+xml'),
);
}
}
}
namespace Symfony\Component\HttpFoundation
{
class ApacheRequest extends Request
{
protected function prepareRequestUri()
{
return $this->server->get('REQUEST_URI');
}
protected function prepareBaseUrl()
{
return $this->server->get('SCRIPT_NAME');
}
protected function preparePathInfo()
{
return $this->server->get('PATH_INFO');
}
}
}
namespace Symfony\Component\HttpFoundation
{
class ResponseHeaderBag extends HeaderBag
{
protected $computedCacheControl = array();
public function __construct(array $headers = array())
{
parent::__construct($headers);
if (!isset($this->headers['cache-control'])) {
$this->set('cache-control', '');
}
}
public function replace(array $headers = array())
{
parent::replace($headers);
if (!isset($this->headers['cache-control'])) {
$this->set('cache-control', '');
}
}
public function set($key, $values, $replace = true)
{
parent::set($key, $values, $replace);
if (in_array(strtr(strtolower($key), '_', '-'), array('cache-control', 'etag', 'last-modified', 'expires'))) {
$computed = $this->computeCacheControlValue();
$this->headers['cache-control'] = array($computed);
$this->computedCacheControl = $this->parseCacheControl($computed);
}
}
public function remove($key)
{
parent::remove($key);
if ('cache-control' === strtr(strtolower($key), '_', '-')) {
$this->computedCacheControl = array();
}
}
public function hasCacheControlDirective($key)
{
return array_key_exists($key, $this->computedCacheControl);
}
public function getCacheControlDirective($key)
{
return array_key_exists($key, $this->computedCacheControl) ? $this->computedCacheControl[$key] : null;
}
public function clearCookie($name, $path = null, $domain = null)
{
$this->setCookie(new Cookie($name, null, 1, $path, $domain));
}
protected function computeCacheControlValue()
{
if (!$this->cacheControl && !$this->has('ETag') && !$this->has('Last-Modified') && !$this->has('Expires')) {
return 'no-cache';
}
if (!$this->cacheControl) {
return 'private, must-revalidate';
}
$header = $this->getCacheControlHeader();
if (isset($this->cacheControl['public']) || isset($this->cacheControl['private'])) {
return $header;
}
if (!isset($this->cacheControl['s-maxage'])) {
return $header.', private';
}
return $header;
}
}}
namespace Symfony\Component\HttpFoundation
{
class Response
{
public $headers;
protected $content;
protected $version;
protected $statusCode;
protected $statusText;
protected $charset;
static public $statusTexts = array(
100 => 'Continue',
101 => 'Switching Protocols',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
418 => 'I\'m a teapot',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
);
public function __construct($content = '', $status = 200, $headers = array())
{
$this->setContent($content);
$this->setStatusCode($status);
$this->setProtocolVersion('1.0');
$this->headers = new ResponseHeaderBag($headers);
}
public function __toString()
{
$content = '';
if (!$this->headers->has('Content-Type')) {
$this->headers->set('Content-Type', 'text/html; charset='.(null === $this->charset ? 'UTF-8' : $this->charset));
}
$content .= sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\n";
foreach ($this->headers->all() as $name => $values) {
foreach ($values as $value) {
$content .= "$name: $value\n";
}
}
$content .= "\n".$this->getContent();
return $content;
}
public function __clone()
{
$this->headers = clone $this->headers;
}
public function sendHeaders()
{
if (!$this->headers->has('Content-Type')) {
$this->headers->set('Content-Type', 'text/html; charset='.(null === $this->charset ? 'UTF-8' : $this->charset));
}
header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText));
foreach ($this->headers->all() as $name => $values) {
foreach ($values as $value) {
header($name.': '.$value);
}
}
foreach ($this->headers->getCookies() as $cookie) {
setcookie($cookie->getName(), $cookie->getValue(), $cookie->getExpire(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly());
}
}
public function sendContent()
{
echo $this->content;
}
public function send()
{
$this->sendHeaders();
$this->sendContent();
}
public function setContent($content)
{
$this->content = $content;
}
public function getContent()
{
return $this->content;
}
public function setProtocolVersion($version)
{
$this->version = $version;
}
public function getProtocolVersion()
{
return $this->version;
}
public function setStatusCode($code, $text = null)
{
$this->statusCode = (int) $code;
if ($this->statusCode < 100 || $this->statusCode > 599) {
throw new \InvalidArgumentException(sprintf('The HTTP status code "%s" is not valid.', $code));
}
$this->statusText = false === $text ? '' : (null === $text ? self::$statusTexts[$this->statusCode] : $text);
}
public function getStatusCode()
{
return $this->statusCode;
}
public function setCharset($charset)
{
$this->charset = $charset;
}
public function getCharset()
{
return $this->charset;
}
public function isCacheable()
{
if (!in_array($this->statusCode, array(200, 203, 300, 301, 302, 404, 410))) {
return false;
}
if ($this->headers->hasCacheControlDirective('no-store') || $this->headers->getCacheControlDirective('private')) {
return false;
}
return $this->isValidateable() || $this->isFresh();
}
public function isFresh()
{
return $this->getTtl() > 0;
}
public function isValidateable()
{
return $this->headers->has('Last-Modified') || $this->headers->has('ETag');
}
public function setPrivate()
{
$this->headers->removeCacheControlDirective('public');
$this->headers->addCacheControlDirective('private');
}
public function setPublic()
{
$this->headers->addCacheControlDirective('public');
$this->headers->removeCacheControlDirective('private');
}
public function mustRevalidate()
{
return $this->headers->hasCacheControlDirective('must-revalidate') || $this->headers->has('must-proxy-revalidate');
}
public function getDate()
{
if (null === $date = $this->headers->getDate('Date')) {
$date = new \DateTime(null, new \DateTimeZone('UTC'));
$this->headers->set('Date', $date->format('D, d M Y H:i:s').' GMT');
}
return $date;
}
public function getAge()
{
if ($age = $this->headers->get('Age')) {
return $age;
}
return max(time() - $this->getDate()->format('U'), 0);
}
public function expire()
{
if ($this->isFresh()) {
$this->headers->set('Age', $this->getMaxAge());
}
}
public function getExpires()
{
return $this->headers->getDate('Expires');
}
public function setExpires(\DateTime $date = null)
{
if (null === $date) {
$this->headers->remove('Expires');
} else {
$date = clone $date;
$date->setTimezone(new \DateTimeZone('UTC'));
$this->headers->set('Expires', $date->format('D, d M Y H:i:s').' GMT');
}
}
public function getMaxAge()
{
if ($age = $this->headers->getCacheControlDirective('s-maxage')) {
return $age;
}
if ($age = $this->headers->getCacheControlDirective('max-age')) {
return $age;
}
if (null !== $this->getExpires()) {
return $this->getExpires()->format('U') - $this->getDate()->format('U');
}
return null;
}
public function setMaxAge($value)
{
$this->headers->addCacheControlDirective('max-age', $value);
}
public function setSharedMaxAge($value)
{
$this->headers->addCacheControlDirective('s-maxage', $value);
}
public function getTtl()
{
if ($maxAge = $this->getMaxAge()) {
return $maxAge - $this->getAge();
}
return null;
}
public function setTtl($seconds)
{
$this->setSharedMaxAge($this->getAge() + $seconds);
}
public function setClientTtl($seconds)
{
$this->setMaxAge($this->getAge() + $seconds);
}
public function getLastModified()
{
return $this->headers->getDate('LastModified');
}
public function setLastModified(\DateTime $date = null)
{
if (null === $date) {
$this->headers->remove('Last-Modified');
} else {
$date = clone $date;
$date->setTimezone(new \DateTimeZone('UTC'));
$this->headers->set('Last-Modified', $date->format('D, d M Y H:i:s').' GMT');
}
}
public function getEtag()
{
return $this->headers->get('ETag');
}
public function setEtag($etag = null, $weak = false)
{
if (null === $etag) {
$this->headers->remove('Etag');
} else {
if (0 !== strpos($etag, '"')) {
$etag = '"'.$etag.'"';
}
$this->headers->set('ETag', (true === $weak ? 'W/' : '').$etag);
}
}
public function setCache(array $options)
{
if ($diff = array_diff(array_keys($options), array('etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public'))) {
throw new \InvalidArgumentException(sprintf('Response does not support the following options: "%s".', implode('", "', array_keys($diff))));
}
if (isset($options['etag'])) {
$this->setEtag($options['etag']);
}
if (isset($options['last_modified'])) {
$this->setLastModified($options['last_modified']);
}
if (isset($options['max_age'])) {
$this->setMaxAge($options['max_age']);
}
if (isset($options['s_maxage'])) {
$this->setSharedMaxAge($options['s_maxage']);
}
if (isset($options['public'])) {
if ($options['public']) {
$this->setPublic();
} else {
$this->setPrivate();
}
}
if (isset($options['private'])) {
if ($options['private']) {
$this->setPrivate();
} else {
$this->setPublic();
}
}
}
public function setNotModified()
{
$this->setStatusCode(304);
$this->setContent(null);
foreach (array('Allow', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-MD5', 'Content-Type', 'Last-Modified') as $header) {
$this->headers->remove($header);
}
}
public function hasVary()
{
return (Boolean) $this->headers->get('Vary');
}
public function getVary()
{
if (!$vary = $this->headers->get('Vary')) {
return array();
}
return is_array($vary) ? $vary : preg_split('/[\s,]+/', $vary);
}
public function setVary($headers, $replace = true)
{
$this->headers->set('Vary', $headers, $replace);
}
public function isNotModified(Request $request)
{
$lastModified = $request->headers->get('If-Modified-Since');
$notModified = false;
if ($etags = $request->getEtags()) {
$notModified = (in_array($this->getEtag(), $etags) || in_array('*', $etags)) && (!$lastModified || $this->headers->get('Last-Modified') == $lastModified);
} elseif ($lastModified) {
$notModified = $lastModified == $this->headers->get('Last-Modified');
}
if ($notModified) {
$this->setNotModified();
}
return $notModified;
}
public function isInvalid()
{
return $this->statusCode < 100 || $this->statusCode >= 600;
}
public function isInformational()
{
return $this->statusCode >= 100 && $this->statusCode < 200;
}
public function isSuccessful()
{
return $this->statusCode >= 200 && $this->statusCode < 300;
}
public function isRedirection()
{
return $this->statusCode >= 300 && $this->statusCode < 400;
}
public function isClientError()
{
return $this->statusCode >= 400 && $this->statusCode < 500;
}
public function isServerError()
{
return $this->statusCode >= 500 && $this->statusCode < 600;
}
public function isOk()
{
return 200 === $this->statusCode;
}
public function isForbidden()
{
return 403 === $this->statusCode;
}
public function isNotFound()
{
return 404 === $this->statusCode;
}
public function isRedirect()
{
return in_array($this->statusCode, array(301, 302, 303, 307));
}
public function isEmpty()
{
return in_array($this->statusCode, array(201, 204, 304));
}
public function isRedirected($location)
{
return $this->isRedirect() && $location == $this->headers->get('Location');
}
}
}
namespace Symfony\Component\ClassLoader
{
class UniversalClassLoader
{
protected $namespaces = array();
protected $prefixes = array();
protected $namespaceFallback = array();
protected $prefixFallback = array();
public function getNamespaces()
{
return $this->namespaces;
}
public function getPrefixes()
{
return $this->prefixes;
}
public function getNamespaceFallback()
{
return $this->namespaceFallback;
}
public function getPrefixFallback()
{
return $this->prefixFallback;
}
public function registerNamespaceFallback($dirs)
{
$this->namespaceFallback = (array) $dirs;
}
public function registerPrefixFallback($dirs)
{
$this->prefixFallback = (array) $dirs;
}
public function registerNamespaces(array $namespaces)
{
foreach ($namespaces as $namespace => $locations) {
$this->namespaces[$namespace] = (array) $locations;
}
}
public function registerNamespace($namespace, $paths)
{
$this->namespaces[$namespace] = (array) $paths;
}
public function registerPrefixes(array $classes)
{
foreach ($classes as $prefix => $locations) {
$this->prefixes[$prefix] = (array) $locations;
}
}
public function registerPrefix($prefix, $paths)
{
$this->prefixes[$prefix] = (array) $paths;
}
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
}
public function loadClass($class)
{
$class = ltrim($class, '\\');
if (false !== ($pos = strrpos($class, '\\'))) {
$namespace = substr($class, 0, $pos);
foreach ($this->namespaces as $ns => $dirs) {
foreach ($dirs as $dir) {
if (0 === strpos($namespace, $ns)) {
$className = substr($class, $pos + 1);
$file = $dir.DIRECTORY_SEPARATOR.str_replace('\\', DIRECTORY_SEPARATOR, $namespace).DIRECTORY_SEPARATOR.str_replace('_', DIRECTORY_SEPARATOR, $className).'.php';
if (file_exists($file)) {
require $file;
return;
}
}
}
}
foreach ($this->namespaceFallback as $dir) {
$file = $dir.DIRECTORY_SEPARATOR.str_replace('\\', DIRECTORY_SEPARATOR, $class).'.php';
if (file_exists($file)) {
require $file;
return;
}
}
} else {
foreach ($this->prefixes as $prefix => $dirs) {
foreach ($dirs as $dir) {
if (0 === strpos($class, $prefix)) {
$file = $dir.DIRECTORY_SEPARATOR.str_replace('_', DIRECTORY_SEPARATOR, $class).'.php';
if (file_exists($file)) {
require $file;
return;
}
}
}
}
foreach ($this->prefixFallback as $dir) {
$file = $dir.DIRECTORY_SEPARATOR.str_replace('_', DIRECTORY_SEPARATOR, $class).'.php';
if (file_exists($file)) {
require $file;
return;
}
}
}
}
}
}
| {'content_hash': 'f8dace83757921cdc858a0d523daf9d4', 'timestamp': '', 'source': 'github', 'line_count': 2481, 'max_line_length': 216, 'avg_line_length': 35.34421604191858, 'alnum_prop': 0.5201222502252278, 'repo_name': 'l3l0/BehatExamples', 'id': 'b891ab39c5989b92ac7cb39051890573a64b82ae', 'size': '87689', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/bootstrap_cache.php', 'mode': '33188', 'license': 'mit', 'language': []} |
OpenVirteX
==========
The OpenVirteX Virtualization Platform
| {'content_hash': '3bcf0bdf9f86adbd0b4ac9aa01ed24f4', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 38, 'avg_line_length': 15.5, 'alnum_prop': 0.7258064516129032, 'repo_name': 'mgerola/OpenVirteX', 'id': 'c33796dda14bf895dd399005e8af423de93836e2', 'size': '62', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '1039209'}, {'name': 'Python', 'bytes': '166438'}, {'name': 'Shell', 'bytes': '3914'}]} |
using AutoMapper;
namespace LiveScoreUpdateSystem.Web.Infrastructure.Contracts
{
public interface ICustomMapping
{
void CreateMappings(IMapperConfigurationExpression configuration);
}
} | {'content_hash': 'cfa2f1be12749dc47a2d2f1a476a58fa', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 74, 'avg_line_length': 23.0, 'alnum_prop': 0.7777777777777778, 'repo_name': 'BorislavBorisov22/LiveScoreUpdateSystem', 'id': 'c645f717f541a3238dcd75846e63b28ef396044b', 'size': '209', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'LiveScoreUpdateSystem/LiveScoreUpdateSystem.Web/Infrastructure/Contracts/ICustomMappings.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '116'}, {'name': 'C#', 'bytes': '404671'}, {'name': 'CSS', 'bytes': '189596'}, {'name': 'JavaScript', 'bytes': '152987'}]} |
package org.elasticsearch.index.engine;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.component.CloseableComponent;
import org.elasticsearch.common.lease.Releasable;
import org.elasticsearch.common.lucene.uid.Versions;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.index.deletionpolicy.SnapshotIndexCommit;
import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.ParseContext.Document;
import org.elasticsearch.index.mapper.ParsedDocument;
import org.elasticsearch.index.shard.IndexShardComponent;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.translog.Translog;
import java.util.List;
/**
*
*/
public interface Engine extends IndexShardComponent, CloseableComponent {
static final String INDEX_CODEC = "index.codec";
static ByteSizeValue INACTIVE_SHARD_INDEXING_BUFFER = ByteSizeValue.parseBytesSizeValue("500kb");
/**
* The default suggested refresh interval, -1 to disable it.
*/
TimeValue defaultRefreshInterval();
void enableGcDeletes(boolean enableGcDeletes);
void updateIndexingBufferSize(ByteSizeValue indexingBufferSize);
void addFailedEngineListener(FailedEngineListener listener);
/**
* Starts the Engine.
* <p/>
* <p>Note, after the creation and before the call to start, the store might
* be changed.
*/
void start() throws EngineException;
void create(Create create) throws EngineException;
void index(Index index) throws EngineException;
void delete(Delete delete) throws EngineException;
void delete(DeleteByQuery delete) throws EngineException;
GetResult get(Get get) throws EngineException;
/**
* Returns a new searcher instance. The consumer of this
* API is responsible for releasing the returned seacher in a
* safe manner, preferably in a try/finally block.
*
* @see Searcher#release()
*/
Searcher acquireSearcher(String source) throws EngineException;
/**
* Global stats on segments.
*/
SegmentsStats segmentsStats();
/**
* The list of segments in the engine.
*/
List<Segment> segments();
/**
* Returns <tt>true</tt> if a refresh is really needed.
*/
boolean refreshNeeded();
/**
* Returns <tt>true</tt> if a possible merge is really needed.
*/
boolean possibleMergeNeeded();
void maybeMerge() throws EngineException;
/**
* Refreshes the engine for new search operations to reflect the latest
* changes. Pass <tt>true</tt> if the refresh operation should include
* all the operations performed up to this call.
*/
void refresh(Refresh refresh) throws EngineException;
/**
* Flushes the state of the engine, clearing memory.
*/
void flush(Flush flush) throws EngineException, FlushNotAllowedEngineException;
void optimize(Optimize optimize) throws EngineException;
<T> T snapshot(SnapshotHandler<T> snapshotHandler) throws EngineException;
/**
* Snapshots the index and returns a handle to it. Will always try and "commit" the
* lucene index to make sure we have a "fresh" copy of the files to snapshot.
*/
SnapshotIndexCommit snapshotIndex() throws EngineException;
void recover(RecoveryHandler recoveryHandler) throws EngineException;
static interface FailedEngineListener {
void onFailedEngine(ShardId shardId, Throwable t);
}
/**
* Recovery allow to start the recovery process. It is built of three phases.
* <p/>
* <p>The first phase allows to take a snapshot of the master index. Once this
* is taken, no commit operations are effectively allowed on the index until the recovery
* phases are through.
* <p/>
* <p>The seconds phase takes a snapshot of the current transaction log.
* <p/>
* <p>The last phase returns the remaining transaction log. During this phase, no dirty
* operations are allowed on the index.
*/
static interface RecoveryHandler {
void phase1(SnapshotIndexCommit snapshot) throws ElasticsearchException;
void phase2(Translog.Snapshot snapshot) throws ElasticsearchException;
void phase3(Translog.Snapshot snapshot) throws ElasticsearchException;
}
static interface SnapshotHandler<T> {
T snapshot(SnapshotIndexCommit snapshotIndexCommit, Translog.Snapshot translogSnapshot) throws EngineException;
}
static interface Searcher extends Releasable {
/**
* The source that caused this searcher to be acquired.
*/
String source();
IndexReader reader();
IndexSearcher searcher();
}
static class SimpleSearcher implements Searcher {
private final String source;
private final IndexSearcher searcher;
public SimpleSearcher(String source, IndexSearcher searcher) {
this.source = source;
this.searcher = searcher;
}
@Override
public String source() {
return source;
}
@Override
public IndexReader reader() {
return searcher.getIndexReader();
}
@Override
public IndexSearcher searcher() {
return searcher;
}
@Override
public boolean release() throws ElasticsearchException {
// nothing to release here...
return true;
}
}
static class Refresh {
private final String source;
private boolean force = false;
public Refresh(String source) {
this.source = source;
}
/**
* Forces calling refresh, overriding the check that dirty operations even happened. Defaults
* to true (note, still lightweight if no refresh is needed).
*/
public Refresh force(boolean force) {
this.force = force;
return this;
}
public boolean force() {
return this.force;
}
public String source() {
return this.source;
}
@Override
public String toString() {
return "force[" + force + "], source [" + source + "]";
}
}
static class Flush {
public static enum Type {
/**
* A flush that causes a new writer to be created.
*/
NEW_WRITER,
/**
* A flush that just commits the writer, without cleaning the translog.
*/
COMMIT,
/**
* A flush that does a commit, as well as clears the translog.
*/
COMMIT_TRANSLOG
}
private Type type = Type.COMMIT_TRANSLOG;
private boolean force = false;
/**
* Should the flush operation wait if there is an ongoing flush operation.
*/
private boolean waitIfOngoing = false;
public Type type() {
return this.type;
}
/**
* Should a "full" flush be issued, basically cleaning as much memory as possible.
*/
public Flush type(Type type) {
this.type = type;
return this;
}
public boolean force() {
return this.force;
}
public Flush force(boolean force) {
this.force = force;
return this;
}
public boolean waitIfOngoing() {
return this.waitIfOngoing;
}
public Flush waitIfOngoing(boolean waitIfOngoing) {
this.waitIfOngoing = waitIfOngoing;
return this;
}
@Override
public String toString() {
return "type[" + type + "], force[" + force + "]";
}
}
static class Optimize {
private boolean waitForMerge = true;
private int maxNumSegments = -1;
private boolean onlyExpungeDeletes = false;
private boolean flush = false;
private boolean force = false;
public Optimize() {
}
public boolean waitForMerge() {
return waitForMerge;
}
public Optimize waitForMerge(boolean waitForMerge) {
this.waitForMerge = waitForMerge;
return this;
}
public int maxNumSegments() {
return maxNumSegments;
}
public Optimize maxNumSegments(int maxNumSegments) {
this.maxNumSegments = maxNumSegments;
return this;
}
public boolean onlyExpungeDeletes() {
return onlyExpungeDeletes;
}
public Optimize onlyExpungeDeletes(boolean onlyExpungeDeletes) {
this.onlyExpungeDeletes = onlyExpungeDeletes;
return this;
}
public boolean flush() {
return flush;
}
public Optimize flush(boolean flush) {
this.flush = flush;
return this;
}
public boolean force() {
return force;
}
public Optimize force(boolean force) {
this.force = force;
return this;
}
@Override
public String toString() {
return "waitForMerge[" + waitForMerge + "], maxNumSegments[" + maxNumSegments + "], onlyExpungeDeletes[" + onlyExpungeDeletes + "], flush[" + flush + "], force[" + force + "]";
}
}
static interface Operation {
static enum Type {
CREATE,
INDEX,
DELETE
}
static enum Origin {
PRIMARY,
REPLICA,
RECOVERY
}
Type opType();
Origin origin();
}
static interface IndexingOperation extends Operation {
ParsedDocument parsedDoc();
List<Document> docs();
DocumentMapper docMapper();
}
static class Create implements IndexingOperation {
private final DocumentMapper docMapper;
private final Term uid;
private final ParsedDocument doc;
private long version = Versions.MATCH_ANY;
private VersionType versionType = VersionType.INTERNAL;
private Origin origin = Origin.PRIMARY;
private long startTime;
private long endTime;
public Create(DocumentMapper docMapper, Term uid, ParsedDocument doc) {
this.docMapper = docMapper;
this.uid = uid;
this.doc = doc;
}
@Override
public DocumentMapper docMapper() {
return this.docMapper;
}
@Override
public Type opType() {
return Type.CREATE;
}
public Create origin(Origin origin) {
this.origin = origin;
return this;
}
@Override
public Origin origin() {
return this.origin;
}
@Override
public ParsedDocument parsedDoc() {
return this.doc;
}
public Term uid() {
return this.uid;
}
public String type() {
return this.doc.type();
}
public String id() {
return this.doc.id();
}
public String routing() {
return this.doc.routing();
}
public long timestamp() {
return this.doc.timestamp();
}
public long ttl() {
return this.doc.ttl();
}
public long version() {
return this.version;
}
public Create version(long version) {
this.version = version;
this.doc.version().setLongValue(version);
return this;
}
public VersionType versionType() {
return this.versionType;
}
public Create versionType(VersionType versionType) {
this.versionType = versionType;
return this;
}
public String parent() {
return this.doc.parent();
}
@Override
public List<Document> docs() {
return this.doc.docs();
}
public Analyzer analyzer() {
return this.doc.analyzer();
}
public BytesReference source() {
return this.doc.source();
}
public Create startTime(long startTime) {
this.startTime = startTime;
return this;
}
/**
* Returns operation start time in nanoseconds.
*/
public long startTime() {
return this.startTime;
}
public Create endTime(long endTime) {
this.endTime = endTime;
return this;
}
/**
* Returns operation end time in nanoseconds.
*/
public long endTime() {
return this.endTime;
}
}
static class Index implements IndexingOperation {
private final DocumentMapper docMapper;
private final Term uid;
private final ParsedDocument doc;
private long version = Versions.MATCH_ANY;
private VersionType versionType = VersionType.INTERNAL;
private Origin origin = Origin.PRIMARY;
private boolean created;
private long startTime;
private long endTime;
public Index(DocumentMapper docMapper, Term uid, ParsedDocument doc) {
this.docMapper = docMapper;
this.uid = uid;
this.doc = doc;
}
@Override
public DocumentMapper docMapper() {
return this.docMapper;
}
@Override
public Type opType() {
return Type.INDEX;
}
public Index origin(Origin origin) {
this.origin = origin;
return this;
}
@Override
public Origin origin() {
return this.origin;
}
public Term uid() {
return this.uid;
}
@Override
public ParsedDocument parsedDoc() {
return this.doc;
}
public Index version(long version) {
this.version = version;
doc.version().setLongValue(version);
return this;
}
/**
* before indexing holds the version requested, after indexing holds the new version of the document.
*/
public long version() {
return this.version;
}
public Index versionType(VersionType versionType) {
this.versionType = versionType;
return this;
}
public VersionType versionType() {
return this.versionType;
}
@Override
public List<Document> docs() {
return this.doc.docs();
}
public Analyzer analyzer() {
return this.doc.analyzer();
}
public String id() {
return this.doc.id();
}
public String type() {
return this.doc.type();
}
public String routing() {
return this.doc.routing();
}
public String parent() {
return this.doc.parent();
}
public long timestamp() {
return this.doc.timestamp();
}
public long ttl() {
return this.doc.ttl();
}
public BytesReference source() {
return this.doc.source();
}
public Index startTime(long startTime) {
this.startTime = startTime;
return this;
}
/**
* Returns operation start time in nanoseconds.
*/
public long startTime() {
return this.startTime;
}
public Index endTime(long endTime) {
this.endTime = endTime;
return this;
}
/**
* Returns operation end time in nanoseconds.
*/
public long endTime() {
return this.endTime;
}
/**
* @return true if object was created
*/
public boolean created() {
return created;
}
public void created(boolean created) {
this.created = created;
}
}
static class Delete implements Operation {
private final String type;
private final String id;
private final Term uid;
private long version = Versions.MATCH_ANY;
private VersionType versionType = VersionType.INTERNAL;
private Origin origin = Origin.PRIMARY;
private boolean found;
private long startTime;
private long endTime;
public Delete(String type, String id, Term uid) {
this.type = type;
this.id = id;
this.uid = uid;
}
@Override
public Type opType() {
return Type.DELETE;
}
public Delete origin(Origin origin) {
this.origin = origin;
return this;
}
@Override
public Origin origin() {
return this.origin;
}
public String type() {
return this.type;
}
public String id() {
return this.id;
}
public Term uid() {
return this.uid;
}
public Delete version(long version) {
this.version = version;
return this;
}
/**
* before delete execution this is the version to be deleted. After this is the version of the "delete" transaction record.
*/
public long version() {
return this.version;
}
public Delete versionType(VersionType versionType) {
this.versionType = versionType;
return this;
}
public VersionType versionType() {
return this.versionType;
}
public boolean found() {
return this.found;
}
public Delete found(boolean found) {
this.found = found;
return this;
}
public Delete startTime(long startTime) {
this.startTime = startTime;
return this;
}
/**
* Returns operation start time in nanoseconds.
*/
public long startTime() {
return this.startTime;
}
public Delete endTime(long endTime) {
this.endTime = endTime;
return this;
}
/**
* Returns operation end time in nanoseconds.
*/
public long endTime() {
return this.endTime;
}
}
static class DeleteByQuery {
private final Query query;
private final BytesReference source;
private final String[] filteringAliases;
private final Filter aliasFilter;
private final String[] types;
private final Filter parentFilter;
private Operation.Origin origin = Operation.Origin.PRIMARY;
private long startTime;
private long endTime;
public DeleteByQuery(Query query, BytesReference source, @Nullable String[] filteringAliases, @Nullable Filter aliasFilter, Filter parentFilter, String... types) {
this.query = query;
this.source = source;
this.types = types;
this.filteringAliases = filteringAliases;
this.aliasFilter = aliasFilter;
this.parentFilter = parentFilter;
}
public Query query() {
return this.query;
}
public BytesReference source() {
return this.source;
}
public String[] types() {
return this.types;
}
public String[] filteringAliases() {
return filteringAliases;
}
public Filter aliasFilter() {
return aliasFilter;
}
public boolean nested() {
return parentFilter != null;
}
public Filter parentFilter() {
return parentFilter;
}
public DeleteByQuery origin(Operation.Origin origin) {
this.origin = origin;
return this;
}
public Operation.Origin origin() {
return this.origin;
}
public DeleteByQuery startTime(long startTime) {
this.startTime = startTime;
return this;
}
/**
* Returns operation start time in nanoseconds.
*/
public long startTime() {
return this.startTime;
}
public DeleteByQuery endTime(long endTime) {
this.endTime = endTime;
return this;
}
/**
* Returns operation end time in nanoseconds.
*/
public long endTime() {
return this.endTime;
}
}
static class Get {
private final boolean realtime;
private final Term uid;
private boolean loadSource = true;
private long version;
private VersionType versionType;
public Get(boolean realtime, Term uid) {
this.realtime = realtime;
this.uid = uid;
}
public boolean realtime() {
return this.realtime;
}
public Term uid() {
return uid;
}
public boolean loadSource() {
return this.loadSource;
}
public Get loadSource(boolean loadSource) {
this.loadSource = loadSource;
return this;
}
public long version() {
return version;
}
public Get version(long version) {
this.version = version;
return this;
}
public VersionType versionType() {
return versionType;
}
public Get versionType(VersionType versionType) {
this.versionType = versionType;
return this;
}
}
static class GetResult {
private final boolean exists;
private final long version;
private final Translog.Source source;
private final Versions.DocIdAndVersion docIdAndVersion;
private final Searcher searcher;
public static final GetResult NOT_EXISTS = new GetResult(false, Versions.NOT_FOUND, null);
public GetResult(boolean exists, long version, @Nullable Translog.Source source) {
this.source = source;
this.exists = exists;
this.version = version;
this.docIdAndVersion = null;
this.searcher = null;
}
public GetResult(Searcher searcher, Versions.DocIdAndVersion docIdAndVersion) {
this.exists = true;
this.source = null;
this.version = docIdAndVersion.version;
this.docIdAndVersion = docIdAndVersion;
this.searcher = searcher;
}
public boolean exists() {
return exists;
}
public long version() {
return this.version;
}
@Nullable
public Translog.Source source() {
return source;
}
public Searcher searcher() {
return this.searcher;
}
public Versions.DocIdAndVersion docIdAndVersion() {
return docIdAndVersion;
}
public void release() {
if (searcher != null) {
searcher.release();
}
}
}
}
| {'content_hash': 'b56fd9c62edb9097466746fdd460ce4b', 'timestamp': '', 'source': 'github', 'line_count': 930, 'max_line_length': 188, 'avg_line_length': 25.789247311827957, 'alnum_prop': 0.567503335557038, 'repo_name': 'libosu/elasticsearch', 'id': 'fa91c5e14a5ef50b7b0a51fd2f33c6d573ce99ba', 'size': '24772', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/elasticsearch/index/engine/Engine.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '9871'}, {'name': 'HTML', 'bytes': '5724'}, {'name': 'Java', 'bytes': '23550632'}, {'name': 'Perl', 'bytes': '5619'}, {'name': 'Python', 'bytes': '25956'}, {'name': 'Ruby', 'bytes': '20614'}, {'name': 'Shell', 'bytes': '21472'}]} |
typedef std::basic_string<wchar_t> UCharString;
#else
typedef std::u16string UCharString;
#endif
namespace peparse {
template <class T>
static std::string to_string(T t, std::ios_base &(*f)(std::ios_base &) ) {
std::ostringstream oss;
oss << f << t;
return oss.str();
}
std::string from_utf16(const UCharString &u);
} // namespace peparse
| {'content_hash': 'ba6f9b076e8df1a0b703ff6e48ba88d4', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 74, 'avg_line_length': 23.133333333333333, 'alnum_prop': 0.69164265129683, 'repo_name': 'trailofbits/pe-parse', 'id': '92933b0428bbe6e0711e46543045070daeaf8c6f', 'size': '421', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'pe-parser-library/include/pe-parse/to_string.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '206578'}, {'name': 'CMake', 'bytes': '23836'}, {'name': 'Dockerfile', 'bytes': '598'}, {'name': 'Python', 'bytes': '7416'}, {'name': 'Shell', 'bytes': '1213'}]} |
<?xml version="1.0"?>
<component>
<component-class>javax.faces.component.UIPanel</component-class>
<base-class>javax.faces.component.UIComponentBase</base-class>
<component-type>javax.faces.Panel</component-type>
<component-family>javax.faces.Panel</component-family>
</component>
| {'content_hash': '121593a55e1530018aa6a7bce2081eaa', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 68, 'avg_line_length': 43.42857142857143, 'alnum_prop': 0.7302631578947368, 'repo_name': 'GIP-RECIA/esco-grouper-ui', 'id': '2d673595a989d453d5595a61ed6a00dd608e87dc', 'size': '304', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ext/bundles/myfaces-api/src/main/java/javax/faces/component/UIPanel.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '218175'}, {'name': 'Java', 'bytes': '6786611'}, {'name': 'JavaScript', 'bytes': '1616913'}, {'name': 'Shell', 'bytes': '3445'}, {'name': 'XSLT', 'bytes': '3601'}]} |
/*
* Minio Client (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"bytes"
"io/ioutil"
"os"
"path/filepath"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
. "gopkg.in/check.v1"
)
func (s *TestSuite) TestCat(c *C) {
/// filesystem
root, err := ioutil.TempDir(os.TempDir(), "cmd-")
c.Assert(err, IsNil)
defer os.RemoveAll(root)
objectPath := filepath.Join(root, "object1")
objectPathServer := server.URL + "/bucket/object1"
data := "hello"
dataLen := len(data)
var perr *probe.Error
perr = putTarget(objectPath, int64(dataLen), bytes.NewReader([]byte(data)))
c.Assert(perr, IsNil)
perr = putTarget(objectPathServer, int64(dataLen), bytes.NewReader([]byte(data)))
c.Assert(perr, IsNil)
var sourceURLs []string
sourceURLs = append(sourceURLs, objectPath)
sourceURLs = append(sourceURLs, objectPathServer)
for _, sourceURL := range sourceURLs {
c.Assert(catURL(sourceURL), IsNil)
}
objectPath = filepath.Join(root, "object2")
c.Assert(catURL(objectPath), Not(IsNil))
}
func (s *TestSuite) TestCatContext(c *C) {
err := app.Run([]string{os.Args[0], "cat", server.URL + "/bucket/object1"})
c.Assert(err, IsNil)
c.Assert(console.IsExited, Equals, false)
// reset back
console.IsExited = false
err = app.Run([]string{os.Args[0], "cat", server.URL + "/invalid"})
c.Assert(err, IsNil)
c.Assert(console.IsExited, Equals, true)
// reset back
console.IsExited = false
}
| {'content_hash': 'bb5a24173587b904de5feac262b59a79', 'timestamp': '', 'source': 'github', 'line_count': 72, 'max_line_length': 82, 'avg_line_length': 27.625, 'alnum_prop': 0.7048768225238814, 'repo_name': 'winchram/mc', 'id': '01300d1edda555326568967d6e0fc4215c596680', 'size': '1989', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'cat_test.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Go', 'bytes': '377986'}, {'name': 'Makefile', 'bytes': '2432'}, {'name': 'Shell', 'bytes': '7035'}]} |
#pragma once
#include <aws/personalize/Personalize_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace Personalize
{
namespace Model
{
/**
* <p>The optional metadata that you apply to resources to help you categorize and
* organize them. Each tag consists of a key and an optional value, both of which
* you define. For more information see <a
* href="https://docs.aws.amazon.com/personalize/latest/dev/tagging-resources.html">Tagging
* Personalize resources</a>. </p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/personalize-2018-05-22/Tag">AWS API
* Reference</a></p>
*/
class AWS_PERSONALIZE_API Tag
{
public:
Tag();
Tag(Aws::Utils::Json::JsonView jsonValue);
Tag& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>One part of a key-value pair that makes up a tag. A key is a general label
* that acts like a category for more specific tag values.</p>
*/
inline const Aws::String& GetTagKey() const{ return m_tagKey; }
/**
* <p>One part of a key-value pair that makes up a tag. A key is a general label
* that acts like a category for more specific tag values.</p>
*/
inline bool TagKeyHasBeenSet() const { return m_tagKeyHasBeenSet; }
/**
* <p>One part of a key-value pair that makes up a tag. A key is a general label
* that acts like a category for more specific tag values.</p>
*/
inline void SetTagKey(const Aws::String& value) { m_tagKeyHasBeenSet = true; m_tagKey = value; }
/**
* <p>One part of a key-value pair that makes up a tag. A key is a general label
* that acts like a category for more specific tag values.</p>
*/
inline void SetTagKey(Aws::String&& value) { m_tagKeyHasBeenSet = true; m_tagKey = std::move(value); }
/**
* <p>One part of a key-value pair that makes up a tag. A key is a general label
* that acts like a category for more specific tag values.</p>
*/
inline void SetTagKey(const char* value) { m_tagKeyHasBeenSet = true; m_tagKey.assign(value); }
/**
* <p>One part of a key-value pair that makes up a tag. A key is a general label
* that acts like a category for more specific tag values.</p>
*/
inline Tag& WithTagKey(const Aws::String& value) { SetTagKey(value); return *this;}
/**
* <p>One part of a key-value pair that makes up a tag. A key is a general label
* that acts like a category for more specific tag values.</p>
*/
inline Tag& WithTagKey(Aws::String&& value) { SetTagKey(std::move(value)); return *this;}
/**
* <p>One part of a key-value pair that makes up a tag. A key is a general label
* that acts like a category for more specific tag values.</p>
*/
inline Tag& WithTagKey(const char* value) { SetTagKey(value); return *this;}
/**
* <p>The optional part of a key-value pair that makes up a tag. A value acts as a
* descriptor within a tag category (key).</p>
*/
inline const Aws::String& GetTagValue() const{ return m_tagValue; }
/**
* <p>The optional part of a key-value pair that makes up a tag. A value acts as a
* descriptor within a tag category (key).</p>
*/
inline bool TagValueHasBeenSet() const { return m_tagValueHasBeenSet; }
/**
* <p>The optional part of a key-value pair that makes up a tag. A value acts as a
* descriptor within a tag category (key).</p>
*/
inline void SetTagValue(const Aws::String& value) { m_tagValueHasBeenSet = true; m_tagValue = value; }
/**
* <p>The optional part of a key-value pair that makes up a tag. A value acts as a
* descriptor within a tag category (key).</p>
*/
inline void SetTagValue(Aws::String&& value) { m_tagValueHasBeenSet = true; m_tagValue = std::move(value); }
/**
* <p>The optional part of a key-value pair that makes up a tag. A value acts as a
* descriptor within a tag category (key).</p>
*/
inline void SetTagValue(const char* value) { m_tagValueHasBeenSet = true; m_tagValue.assign(value); }
/**
* <p>The optional part of a key-value pair that makes up a tag. A value acts as a
* descriptor within a tag category (key).</p>
*/
inline Tag& WithTagValue(const Aws::String& value) { SetTagValue(value); return *this;}
/**
* <p>The optional part of a key-value pair that makes up a tag. A value acts as a
* descriptor within a tag category (key).</p>
*/
inline Tag& WithTagValue(Aws::String&& value) { SetTagValue(std::move(value)); return *this;}
/**
* <p>The optional part of a key-value pair that makes up a tag. A value acts as a
* descriptor within a tag category (key).</p>
*/
inline Tag& WithTagValue(const char* value) { SetTagValue(value); return *this;}
private:
Aws::String m_tagKey;
bool m_tagKeyHasBeenSet = false;
Aws::String m_tagValue;
bool m_tagValueHasBeenSet = false;
};
} // namespace Model
} // namespace Personalize
} // namespace Aws
| {'content_hash': '519288c58101e7a336d988762743a0d5', 'timestamp': '', 'source': 'github', 'line_count': 149, 'max_line_length': 112, 'avg_line_length': 35.43624161073826, 'alnum_prop': 0.6509469696969697, 'repo_name': 'aws/aws-sdk-cpp', 'id': '07679245c76f4841ae02199633d9305ae6ed9dbf', 'size': '5399', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'aws-cpp-sdk-personalize/include/aws/personalize/model/Tag.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '309797'}, {'name': 'C++', 'bytes': '476866144'}, {'name': 'CMake', 'bytes': '1245180'}, {'name': 'Dockerfile', 'bytes': '11688'}, {'name': 'HTML', 'bytes': '8056'}, {'name': 'Java', 'bytes': '413602'}, {'name': 'Python', 'bytes': '79245'}, {'name': 'Shell', 'bytes': '9246'}]} |
@interface IBCollectionSectionHeaderView : NSView{
}
@end
IB_DESIGNABLE
@interface IBCollectionSectionView : NSView{
}
-(void)trackHeaderViewWithVisibleRect:(NSRect)visibleRect;
@property (assign) BOOL hasHeader;
@property (assign) BOOL hasBottom;
@property (strong) IBOutlet NSView *headerView;
@property (strong) IBOutlet NSView *bottomView;
@property (strong) IBInspectable NSString *reuseIdentifier;
@end
| {'content_hash': '6c65fb966d519666c1d19041bc1e2cfa', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 59, 'avg_line_length': 20.238095238095237, 'alnum_prop': 0.7788235294117647, 'repo_name': 'keefo/IBCollectionView', 'id': '2c08a684fc8f27b713995c439f1e5a002a0a6cad', 'size': '646', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'IBCollectionView/Source/IBCollectionSectionView.h', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '303'}, {'name': 'Objective-C', 'bytes': '109693'}]} |
@if(Session::has('flash_message'))
<script>
swal({
title: "{{Session::get('flash_message')}}",
text: "This message will disappear after 2 seconds",
timer: 2000,
showConfirmButton: false
});
</script>
{{Session::forget('flash_message')}}
@endif | {'content_hash': '762d04d36e70ed11c95338d7c64564e4', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 64, 'avg_line_length': 24.692307692307693, 'alnum_prop': 0.5264797507788161, 'repo_name': 'elbadrawy/playlists', 'id': '326f73fa863419112fa60e606fa54226582fc1d2', 'size': '321', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/resources/views/layouts/flashmsg.blade.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '10173'}, {'name': 'HTML', 'bytes': '115039'}, {'name': 'Hack', 'bytes': '983'}, {'name': 'PHP', 'bytes': '621632'}, {'name': 'Vue', 'bytes': '563'}]} |
<?php
namespace Doctrine\DBAL\Query\Expression;
use Doctrine\DBAL\Connection;
/**
* ExpressionBuilder class is responsible to dynamically create SQL query parts.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.com
* @since 2.1
* @author Guilherme Blanco <[email protected]>
* @author Benjamin Eberlei <[email protected]>
*/
class ExpressionBuilder
{
const EQ = '=';
const NEQ = '<>';
const LT = '<';
const LTE = '<=';
const GT = '>';
const GTE = '>=';
/**
* @var Doctrine\DBAL\Connection DBAL Connection
*/
private $connection = null;
/**
* Initializes a new <tt>ExpressionBuilder</tt>.
*
* @param Doctrine\DBAL\Connection $connection DBAL Connection
*/
public function __construct(Connection $connection)
{
$this->connection = $connection;
}
/**
* Creates a conjunction of the given boolean expressions.
*
* Example:
*
* [php]
* // (u.type = ?) AND (u.role = ?)
* $expr->andX('u.type = ?', 'u.role = ?'));
*
* @param mixed $x Optional clause. Defaults = null, but requires
* at least one defined when converting to string.
* @return CompositeExpression
*/
public function andX($x = null)
{
return new CompositeExpression(CompositeExpression::TYPE_AND, func_get_args());
}
/**
* Creates a disjunction of the given boolean expressions.
*
* Example:
*
* [php]
* // (u.type = ?) OR (u.role = ?)
* $qb->where($qb->expr()->orX('u.type = ?', 'u.role = ?'));
*
* @param mixed $x Optional clause. Defaults = null, but requires
* at least one defined when converting to string.
* @return CompositeExpression
*/
public function orX($x = null)
{
return new CompositeExpression(CompositeExpression::TYPE_OR, func_get_args());
}
/**
* Creates a comparison expression.
*
* @param mixed $x Left expression
* @param string $operator One of the ExpressionBuikder::* constants.
* @param mixed $y Right expression
* @return string
*/
public function comparison($x, $operator, $y)
{
return $x . ' ' . $operator . ' ' . $y;
}
/**
* Creates an equality comparison expression with the given arguments.
*
* First argument is considered the left expression and the second is the right expression.
* When converted to string, it will generated a <left expr> = <right expr>. Example:
*
* [php]
* // u.id = ?
* $expr->eq('u.id', '?');
*
* @param mixed $x Left expression
* @param mixed $y Right expression
* @return string
*/
public function eq($x, $y)
{
return $this->comparison($x, self::EQ, $y);
}
/**
* Creates a non equality comparison expression with the given arguments.
* First argument is considered the left expression and the second is the right expression.
* When converted to string, it will generated a <left expr> <> <right expr>. Example:
*
* [php]
* // u.id <> 1
* $q->where($q->expr()->neq('u.id', '1'));
*
* @param mixed $x Left expression
* @param mixed $y Right expression
* @return string
*/
public function neq($x, $y)
{
return $this->comparison($x, self::NEQ, $y);
}
/**
* Creates a lower-than comparison expression with the given arguments.
* First argument is considered the left expression and the second is the right expression.
* When converted to string, it will generated a <left expr> < <right expr>. Example:
*
* [php]
* // u.id < ?
* $q->where($q->expr()->lt('u.id', '?'));
*
* @param mixed $x Left expression
* @param mixed $y Right expression
* @return string
*/
public function lt($x, $y)
{
return $this->comparison($x, self::LT, $y);
}
/**
* Creates a lower-than-equal comparison expression with the given arguments.
* First argument is considered the left expression and the second is the right expression.
* When converted to string, it will generated a <left expr> <= <right expr>. Example:
*
* [php]
* // u.id <= ?
* $q->where($q->expr()->lte('u.id', '?'));
*
* @param mixed $x Left expression
* @param mixed $y Right expression
* @return string
*/
public function lte($x, $y)
{
return $this->comparison($x, self::LTE, $y);
}
/**
* Creates a greater-than comparison expression with the given arguments.
* First argument is considered the left expression and the second is the right expression.
* When converted to string, it will generated a <left expr> > <right expr>. Example:
*
* [php]
* // u.id > ?
* $q->where($q->expr()->gt('u.id', '?'));
*
* @param mixed $x Left expression
* @param mixed $y Right expression
* @return string
*/
public function gt($x, $y)
{
return $this->comparison($x, self::GT, $y);
}
/**
* Creates a greater-than-equal comparison expression with the given arguments.
* First argument is considered the left expression and the second is the right expression.
* When converted to string, it will generated a <left expr> >= <right expr>. Example:
*
* [php]
* // u.id >= ?
* $q->where($q->expr()->gte('u.id', '?'));
*
* @param mixed $x Left expression
* @param mixed $y Right expression
* @return string
*/
public function gte($x, $y)
{
return $this->comparison($x, self::GTE, $y);
}
/**
* Creates an IS NULL expression with the given arguments.
*
* @param string $x Field in string format to be restricted by IS NULL
*
* @return string
*/
public function isNull($x)
{
return $x . ' IS NULL';
}
/**
* Creates an IS NOT NULL expression with the given arguments.
*
* @param string $x Field in string format to be restricted by IS NOT NULL
*
* @return string
*/
public function isNotNull($x)
{
return $x . ' IS NOT NULL';
}
/**
* Creates a LIKE() comparison expression with the given arguments.
*
* @param string $x Field in string format to be inspected by LIKE() comparison.
* @param mixed $y Argument to be used in LIKE() comparison.
*
* @return string
*/
public function like($x, $y)
{
return $this->comparison($x, 'LIKE', $y);
}
/**
* Quotes a given input parameter.
*
* @param mixed $input Parameter to be quoted.
* @param string $type Type of the parameter.
*
* @return string
*/
public function literal($input, $type = null)
{
return $this->connection->quote($input, $type);
}
} | {'content_hash': '69722067865ecfc439ce6929f153f7b2', 'timestamp': '', 'source': 'github', 'line_count': 248, 'max_line_length': 95, 'avg_line_length': 29.778225806451612, 'alnum_prop': 0.5428571428571428, 'repo_name': 'krishcdbry/z-zangura', 'id': '9057675a5ec2f4d2c69273e9c341def9026b2571', 'size': '8375', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'application/libraries/Doctrine/DBAL/Query/Expression/ExpressionBuilder.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '474'}, {'name': 'CSS', 'bytes': '30948'}, {'name': 'HTML', 'bytes': '5396471'}, {'name': 'JavaScript', 'bytes': '59592'}, {'name': 'PHP', 'bytes': '4357353'}]} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.6.0_18) on Thu Dec 18 17:18:36 PST 2014 -->
<title>Uses of Class java.security.spec.InvalidParameterSpecException (Java Platform SE 7 )</title>
<meta name="date" content="2014-12-18">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class java.security.spec.InvalidParameterSpecException (Java Platform SE 7 )";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../java/security/spec/InvalidParameterSpecException.html" title="class in java.security.spec">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><strong>Java™ Platform<br>Standard Ed. 7</strong></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?java/security/spec/class-use/InvalidParameterSpecException.html" target="_top">Frames</a></li>
<li><a href="InvalidParameterSpecException.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class java.security.spec.InvalidParameterSpecException" class="title">Uses of Class<br>java.security.spec.InvalidParameterSpecException</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../java/security/spec/InvalidParameterSpecException.html" title="class in java.security.spec">InvalidParameterSpecException</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#java.security">java.security</a></td>
<td class="colLast">
<div class="block">Provides the classes and interfaces for the security framework.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="java.security">
<!-- -->
</a>
<h3>Uses of <a href="../../../../java/security/spec/InvalidParameterSpecException.html" title="class in java.security.spec">InvalidParameterSpecException</a> in <a href="../../../../java/security/package-summary.html">java.security</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../java/security/package-summary.html">java.security</a> that throw <a href="../../../../java/security/spec/InvalidParameterSpecException.html" title="class in java.security.spec">InvalidParameterSpecException</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>protected abstract <T extends <a href="../../../../java/security/spec/AlgorithmParameterSpec.html" title="interface in java.security.spec">AlgorithmParameterSpec</a>> <br>T</code></td>
<td class="colLast"><span class="strong">AlgorithmParametersSpi.</span><code><strong><a href="../../../../java/security/AlgorithmParametersSpi.html#engineGetParameterSpec(java.lang.Class)">engineGetParameterSpec</a></strong>(<a href="../../../../java/lang/Class.html" title="class in java.lang">Class</a><T> paramSpec)</code>
<div class="block">Returns a (transparent) specification of this parameters
object.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>protected abstract void</code></td>
<td class="colLast"><span class="strong">AlgorithmParametersSpi.</span><code><strong><a href="../../../../java/security/AlgorithmParametersSpi.html#engineInit(java.security.spec.AlgorithmParameterSpec)">engineInit</a></strong>(<a href="../../../../java/security/spec/AlgorithmParameterSpec.html" title="interface in java.security.spec">AlgorithmParameterSpec</a> paramSpec)</code>
<div class="block">Initializes this parameters object using the parameters
specified in <code>paramSpec</code>.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><T extends <a href="../../../../java/security/spec/AlgorithmParameterSpec.html" title="interface in java.security.spec">AlgorithmParameterSpec</a>> <br>T</code></td>
<td class="colLast"><span class="strong">AlgorithmParameters.</span><code><strong><a href="../../../../java/security/AlgorithmParameters.html#getParameterSpec(java.lang.Class)">getParameterSpec</a></strong>(<a href="../../../../java/lang/Class.html" title="class in java.lang">Class</a><T> paramSpec)</code>
<div class="block">Returns a (transparent) specification of this parameter object.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">AlgorithmParameters.</span><code><strong><a href="../../../../java/security/AlgorithmParameters.html#init(java.security.spec.AlgorithmParameterSpec)">init</a></strong>(<a href="../../../../java/security/spec/AlgorithmParameterSpec.html" title="interface in java.security.spec">AlgorithmParameterSpec</a> paramSpec)</code>
<div class="block">Initializes this parameter object using the parameters
specified in <code>paramSpec</code>.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../java/security/spec/InvalidParameterSpecException.html" title="class in java.security.spec">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><strong>Java™ Platform<br>Standard Ed. 7</strong></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?java/security/spec/class-use/InvalidParameterSpecException.html" target="_top">Frames</a></li>
<li><a href="InvalidParameterSpecException.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small><font size="-1"> <a href="http://bugreport.sun.com/bugreport/">Submit a bug or feature</a> <br>For further API reference and developer documentation, see <a href="http://docs.oracle.com/javase/7/docs/index.html" target="_blank">Java SE Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> <a href="../../../../../legal/cpyr.html">Copyright</a> © 1993, 2015, Oracle and/or its affiliates. All rights reserved. </font></small></p>
</body>
</html>
| {'content_hash': 'cf60dab120ba4be507b5baae21253856', 'timestamp': '', 'source': 'github', 'line_count': 183, 'max_line_length': 599, 'avg_line_length': 50.36065573770492, 'alnum_prop': 0.6781684027777778, 'repo_name': 'fbiville/annotation-processing-ftw', 'id': '460073bd47cefdccdb8ff1bee4f8cafbaf6d9408', 'size': '9216', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/java/jdk7/java/security/spec/class-use/InvalidParameterSpecException.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '191178'}, {'name': 'HTML', 'bytes': '63904'}, {'name': 'Java', 'bytes': '107042'}, {'name': 'JavaScript', 'bytes': '246677'}]} |
<?php
$lang['result'] = "Resultaat";
$lang['results'] = "Resultaten";
$lang['data_for_result'] = "Data voor resultaat %s";
$lang['add_result'] = "Voeg resultaat toe";
$lang['result_added'] = "Nieuwe resultaat %s succesvol toegevoegd.";
$lang['edit_result'] = "Bewerk resultaat %s";
$lang['result_edited'] = "Resultaat %s succesvol bewerkt.";
$lang['sure_delete_result'] = "Weet u zeker dat u dit resultaat wilt verwijderen?";
$lang['result_deleted'] = "Resultaat succesvol verwijderd.";
$lang['phasenr'] = "Phase number";
$lang['phase'] = "Phase";
$lang['trial'] = "Trial";
$lang['lookingtime'] = "Lookingtime (in ms)";
$lang['nrlooks'] = "# views";
?> | {'content_hash': '14c422427e30a43beacae452ffeca28c', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 83, 'avg_line_length': 40.05882352941177, 'alnum_prop': 0.6328928046989721, 'repo_name': 'UiL-OTS-labs/babylab-admin', 'id': '2af3677bca6a95a167d3306a0b83ca4b2f4f157d', 'size': '681', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'application/language/english/result_lang.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '44458'}, {'name': 'HTML', 'bytes': '6096'}, {'name': 'Hack', 'bytes': '60'}, {'name': 'JavaScript', 'bytes': '427290'}, {'name': 'PHP', 'bytes': '2634077'}]} |
/* eslint-env node */
const EmberAddon = require('ember-cli/lib/broccoli/ember-addon')
module.exports = function (defaults) {
let app = new EmberAddon(defaults, {
babel: {
optional: ['es7.decorators']
},
sassOptions: {
includePaths: []
},
snippetSearchPaths: [
'addon',
'tests/dummy'
]
})
return app.toTree()
}
| {'content_hash': 'ac800b510ba72bfa989adb16218a5996', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 64, 'avg_line_length': 20.333333333333332, 'alnum_prop': 0.592896174863388, 'repo_name': 'ciena-frost/ember-frost-tabs', 'id': 'e4b2ac80b7cbad87378af38ae0faf23ac6eb89e1', 'size': '366', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ember-cli-build.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '14443'}, {'name': 'HTML', 'bytes': '25643'}, {'name': 'JavaScript', 'bytes': '57993'}, {'name': 'Shell', 'bytes': '2166'}]} |
{
"name": "collection.js",
"url": "https://github.com/kobezzza/Collection.git"
}
| {'content_hash': 'fa1198ff4d21909b519f10ba54ac39c7', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 53, 'avg_line_length': 21.25, 'alnum_prop': 0.6352941176470588, 'repo_name': 'bower/components', 'id': 'd22dad8b0a3b484b107a218b6eaeedebda4bebf5', 'size': '85', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'packages/collection.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': '1C Enterprise', 'bytes': '79'}, {'name': 'C++', 'bytes': '91'}, {'name': 'CSS', 'bytes': '19277'}, {'name': 'CoffeeScript', 'bytes': '1083'}, {'name': 'DIGITAL Command Language', 'bytes': '348'}, {'name': 'Forth', 'bytes': '102'}, {'name': 'GLSL', 'bytes': '252'}, {'name': 'Gnuplot', 'bytes': '89'}, {'name': 'HTML', 'bytes': '1164'}, {'name': 'Haxe', 'bytes': '87'}, {'name': 'Io', 'bytes': '3661'}, {'name': 'JavaScript', 'bytes': '180336'}, {'name': 'Logos', 'bytes': '272'}, {'name': 'Mathematica', 'bytes': '102'}, {'name': 'PHP', 'bytes': '343'}, {'name': 'Pep8', 'bytes': '90'}, {'name': 'Perl 6', 'bytes': '85'}, {'name': 'Propeller Spin', 'bytes': '104'}, {'name': 'Python', 'bytes': '91'}, {'name': 'QMake', 'bytes': '73'}, {'name': 'Roff', 'bytes': '5053'}, {'name': 'Scheme', 'bytes': '78'}, {'name': 'Shell', 'bytes': '292'}, {'name': 'SourcePawn', 'bytes': '98'}, {'name': 'Stata', 'bytes': '84'}, {'name': 'TeX', 'bytes': '73'}, {'name': 'TypeScript', 'bytes': '347'}, {'name': 'XSLT', 'bytes': '96'}]} |
/*global angular, alert */
(function () {
'use strict';
function AutonumericInputTestController() {
var self = this;
self.moneyValue = 12345678;
self.numberValue = 87654321;
self.customSettings = {
aSign: '$',
vMin: 0
};
self.clickButton = function () {
alert('model value is: ' + self.moneyValue);
};
}
function AutonumericConfig(bbAutonumericConfig) {
bbAutonumericConfig.money.aSep = ',';
}
AutonumericConfig.$inject = ['bbAutonumericConfig'];
angular.module('stache')
.config(AutonumericConfig)
.controller('AutonumericInputTestController', AutonumericInputTestController);
}());
| {'content_hash': 'ffe4a5aa5d8ae48e3d67129d73b72494', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 82, 'avg_line_length': 23.483870967741936, 'alnum_prop': 0.6002747252747253, 'repo_name': 'Blackbaud-StacyCarlos/skyux', 'id': '99ffc41ee1a1f1844cae754325ec66d6b8cc9920', 'size': '728', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'js/sky/src/autonumeric/docs/demo.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '594312'}, {'name': 'HTML', 'bytes': '365652'}, {'name': 'JavaScript', 'bytes': '2134086'}, {'name': 'Shell', 'bytes': '6756'}]} |
package org.jabref.logic.bibtex.comparator;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.jabref.logic.bibtex.DuplicateCheck;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.FieldName;
public class BibDatabaseDiff {
private static final double MATCH_THRESHOLD = 0.4;
private final Optional<MetaDataDiff> metaDataDiff;
private final Optional<PreambleDiff> preambleDiff;
private final List<BibStringDiff> bibStringDiffs;
private final List<BibEntryDiff> entryDiffs;
private BibDatabaseDiff(BibDatabaseContext originalDatabase, BibDatabaseContext newDatabase) {
metaDataDiff = MetaDataDiff.compare(originalDatabase.getMetaData(), newDatabase.getMetaData());
preambleDiff = PreambleDiff.compare(originalDatabase, newDatabase);
bibStringDiffs = BibStringDiff.compare(originalDatabase.getDatabase(), newDatabase.getDatabase());
// Sort both databases according to a common sort key.
EntryComparator comparator = getEntryComparator();
List<BibEntry> originalEntriesSorted = originalDatabase.getDatabase().getEntriesSorted(comparator);
List<BibEntry> newEntriesSorted = newDatabase.getDatabase().getEntriesSorted(comparator);
entryDiffs = compareEntries(originalEntriesSorted, newEntriesSorted);
}
private static EntryComparator getEntryComparator() {
EntryComparator comparator = new EntryComparator(false, true, FieldName.TITLE);
comparator = new EntryComparator(false, true, FieldName.AUTHOR, comparator);
comparator = new EntryComparator(false, true, FieldName.YEAR, comparator);
return comparator;
}
private static List<BibEntryDiff> compareEntries(List<BibEntry> originalEntries, List<BibEntry> newEntries) {
List<BibEntryDiff> differences = new ArrayList<>();
// Create pointers that are incremented as the entries of each base are used in
// successive order from the beginning. Entries "further down" in the new database
// can also be matched.
int positionNew = 0;
// Create a HashSet where we can put references to entries in the new
// database that we have matched. This is to avoid matching them twice.
Set<Integer> used = new HashSet<>(newEntries.size());
Set<BibEntry> notMatched = new HashSet<>(originalEntries.size());
// Loop through the entries of the original database, looking for exact matches in the new one.
// We must finish scanning for exact matches before looking for near matches, to avoid an exact
// match being "stolen" from another entry.
mainLoop:
for (BibEntry originalEntry : originalEntries) {
// First check if the similarly placed entry in the other base matches exactly.
if (!used.contains(positionNew) && (positionNew < newEntries.size())) {
double score = DuplicateCheck.compareEntriesStrictly(originalEntry, newEntries.get(positionNew));
if (score > 1) {
used.add(positionNew);
positionNew++;
continue;
}
}
// No? Then check if another entry matches exactly.
for (int i = positionNew + 1; i < newEntries.size(); i++) {
if (!used.contains(i)) {
double score = DuplicateCheck.compareEntriesStrictly(originalEntry, newEntries.get(i));
if (score > 1) {
used.add(i);
continue mainLoop;
}
}
}
// No? Add this entry to the list of non-matched entries.
notMatched.add(originalEntry);
}
// Now we've found all exact matches, look through the remaining entries, looking for close matches.
for (Iterator<BibEntry> iteratorNotMatched = notMatched.iterator(); iteratorNotMatched.hasNext(); ) {
BibEntry originalEntry = iteratorNotMatched.next();
// These two variables will keep track of which entry most closely matches the one we're looking at.
double bestMatch = 0;
int bestMatchIndex = -1;
if (positionNew < (newEntries.size() - 1)) {
for (int i = positionNew; i < newEntries.size(); i++) {
if (!used.contains(i)) {
double score = DuplicateCheck.compareEntriesStrictly(originalEntry, newEntries.get(i));
if (score > bestMatch) {
bestMatch = score;
bestMatchIndex = i;
}
}
}
}
if (bestMatch > MATCH_THRESHOLD) {
used.add(bestMatchIndex);
iteratorNotMatched.remove();
differences.add(new BibEntryDiff(originalEntry, newEntries.get(bestMatchIndex)));
} else {
differences.add(new BibEntryDiff(originalEntry, null));
}
}
// Finally, look if there are still untouched entries in the new database. These may have been added.
for (int i = 0; i < newEntries.size(); i++) {
if (!used.contains(i)) {
differences.add(new BibEntryDiff(null, newEntries.get(i)));
}
}
return differences;
}
public static BibDatabaseDiff compare(BibDatabaseContext base, BibDatabaseContext changed) {
return new BibDatabaseDiff(base, changed);
}
public Optional<MetaDataDiff> getMetaDataDifferences() {
return metaDataDiff;
}
public Optional<PreambleDiff> getPreambleDifferences() {
return preambleDiff;
}
public List<BibStringDiff> getBibStringDifferences() {
return bibStringDiffs;
}
public List<BibEntryDiff> getEntryDifferences() {
return entryDiffs;
}
}
| {'content_hash': 'd3e4f7f1ead44df49ddcd05c78079efd', 'timestamp': '', 'source': 'github', 'line_count': 143, 'max_line_length': 113, 'avg_line_length': 42.87412587412587, 'alnum_prop': 0.633991192301419, 'repo_name': 'oscargus/jabref', 'id': '3f69c530a214db495397ead1e062905cd6bd933a', 'size': '6131', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/jabref/logic/bibtex/comparator/BibDatabaseDiff.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ANTLR', 'bytes': '1751'}, {'name': 'CSS', 'bytes': '5934'}, {'name': 'GAP', 'bytes': '1492'}, {'name': 'Java', 'bytes': '6171506'}, {'name': 'Perl', 'bytes': '9622'}, {'name': 'Python', 'bytes': '17912'}, {'name': 'Ruby', 'bytes': '1115'}, {'name': 'Shell', 'bytes': '4075'}, {'name': 'TeX', 'bytes': '303509'}, {'name': 'XSLT', 'bytes': '2185'}]} |
<!-- CSS goes in the document HEAD or added to your external stylesheet -->
<style type="text/css">
table.gridtable {
font-family: verdana,arial,sans-serif;
font-size:11px;
color:#333333;
border-width: 1px;
border-color: #666666;
border-collapse: collapse;
}
table.gridtable th {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
background-color: #dedede;
}
table.gridtable td {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
background-color: #ffffff;
}
</style>
<!-- Table goes in the document BODY -->
<table class="gridtable">
<tr>
<th>Info Header 1</th><th>Info Header 2</th><th>Info Header 3</th>
</tr>
<tr>
<td>Text 1A</td><td>Text 1B</td><td>Text 1C</td>
</tr>
<tr>
<td>Text 2A</td><td>Text 2B</td><td>Text 2C</td>
</tr>
</table>
| {'content_hash': 'ae9b3934e8b040cc3b7d180bf1bbb093', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 75, 'avg_line_length': 21.473684210526315, 'alnum_prop': 0.6764705882352942, 'repo_name': 'notinmood/basiclibrary', 'id': 'a0c725246687d0f4a083ad91c1c612527b09cc34', 'size': '816', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Resource/好看的CSS样式表格.html', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
'use strict';
var Grid = require('gridfs-stream');
// The Package is past automatically as first parameter
module.exports = function(Admin, app, auth, database) {
var gfs = new Grid(database.connection.connections[0].db, database.connection.mongo);
var mean = require('meanio');
//Setting up the users api
var users = require('../controllers/users');
app.get('/admin/users', auth.requiresAdmin, users.all);
app.post('/admin/users', auth.requiresAdmin, users.create);
app.put('/admin/users/:userId', auth.requiresAdmin, users.update);
app.delete('/admin/users/:userId', auth.requiresAdmin, users.destroy);
//Setting up the users api
var themes = require('../controllers/themes');
app.get('/admin/themes', auth.requiresAdmin, function(req, res) {
themes.save(req, res, gfs);
});
app.get('/admin/themes/defaultTheme', auth.requiresAdmin, function(req, res) {
themes.defaultTheme(req, res, gfs);
});
app.get('/admin/themes/defaultTheme', auth.requiresAdmin, function(req, res) {
themes.defaultTheme(req, res, gfs);
});
app.get('/admin/modules', auth.requiresAdmin, function(req, res) {
var modules = {};
for (var name in mean.modules)
modules[name] = mean.modules[name];
res.jsonp(modules);
});
var settings = require('../controllers/settings');
app.get('/admin/settings', auth.requiresAdmin, settings.get);
app.put('/admin/settings', auth.requiresAdmin, settings.save);
app.get('/admin/professions', auth.requiresAdmin, function (req, res, next) {
console.log('Admin: Professions');
next();
});
app.get('/admin/realms', auth.requiresAdmin, function (req, res, next) {
console.log('Admin: Realms');
next();
});
//Setting up the log api
var logs = require('../controllers/logs');
app.get('/admin/logs', auth.requiresAdmin, logs.get);
}; | {'content_hash': 'd48688acb2876204f1d8051e57fc7c9d', 'timestamp': '', 'source': 'github', 'line_count': 53, 'max_line_length': 89, 'avg_line_length': 36.679245283018865, 'alnum_prop': 0.6424897119341564, 'repo_name': 'joshharbaugh/wowpro', 'id': 'cb769f7e60581ba0f3e98c3d60261b754cedb7fa', 'size': '1944', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'packages/contrib/mean-admin/server/routes/index.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '150313'}, {'name': 'HTML', 'bytes': '40042'}, {'name': 'JavaScript', 'bytes': '266564'}]} |
#ifndef __NYRA_NES_MEMORY_NROM_H__
#define __NYRA_NES_MEMORY_NROM_H__
#include <nes/MemorySystem.h>
#include <nes/Memory.h>
#include <nes/PPURegisters.h>
#include <nes/Constants.h>
namespace nyra
{
namespace nes
{
class MemoryNROM : public MemorySystem
{
public:
MemoryNROM(const ROMBanks& prgROM,
PPURegisters& ppu,
APU& apu,
Controller& controller1,
Controller& controller2);
};
}
}
#endif
| {'content_hash': '0c9ba484f11071514ef14ba7a14c5774', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 40, 'avg_line_length': 18.36, 'alnum_prop': 0.6361655773420479, 'repo_name': 'LCClyde/NyraEmulationSystem', 'id': '367a6e557511152d2dddcff27e60696f5beed1b8', 'size': '1758', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'include/nes/MemoryNROM.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '169785'}, {'name': 'CMake', 'bytes': '783'}, {'name': 'Python', 'bytes': '11474'}]} |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../../style.css');
@import url('../../../../../tree.css');
</style>
<script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../../clover.js" type="text/javascript"></script>
<script src="../../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../../cloud.js" type="text/javascript"></script>
<title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title>
</head>
<body>
<div id="page">
<header id="header" role="banner">
<nav class="aui-header aui-dropdown2-trigger-group" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo aui-header-logo-clover">
<a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a>
</h1>
</div>
<div class="aui-header-secondary">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online documentation" target="_blank"
href="http://openclover.org/documentation">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="aui-page-panel-inner">
<div class="aui-page-panel-nav aui-page-panel-nav-clover">
<div class="aui-page-header-inner" style="margin-bottom: 20px;">
<div class="aui-page-header-image">
<a href="http://cardatechnologies.com" target="_top">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</a>
</div>
<div class="aui-page-header-main" >
<h1>
<a href="http://cardatechnologies.com" target="_top">
ABA Route Transit Number Validator 1.0.1-SNAPSHOT
</a>
</h1>
</div>
</div>
<nav class="aui-navgroup aui-navgroup-vertical">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading packages-nav-heading">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui package-filter-container">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="package-filter-no-results-message hidden">
<small>No results found.</small>
</p>
<div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator">
<div class="packages-tree-container"></div>
<div class="clover-packages-lozenges"></div>
</div>
</div>
</div>
</nav> </div>
<section class="aui-page-panel-content">
<div class="aui-page-panel-content-clover">
<div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li>
<li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li>
<li><a href="test-Test_AbaRouteValidator_13a.html">Class Test_AbaRouteValidator_13a</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_25206_bad
</h1>
<table class="aui">
<thead>
<tr>
<th>Test</th>
<th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th>
<th><label title="When the test execution was started">Start time</label></th>
<th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th>
<th><label title="A failure or error message if the test is not successful.">Message</label></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_13a.html?line=5009#src-5009" >testAbaNumberCheck_25206_bad</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:42:05
</td>
<td>
0.0 </td>
<td>
<div></div>
<div class="errorMessage"></div>
</td>
</tr>
</tbody>
</table>
<div> </div>
<table class="aui aui-table-sortable">
<thead>
<tr>
<th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th>
<th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_25206_bad</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/exceptions/AbaRouteValidationException.html?id=42777#AbaRouteValidationException" title="AbaRouteValidationException" name="sl-43">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</a>
</td>
<td>
<span class="sortValue">0.5714286</span>57.1%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td>
</tr>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/ErrorCodes.html?id=42777#ErrorCodes" title="ErrorCodes" name="sl-42">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</a>
</td>
<td>
<span class="sortValue">0.5714286</span>57.1%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td>
</tr>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=42777#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.29411766</span>29.4%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="29.4% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:29.4%"></div></div></div> </td>
</tr>
</tbody>
</table>
</div> <!-- class="aui-page-panel-content-clover" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1
on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT.
</li>
</ul>
<ul>
<li>OpenClover is free and open-source software. </li>
</ul>
</section>
</footer> </section> <!-- class="aui-page-panel-content" -->
</div> <!-- class="aui-page-panel-inner" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html> | {'content_hash': 'fda4775c8d998b86134437aece5299ca', 'timestamp': '', 'source': 'github', 'line_count': 235, 'max_line_length': 359, 'avg_line_length': 46.757446808510636, 'alnum_prop': 0.5303967965052785, 'repo_name': 'dcarda/aba.route.validator', 'id': '53e91d3b56496f6f78d3ecae865af38b6142573f', 'size': '10988', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_13a_testAbaNumberCheck_25206_bad_x09.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '18715254'}]} |
1. EDAC memory and PCI errors counters
2. Ext4 sysfs error counters -- since 3.18 -- http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=52c198c6820f68b6fbe1d83f76e34a82bf736024
3. Network interfaces error counters
4. IPMI SEL (list/elist)
| {'content_hash': '2e47545e1004bc74457fe0923dfcbeb4', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 160, 'avg_line_length': 65.5, 'alnum_prop': 0.7938931297709924, 'repo_name': 'lesovsky/uber-scripts', 'id': '72c231ca1848537765c6ef3f07e1f54a0936028e', 'size': '279', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'checklists/errors-checklist.sh', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '1312'}, {'name': 'PLpgSQL', 'bytes': '9087'}, {'name': 'Python', 'bytes': '1137'}, {'name': 'Shell', 'bytes': '91533'}, {'name': 'Smalltalk', 'bytes': '62122'}]} |
"""Test the wrapping of vtkCommand
The following vtkCommmand functionality must be tested
- Event enum constants
- Event names
Created on Mar 22, 2012 by David Gobbi
Updated on Feb 12, 2014 by Jean-Christophe Fillion-Robin
"""
import sys
import gc
import vtk
from vtk.test import Testing
class callback:
def __init__(self):
self.reset()
def __call__(self, o, e, d = None):
self.caller = o
self.event = e
self.calldata = d
def reset(self):
self.caller = None
self.event = None
self.calldata = None
class TestCommand(Testing.vtkTest):
def testEnumConstants(self):
"""Make sure the event id constants are wrapped
"""
self.assertEqual(vtk.vtkCommand.ErrorEvent, 39)
def testCommandWithArgs(self):
"""Test binding a command that has arguments.
"""
cb = callback()
o = vtk.vtkObject()
o.AddObserver(vtk.vtkCommand.ModifiedEvent, cb)
o.Modified()
self.assertEqual(cb.caller, o)
self.assertEqual(cb.event, "ModifiedEvent")
def testUseEventNameString(self):
"""Test binding with a string event name.
"""
cb = callback()
o = vtk.vtkObject()
o.AddObserver("ModifiedEvent", cb)
o.Modified()
self.assertEqual(cb.caller, o)
self.assertEqual(cb.event, "ModifiedEvent")
def testPriorityArg(self):
"""Test the optional priority argument
"""
cb = callback()
o = vtk.vtkObject()
o.AddObserver(vtk.vtkCommand.ModifiedEvent, cb, 0.5)
o.Modified()
self.assertEqual(cb.caller, o)
def testRemoveCommand(self):
"""Test the removal of an observer.
"""
cb = callback()
o = vtk.vtkObject()
o.AddObserver(vtk.vtkCommand.ModifiedEvent, cb)
o.Modified()
self.assertEqual(cb.caller, o)
o.RemoveObservers(vtk.vtkCommand.ModifiedEvent)
cb.caller = None
cb.event = None
o.Modified()
self.assertEqual(cb.caller, None)
def testGetCommand(self):
"""Test getting the vtkCommand object
"""
cb = callback()
o = vtk.vtkObject()
n = o.AddObserver(vtk.vtkCommand.ModifiedEvent, cb)
o.Modified()
self.assertEqual(cb.caller, o)
c = o.GetCommand(n)
self.assertEqual((c.IsA("vtkCommand") != 0), True)
# in the future, o.RemoveObserver(c) should also be made to work
o.RemoveObserver(n)
cb.caller = None
cb.event = None
o.Modified()
self.assertEqual(cb.caller, None)
def testCommandCircularRef(self):
"""Test correct reference loop reporting for commands
"""
cb = callback()
o = vtk.vtkObject()
o.AddObserver(vtk.vtkCommand.ModifiedEvent, cb)
cb.circular_ref = o
# referent to check if "o" is deleted
referent = vtk.vtkObject()
o.referent = referent
# make sure gc removes referer "o" from referent
s1 = repr(gc.get_referrers(referent))
del o
del cb
gc.collect()
s2 = repr(gc.get_referrers(referent))
self.assertNotEqual(s1, s2)
self.assertNotEqual(s1.count("vtkObject"),0)
self.assertEqual(s2.count("vtkObject"),0)
def testAddRemoveObservers(self):
"""Test adding and removing observers
"""
cb = callback()
cb2 = callback()
o = vtk.vtkObject()
n = o.AddObserver(vtk.vtkCommand.ModifiedEvent, cb)
n2 = o.AddObserver(vtk.vtkCommand.ModifiedEvent, cb2)
o.Modified()
self.assertEqual(cb.caller, o)
self.assertEqual(cb2.caller, o)
o.RemoveObserver(n)
cb.reset()
cb2.reset()
o.Modified()
self.assertEqual(cb.caller, None)
self.assertEqual(cb2.caller, o)
o.RemoveObserver(n2)
cb.reset()
cb2.reset()
o.Modified()
self.assertEqual(cb.caller, None)
self.assertEqual(cb2.caller, None)
def testUseCallDataType(self):
"""Test adding an observer associated with a callback expecting a CallData
"""
cb = callback()
cb.CallDataType = vtk.VTK_STRING
lt = vtk.vtkLookupTable()
lt.AddObserver(vtk.vtkCommand.ErrorEvent, cb)
lt.SetTableRange(2, 1)
self.assertEqual(cb.caller, lt)
self.assertEqual(cb.event, "ErrorEvent")
self.assertTrue(cb.calldata.startswith("ERROR: In"))
def testUseCallDataTypeWithDecoratorAsString0(self):
"""Test adding an observer associated with a callback expecting a CallData.
This test ensures backward compatibility checking the CallDataType can
be set to the string 'string0'.
"""
self.onErrorCalldata = ''
@vtk.calldata_type('string0')
def onError(caller, event, calldata):
self.onErrorCalldata = calldata
lt = vtk.vtkLookupTable()
lt.AddObserver(vtk.vtkCommand.ErrorEvent, onError)
lt.SetTableRange(2, 1)
self.assertTrue(self.onErrorCalldata.startswith("ERROR: In"))
def testUseCallDataTypeWithDecorator(self):
"""Test adding an observer associated with a callback expecting a CallData
"""
self.onErrorCalldata = ''
@vtk.calldata_type(vtk.VTK_STRING)
def onError(caller, event, calldata):
self.onErrorCalldata = calldata
lt = vtk.vtkLookupTable()
lt.AddObserver(vtk.vtkCommand.ErrorEvent, onError)
lt.SetTableRange(2, 1)
self.assertTrue(self.onErrorCalldata.startswith("ERROR: In"))
if __name__ == "__main__":
Testing.main([(TestCommand, 'test')])
| {'content_hash': 'f863a807f0735f4ce65c21691a2d379e', 'timestamp': '', 'source': 'github', 'line_count': 188, 'max_line_length': 83, 'avg_line_length': 31.648936170212767, 'alnum_prop': 0.5892436974789916, 'repo_name': 'hlzz/dotfiles', 'id': 'c4c8a56addfb3942547fa97264dc713e8696128c', 'size': '5950', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'graphics/VTK-7.0.0/Common/Core/Testing/Python/TestCommand.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'AppleScript', 'bytes': '1240'}, {'name': 'Arc', 'bytes': '38'}, {'name': 'Assembly', 'bytes': '449468'}, {'name': 'Batchfile', 'bytes': '16152'}, {'name': 'C', 'bytes': '102303195'}, {'name': 'C++', 'bytes': '155056606'}, {'name': 'CMake', 'bytes': '7200627'}, {'name': 'CSS', 'bytes': '179330'}, {'name': 'Cuda', 'bytes': '30026'}, {'name': 'D', 'bytes': '2152'}, {'name': 'Emacs Lisp', 'bytes': '14892'}, {'name': 'FORTRAN', 'bytes': '5276'}, {'name': 'Forth', 'bytes': '3637'}, {'name': 'GAP', 'bytes': '14495'}, {'name': 'GLSL', 'bytes': '438205'}, {'name': 'Gnuplot', 'bytes': '327'}, {'name': 'Groff', 'bytes': '518260'}, {'name': 'HLSL', 'bytes': '965'}, {'name': 'HTML', 'bytes': '2003175'}, {'name': 'Haskell', 'bytes': '10370'}, {'name': 'IDL', 'bytes': '2466'}, {'name': 'Java', 'bytes': '219109'}, {'name': 'JavaScript', 'bytes': '1618007'}, {'name': 'Lex', 'bytes': '119058'}, {'name': 'Lua', 'bytes': '23167'}, {'name': 'M', 'bytes': '1080'}, {'name': 'M4', 'bytes': '292475'}, {'name': 'Makefile', 'bytes': '7112810'}, {'name': 'Matlab', 'bytes': '1582'}, {'name': 'NSIS', 'bytes': '34176'}, {'name': 'Objective-C', 'bytes': '65312'}, {'name': 'Objective-C++', 'bytes': '269995'}, {'name': 'PAWN', 'bytes': '4107117'}, {'name': 'PHP', 'bytes': '2690'}, {'name': 'Pascal', 'bytes': '5054'}, {'name': 'Perl', 'bytes': '485508'}, {'name': 'Pike', 'bytes': '1338'}, {'name': 'Prolog', 'bytes': '5284'}, {'name': 'Python', 'bytes': '16799659'}, {'name': 'QMake', 'bytes': '89858'}, {'name': 'Rebol', 'bytes': '291'}, {'name': 'Ruby', 'bytes': '21590'}, {'name': 'Scilab', 'bytes': '120244'}, {'name': 'Shell', 'bytes': '2266191'}, {'name': 'Slash', 'bytes': '1536'}, {'name': 'Smarty', 'bytes': '1368'}, {'name': 'Swift', 'bytes': '331'}, {'name': 'Tcl', 'bytes': '1911873'}, {'name': 'TeX', 'bytes': '11981'}, {'name': 'Verilog', 'bytes': '3893'}, {'name': 'VimL', 'bytes': '595114'}, {'name': 'XSLT', 'bytes': '62675'}, {'name': 'Yacc', 'bytes': '307000'}, {'name': 'eC', 'bytes': '366863'}]} |
I would like to give big thanks to the following contributors:
* [@aca02djr](https://github.com/aca02djr)
* [@adgrafik](https://github.com/adgrafik)
* [@AdwinTrave](https://github.com/AdwinTrave)
* [@AlaskanShade](https://github.com/AlaskanShade)
* [@alavers](https://github.com/alavers)
* [@Azuka](https://github.com/Azuka)
* [@beeglebug](https://github.com/beeglebug)
* [@blackfyre](https://github.com/blackfyre)
* [@CeRBeR666](https://github.com/CeRBeR666)
* [@dlucazeau](https://github.com/dlucazeau)
* [@dokterpasta](https://github.com/dokterpasta)
* [@easonhan007](https://github.com/easonhan007)
* [@emilchristensen](https://github.com/emilchristensen)
* [@ericnakagawa](https://github.com/ericnakagawa)
* [@evilchili](https://github.com/evilchili)
* [@Francismori7](https://github.com/Francismori7)
* [@gercheq](https://github.com/gercheq)
* [@grzesiek](https://github.com/grzesiek)
* [@henningda](https://github.com/henningda)
* [@ikanedo](https://github.com/ikanedo)
* [@iplus](https://github.com/iplus)
* [@jcnmulio](https://github.com/jcnmulio)
* [@jjshoe](https://github.com/jjshoe)
* [@johanronn77](https://github.com/johanronn77)
* [@jswale](https://github.com/jswale)
* [@jzhang6](https://github.com/jzhang6)
* [@khangvm53](https://github.com/khangvm53)
* [@kristian-puccio](https://github.com/kristian-puccio)
* [@lloydde](https://github.com/lloydde)
* [@logemann](https://github.com/logemann)
* [@manish-in-java](https://github.com/manish-in-java)
* [@maramazza](https://github.com/maramazza)
* [@marceloampuerop6](https://github.com/marceloampuerop6)
* [@marcuscarvalho6](https://github.com/marcuscarvalho6)
* [@MartinDevillers](https://github.com/MartinDevillers)
* [@mike1e](https://github.com/mike1e)
* [@mraiur](https://github.com/mraiur)
* [@MrC0mm0n](https://github.com/MrC0mm0n)
* [@mrpollo](https://github.com/mrpollo)
* [@narutosanjiv](https://github.com/narutosanjiv)
* [@nathanrosspowell](https://github.com/nathanrosspowell)
* [@patmoore](https://github.com/patmoore)
* [@phillprice](https://github.com/phillprice)
* [@pRieStaKos](https://github.com/pRieStaKos)
* [@smeagol74](https://github.com/smeagol74)
* [@thisisclement](https://github.com/thisisclement)
* [@tiagofontella](https://github.com/tiagofontella)
* [@tomByrer](https://github.com/tomByrer)
* [@troymccabe](https://github.com/troymccabe)
* [@tureki](https://github.com/tureki)
* [@vadail](https://github.com/vadail)
* [@vaz](https://github.com/vaz)
* ... might be you! Let's [fork](https://github.com/nghuuphuoc/bootstrapvalidator/fork) and pull a request!
| {'content_hash': 'f1d54e31a55acf75481af211e24ef657', 'timestamp': '', 'source': 'github', 'line_count': 55, 'max_line_length': 107, 'avg_line_length': 46.43636363636364, 'alnum_prop': 0.716523101018011, 'repo_name': 'xiguaaxigua/xiguaaxigua', 'id': '6cebff371b58cb8168daaf1073eb43cf20efc1d8', 'size': '2570', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'BootstrapValid/CONTRIBUTORS.md', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '495581'}, {'name': 'HTML', 'bytes': '4344325'}, {'name': 'JavaScript', 'bytes': '1267511'}, {'name': 'PHP', 'bytes': '155172'}, {'name': 'Python', 'bytes': '1249'}, {'name': 'Ruby', 'bytes': '590'}, {'name': 'Smarty', 'bytes': '29'}]} |
<?php
class flowClassAction extends runtAction
{
public function pipeiAction()
{
m('flow')->repipei();
echo 'success';
}
} | {'content_hash': '24fb518735ed7ac61cd7366d251d683a', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 40, 'avg_line_length': 14.333333333333334, 'alnum_prop': 0.6821705426356589, 'repo_name': 'yaoxf/waterCup', 'id': 'b1bd49e17eb635bf1871cc15f379fe0dffa6f1de', 'size': '129', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'xhxtbgxt_A5/xinhu_utf8_1.5.7/webmain/task/runt/flowAction.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '117152'}, {'name': 'HTML', 'bytes': '318406'}, {'name': 'JavaScript', 'bytes': '478628'}, {'name': 'PHP', 'bytes': '2096056'}]} |
package collections.platzhalter;
public interface Inter {
}
| {'content_hash': '7a350c4ff96a8777fd25c9131793cf9a', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 32, 'avg_line_length': 13.4, 'alnum_prop': 0.7313432835820896, 'repo_name': 'hemmerling/java-114014', 'id': 'b0b7509d6ed99fa5d5ab1b73aceb660f46355893', 'size': '67', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/collections/platzhalter/Inter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '399'}, {'name': 'Java', 'bytes': '216203'}]} |
package com.yummynoodlebar.core.domain;
public class Customer {
private String name;
private String streetAdress;
private String city;
private String postalCode;
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreetAdress() {
return streetAdress;
}
public void setStreetAdress(String streetAdress) {
this.streetAdress = streetAdress;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| {'content_hash': '6f799933213c8d835148d62a5fb48aed', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 52, 'avg_line_length': 17.023809523809526, 'alnum_prop': 0.6867132867132867, 'repo_name': 'leituo56/BrushUp', 'id': '1afb8f3a74dd787604be5a73adaf26f0f8489ea8', 'size': '715', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'Java/Hi-Spring/website/src/main/java/com/yummynoodlebar/core/domain/Customer.java', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '489'}, {'name': 'CSS', 'bytes': '12544'}, {'name': 'HTML', 'bytes': '35436'}, {'name': 'Hack', 'bytes': '2170'}, {'name': 'Java', 'bytes': '63446'}, {'name': 'JavaScript', 'bytes': '187513'}, {'name': 'PHP', 'bytes': '5487'}]} |
namespace djinni_generated {
class NativeTimerListener final : ::djinni::JniInterface<::cpptimer::TimerListener, NativeTimerListener> {
public:
using CppType = std::shared_ptr<::cpptimer::TimerListener>;
using JniType = jobject;
using Boxed = NativeTimerListener;
~NativeTimerListener();
static CppType toCpp(JNIEnv* jniEnv, JniType j) { return ::djinni::JniClass<NativeTimerListener>::get()._fromJava(jniEnv, j); }
static ::djinni::LocalRef<JniType> fromCpp(JNIEnv* jniEnv, const CppType& c) { return {jniEnv, ::djinni::JniClass<NativeTimerListener>::get()._toJava(jniEnv, c)}; }
private:
NativeTimerListener();
friend ::djinni::JniClass<NativeTimerListener>;
friend ::djinni::JniInterface<::cpptimer::TimerListener, NativeTimerListener>;
class JavaProxy final : ::djinni::JavaProxyCacheEntry, public ::cpptimer::TimerListener
{
public:
JavaProxy(JniType j);
~JavaProxy();
void TimerTicked(int32_t seconds_remaining) override;
void TimerEnded() override;
private:
friend ::djinni::JniInterface<::cpptimer::TimerListener, ::djinni_generated::NativeTimerListener>;
};
const ::djinni::GlobalRef<jclass> clazz { ::djinni::jniFindClass("com/mycompany/cpptimer/TimerListener") };
const jmethodID method_timerTicked { ::djinni::jniGetMethodID(clazz.get(), "timerTicked", "(I)V") };
const jmethodID method_timerEnded { ::djinni::jniGetMethodID(clazz.get(), "timerEnded", "()V") };
};
} // namespace djinni_generated
| {'content_hash': '9489cdefe5cec31df672253e1b8d3642', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 168, 'avg_line_length': 40.21052631578947, 'alnum_prop': 0.7041884816753927, 'repo_name': 'spanndemic/cpp-timer', 'id': '700b357664cebea9bbafffde1a61ac3ae448da2c', 'size': '1697', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'generated-src/jni/NativeTimerListener.hpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C++', 'bytes': '8484'}, {'name': 'Java', 'bytes': '1627'}, {'name': 'Objective-C', 'bytes': '5088'}, {'name': 'Objective-C++', 'bytes': '3223'}, {'name': 'Shell', 'bytes': '784'}]} |
/*
ONOS GUI -- Masthead Module
*/
(function () {
'use strict';
// configuration
var mastHeight = 48,
padMobile = 16,
dialogOpts = {
edge: 'left'
};
var ls;
// In the case of Masthead, we cannot cache the lion bundle, because we
// call too early (before the lion data is uploaded from the server).
// So we'll dig into the lion service for each request...
function getLion(x) {
var lion = ls.bundle('core.fw.Mast');
return lion(x);
}
angular.module('onosMast', ['onosNav'])
.controller('MastCtrl',
['$log', '$scope', '$location', '$window', 'WebSocketService',
'NavService', 'DialogService', 'LionService',
function ($log, $scope, $location, $window, wss, ns, ds, _ls_) {
var self = this;
ls = _ls_;
$scope.lion = getLion;
function triggerRefresh(action) {
var uicomp = action === 'add' ? getLion('uicomp_added')
: getLion('uicomp_removed'),
okupd = getLion('ui_ok_to_update');
function createConfirmationText() {
var content = ds.createDiv();
content.append('p').text(uicomp + ' ' + okupd);
return content;
}
function dOk() {
$log.debug('Refreshing GUI');
$window.location.reload();
}
function dCancel() {
$log.debug('Canceling GUI refresh');
}
// NOTE: We use app-dialog (CSS) since we will most likely
// invoke this when we (de)activate apps.
// However we have added this to the masthead, because
// apps could be injected externally (via the onos-app
// command) and we might be looking at some other view.
ds.openDialog('app-dialog', dialogOpts)
.setTitle(getLion('confirm_refresh_title'))
.addContent(createConfirmationText())
.addOk(dOk)
.addCancel(dCancel)
.bindKeys();
}
wss.bindHandlers({
'guiAdded': function () { triggerRefresh('add') },
'guiRemoved': function () { triggerRefresh('rem') }
});
// delegate to NavService
self.toggleNav = function () {
ns.toggleNav();
};
// onosUser is a global set via the index.html generated source
$scope.username = function () {
return onosUser || getLion('unknown_user');
};
// The problem with the following is that the localization bundle
// hasn't been uploaded from the server at this point, so we get
// a lookup miss => '%tt_help%'
// $scope.helpTip = getLion('tt_help');
// We would need to figure out how to inject the text later.
// For now, we'll just leave the tooltip blank.
$scope.helpTip = '';
$scope.directTo = function () {
var curId = $location.path().replace('/', ''),
viewMap = $scope.onos['viewMap'],
helpUrl = viewMap[curId];
$window.open(helpUrl);
};
$log.log('MastCtrl has been created');
}])
// also define a service to allow lookup of mast height.
.factory('MastService', ['FnService', function (fs) {
return {
mastHeight: function () {
return fs.isMobile() ? mastHeight + padMobile : mastHeight;
}
}
}]);
}());
| {'content_hash': '01aa27836d7839310c3b5ae9a7bcfa6a', 'timestamp': '', 'source': 'github', 'line_count': 113, 'max_line_length': 79, 'avg_line_length': 34.39823008849557, 'alnum_prop': 0.4795472086441986, 'repo_name': 'LorenzReinhart/ONOSnew', 'id': 'ae7c81b47c4cd4bc229c204922c55d279320972f', 'size': '4504', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'web/gui/src/main/webapp/app/fw/mast/mast.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '224030'}, {'name': 'HTML', 'bytes': '108368'}, {'name': 'Java', 'bytes': '34148438'}, {'name': 'JavaScript', 'bytes': '3833411'}, {'name': 'Protocol Buffer', 'bytes': '13730'}, {'name': 'Python', 'bytes': '185205'}, {'name': 'Shell', 'bytes': '2594'}]} |
package bdd
import (
"errors"
"testing"
)
var errMatcherTests = []matcherTest{
// Panics
{
result(func() {
panic("stay calm! not!")
}, Panics),
Result{Success: true},
},
// HasOccurred
{
result(errors.New("an error"), HasOccurred),
Result{Success: true},
},
{
result(nil, HasOccurred),
Result{
FailureMessage: "expected an error to have occured. Got: <nil>: nil",
NegatedFailureMessage: "expected an error to have occured. Got: <nil>: nil",
},
},
// ErrorContains
{
result(errors.New("database error"), ErrorContains, "database"),
Result{Success: true},
},
{
result(nil, ErrorContains, "error"),
Result{
Error: errors.New("expected an error, got: <nil>: nil"),
},
},
{
result(errors.New("database error"), ErrorContains, 42),
Result{
Error: errors.New("expected a string, got: <int>: 42"),
},
},
{
result(errors.New("database error"), ErrorContains, "HTTP"),
Result{
FailureMessage: "Expected <error>: database error to contain <string>: HTTP",
NegatedFailureMessage: "Expected <error>: database error not to contain <string>: HTTP",
},
},
}
func Test_Err(t *testing.T) {
testMatchers(t, errMatcherTests)
}
| {'content_hash': 'c160806bee2ab5f3a4f3ed41bdb09f83', 'timestamp': '', 'source': 'github', 'line_count': 58, 'max_line_length': 91, 'avg_line_length': 20.775862068965516, 'alnum_prop': 0.6406639004149378, 'repo_name': '101loops/bdd', 'id': 'adb0dd20d7c297aff93566c7694a85d9fc5cc510', 'size': '1205', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'matcher_err_test.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Go', 'bytes': '47099'}]} |
#ifndef PORTMACRO_H
#define PORTMACRO_H
#ifdef __cplusplus
extern "C" {
#endif
/*-----------------------------------------------------------
* Port specific definitions.
*
* The settings in this file configure FreeRTOS correctly for the
* given hardware and compiler.
*
* These settings should not be altered.
*-----------------------------------------------------------
*/
/* Type definitions. */
#define portCHAR char
#define portFLOAT float
#define portDOUBLE double
#define portLONG long
#define portSHORT short
#define portSTACK_TYPE unsigned int
#define portBASE_TYPE int
typedef portSTACK_TYPE StackType_t;
typedef long BaseType_t;
typedef unsigned long UBaseType_t;
#if (configUSE_16_BIT_TICKS==1)
typedef uint16_t TickType_t;
#define portMAX_DELAY ( TickType_t ) 0xffff
#else
typedef uint32_t TickType_t;
#define portMAX_DELAY ( TickType_t ) 0xffffffffUL
#endif
/*-----------------------------------------------------------*/
/* Interrupt control macros. */
#define portDISABLE_INTERRUPTS() __asm ( "DI" )
#define portENABLE_INTERRUPTS() __asm ( "EI" )
/*-----------------------------------------------------------*/
/* Critical section control macros. */
#define portNO_CRITICAL_SECTION_NESTING ( ( UBaseType_t ) 0 )
#define portENTER_CRITICAL() \
{ \
extern volatile /*uint16_t*/ portSTACK_TYPE usCriticalNesting; \
\
portDISABLE_INTERRUPTS(); \
\
/* Now interrupts are disabled ulCriticalNesting can be accessed */ \
/* directly. Increment ulCriticalNesting to keep a count of how many */ \
/* times portENTER_CRITICAL() has been called. */ \
usCriticalNesting++; \
}
#define portEXIT_CRITICAL() \
{ \
extern volatile /*uint16_t*/ portSTACK_TYPE usCriticalNesting; \
\
if( usCriticalNesting > portNO_CRITICAL_SECTION_NESTING ) \
{ \
/* Decrement the nesting count as we are leaving a critical section. */ \
usCriticalNesting--; \
\
/* If the nesting level has reached zero then interrupts should be */ \
/* re-enabled. */ \
if( usCriticalNesting == portNO_CRITICAL_SECTION_NESTING ) \
{ \
portENABLE_INTERRUPTS(); \
} \
} \
}
/*-----------------------------------------------------------*/
/* Task utilities. */
extern void vPortYield( void );
extern void vPortStart( void );
extern void portSAVE_CONTEXT( void );
extern void portRESTORE_CONTEXT( void );
#define portYIELD() __asm ( "trap 0" )
#define portNOP() __asm ( "NOP" )
extern void vTaskSwitchContext( void );
#define portYIELD_FROM_ISR( xHigherPriorityTaskWoken ) if( xHigherPriorityTaskWoken ) vTaskSwitchContext()
/*-----------------------------------------------------------*/
/* Hardwware specifics. */
#define portBYTE_ALIGNMENT 4
#define portSTACK_GROWTH ( -1 )
#define portTICK_PERIOD_MS ( ( TickType_t ) 1000 / configTICK_RATE_HZ )
/*-----------------------------------------------------------*/
/* Task function macros as described on the FreeRTOS.org WEB site. */
#define portTASK_FUNCTION_PROTO( vFunction, pvParameters ) void vFunction( void *pvParameters )
#define portTASK_FUNCTION( vFunction, pvParameters ) void vFunction( void *pvParameters )
#ifdef __cplusplus
}
#endif
#endif /* PORTMACRO_H */
| {'content_hash': '07e88cda70650dba57ff4fc6bea5c482', 'timestamp': '', 'source': 'github', 'line_count': 110, 'max_line_length': 106, 'avg_line_length': 32.81818181818182, 'alnum_prop': 0.5404432132963989, 'repo_name': 'anarchih/Enhanced-CNC-Controller', 'id': 'd6ebcd024d2ee98c2a181abcdc732132cd35bb37', 'size': '7198', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'freertos/portable/IAR/V850ES/portmacro.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '242218'}, {'name': 'C', 'bytes': '3056880'}, {'name': 'C++', 'bytes': '1983816'}, {'name': 'Makefile', 'bytes': '4170'}, {'name': 'Objective-C', 'bytes': '11759'}, {'name': 'Python', 'bytes': '2738'}, {'name': 'Shell', 'bytes': '9891'}, {'name': 'nesC', 'bytes': '51321'}]} |
from Tkinter import *
import pKa_base
import EM_effect
class EM_effect_struct(Frame,pKa_base.pKa_base,EM_effect.EM_effect):
def __init__(self,parent=None):
"""Init the class"""
self.parent_application=None
if parent:
self.parent_application=parent
#
# Open the window
#
if not self.parent_application:
Frame.__init__(self)
self.EM_window=self.master
else:
self.EM_window=Toplevel()
self.EM_window.geometry('+200+600')
self.EM_window.title('Structure/sequence display')
#
# Draw the pH vs. chem shift graph
#
self.linewidth=2
self.titwidth=1200
self.titheight=450
self.tc=Canvas(self.EM_window,bd=5,bg='white',width=self.titwidth,
height=self.titheight,
scrollregion=(0,0,self.titwidth,self.titheight))
self.tc.xview("moveto", 0)
self.tc.yview("moveto", 0)
self.tc.grid(row=0,column=0)
#
# Axes
#
self.set_graph_size(x_max=129.0,x_min=0.0,y_max=12.0,y_min=0.0,
x_tick_level=20,y_tick_level=2.0,width=self.titwidth,height=self.titheight)
self.draw_ordinates(self.tc,y_label='pH',x_label='Residue')
#
# Pulldown menu
#
self.menu=Menu(self.EM_window)
#
# File menu
#
self.file_menu=Menu(self.menu,tearoff=0)
self.file_menu.add_command(label='Load PDB file',command=self.load_pdb)
self.file_menu.add_command(label='Load Ekin titration data',command=self.load_full_titdata)
self.file_menu.add_command(label='Exit',command=self.quit)
self.menu.add_cascade(label='File',menu=self.file_menu)
#
# Configure the menu
#
self.EM_window.config(menu=self.menu)
return
#
# ----
#
def draw_titrations(self,titdata):
"""Draw all the titrations"""
residues=titdata.keys()
residues.sort()
for residue in residues:
resnumber=int(residue[1:])
if len(titdata[residue])==0:
continue
last_pH,last_chemshift=titdata[residue][0]
for pH,chemshift in titdata[residue][1:]:
x,y=self.get_xy(resnumber,last_pH)
x1,y1=self.get_xy(resnumber+1,pH)
#
# Get the colour - depends on the chemical shift change
#
colour=self.get_colour_from_chemshift((chemshift-last_chemshift)/(pH-last_pH))
self.tc.create_rectangle(x,y,x1,y1,fill=colour,outline=colour)
#
# Update last pH and chemshift
#
last_chemshift=chemshift
last_pH=pH
return
#
# -----
#
def get_colour_from_chemshift(self,dchemshift):
"""Get the colour corresponding to a certain chemshift change"""
import numpy, string
col_min=numpy.array([100,100,100])
if dchemshift>0.0:
col_max=numpy.array([0,0,255])
elif dchemshift<=0.0:
col_max=numpy.array([255,0,0])
#
# Calculate the colour
#
dchemshift=abs(dchemshift)
max_change=0.5
if dchemshift>max_change:
dchemshift=max_change
colour=(col_max-col_min)/max_change*dchemshift+col_min
text='#'
for col in colour:
text=text+string.zfill(hex(int(col))[2:],2)
return text
if __name__=='__main__':
X=EM_effect_struct()
#X.load_pdb('2lzt.pka.pdb')
X.mainloop()
| {'content_hash': '8f9f9327c9213c85f2459a71726a9189', 'timestamp': '', 'source': 'github', 'line_count': 114, 'max_line_length': 103, 'avg_line_length': 32.57017543859649, 'alnum_prop': 0.5432265014812819, 'repo_name': 'dmnfarrell/peat', 'id': '30fcff5a574defa0961a7ba8783d0baf44f09416', 'size': '4660', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'pKaTool/EM_effect_struct_win.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '243'}, {'name': 'C', 'bytes': '744763'}, {'name': 'C++', 'bytes': '999138'}, {'name': 'CSS', 'bytes': '10879'}, {'name': 'Gnuplot', 'bytes': '311'}, {'name': 'JavaScript', 'bytes': '60380'}, {'name': 'Makefile', 'bytes': '12428'}, {'name': 'Mathematica', 'bytes': '964'}, {'name': 'Matlab', 'bytes': '820'}, {'name': 'Mercury', 'bytes': '26238794'}, {'name': 'PHP', 'bytes': '92905'}, {'name': 'Python', 'bytes': '5466696'}, {'name': 'Shell', 'bytes': '2984'}]} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '9371fd18331aca7f222d3ff1e946b1df', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': '884c1536b9aa74ed2e0c26bc31e9fd4c0123a867', 'size': '184', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Salvia/Salvia tunica-mariae/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.