text stringlengths 2 1.04M | meta dict |
|---|---|
package org.apache.jmeter.extractor;
import java.beans.PropertyDescriptor;
import org.apache.jmeter.testbeans.BeanInfoSupport;
public class DebugPostProcessorBeanInfo extends BeanInfoSupport {
public DebugPostProcessorBeanInfo() {
super(DebugPostProcessor.class);
PropertyDescriptor p;
p = property("displaySamplerProperties");
p.setValue(NOT_UNDEFINED, Boolean.TRUE);
p.setValue(NOT_EXPRESSION, Boolean.TRUE);
p.setValue(NOT_OTHER, Boolean.TRUE);
p.setValue(DEFAULT, Boolean.TRUE);
p = property("displayJMeterVariables");
p.setValue(NOT_UNDEFINED, Boolean.TRUE);
p.setValue(NOT_EXPRESSION, Boolean.TRUE);
p.setValue(NOT_OTHER, Boolean.TRUE);
p.setValue(DEFAULT, Boolean.TRUE);
p = property("displayJMeterProperties");
p.setValue(NOT_UNDEFINED, Boolean.TRUE);
p.setValue(NOT_EXPRESSION, Boolean.TRUE);
p.setValue(NOT_OTHER, Boolean.TRUE);
p.setValue(DEFAULT, Boolean.FALSE);
p = property("displaySystemProperties");
p.setValue(NOT_UNDEFINED, Boolean.TRUE);
p.setValue(NOT_EXPRESSION, Boolean.TRUE);
p.setValue(NOT_OTHER, Boolean.TRUE);
p.setValue(DEFAULT, Boolean.FALSE);
}
}
| {
"content_hash": "9355cb4d3cb9479c34bb4a19bfd974b2",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 65,
"avg_line_length": 31.024390243902438,
"alnum_prop": 0.6737421383647799,
"repo_name": "etnetera/jmeter",
"id": "14cf586ac2ba2fcba6a11ef5c18e422b5ce24235",
"size": "2069",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "src/components/src/main/java/org/apache/jmeter/extractor/DebugPostProcessorBeanInfo.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "25493"
},
{
"name": "CSS",
"bytes": "23027"
},
{
"name": "Groovy",
"bytes": "156298"
},
{
"name": "HTML",
"bytes": "93440"
},
{
"name": "Java",
"bytes": "8972491"
},
{
"name": "JavaScript",
"bytes": "36223"
},
{
"name": "Kotlin",
"bytes": "119031"
},
{
"name": "Less",
"bytes": "6310"
},
{
"name": "Shell",
"bytes": "24593"
},
{
"name": "XSLT",
"bytes": "91169"
}
],
"symlink_target": ""
} |
package eu.matejkormuth.rpbuild.configuration.xml;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.xml.bind.annotation.adapters.XmlAdapter;
/**
* Maps Java NIO Path to String.
*/
public class XmlPathAdapter extends XmlAdapter<String, Path> {
@Override
public Path unmarshal(String v) throws Exception {
return Paths.get(v);
}
@Override
public String marshal(Path v) throws Exception {
return v.toString();
}
}
| {
"content_hash": "213b39a9b4d65a14dbcce4e8c40626a8",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 62,
"avg_line_length": 18.708333333333332,
"alnum_prop": 0.7438752783964365,
"repo_name": "dobrakmato/rpbuild",
"id": "a3f239c612268ae33876b084d47d3a8f40835686",
"size": "1999",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/eu/matejkormuth/rpbuild/configuration/xml/XmlPathAdapter.java",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Java",
"bytes": "101378"
},
{
"name": "Shell",
"bytes": "2211"
}
],
"symlink_target": ""
} |
"""Common runtime ctypes."""
# pylint: disable=invalid-name
from __future__ import absolute_import
import ctypes
import json
import numpy as np
from .base import _LIB, check_call
from .. import _api_internal
tvm_shape_index_t = ctypes.c_int64
class TypeCode(object):
"""Type code used in API calls"""
INT = 0
UINT = 1
FLOAT = 2
HANDLE = 3
NULL = 4
TVM_TYPE = 5
TVM_CONTEXT = 6
ARRAY_HANDLE = 7
NODE_HANDLE = 8
MODULE_HANDLE = 9
FUNC_HANDLE = 10
STR = 11
BYTES = 12
NDARRAY_CONTAINER = 13
OBJECT = 14
EXT_BEGIN = 15
class TVMByteArray(ctypes.Structure):
"""Temp data structure for byte array."""
_fields_ = [("data", ctypes.POINTER(ctypes.c_byte)),
("size", ctypes.c_size_t)]
class TVMType(ctypes.Structure):
"""TVM datatype structure"""
_fields_ = [("type_code", ctypes.c_uint8),
("bits", ctypes.c_uint8),
("lanes", ctypes.c_uint16)]
CODE2STR = {
0 : 'int',
1 : 'uint',
2 : 'float',
4 : 'handle'
}
def __init__(self, type_str):
super(TVMType, self).__init__()
if isinstance(type_str, np.dtype):
type_str = str(type_str)
if type_str == "bool":
self.bits = 1
self.type_code = 1
self.lanes = 1
return
arr = type_str.split("x")
head = arr[0]
self.lanes = int(arr[1]) if len(arr) > 1 else 1
bits = 32
if head.startswith("int"):
self.type_code = 0
head = head[3:]
elif head.startswith("uint"):
self.type_code = 1
head = head[4:]
elif head.startswith("float"):
self.type_code = 2
head = head[5:]
elif head.startswith("handle"):
self.type_code = 4
bits = 64
head = ""
elif head.startswith("custom"):
low, high = head.find('['), head.find(']')
if not low or not high or low >= high:
raise ValueError("Badly formatted custom type string %s" % type_str)
type_name = head[low + 1:high]
self.type_code = _api_internal._datatype_get_type_code(type_name)
head = head[high+1:]
else:
raise ValueError("Do not know how to handle type %s" % type_str)
bits = int(head) if head else bits
self.bits = bits
def __repr__(self):
if self.bits == 1 and self.lanes == 1:
return "bool"
if self.type_code in TVMType.CODE2STR:
type_name = TVMType.CODE2STR[self.type_code]
else:
type_name = "custom[%s]" % \
_api_internal._datatype_get_type_name(self.type_code)
x = "%s%d" % (type_name, self.bits)
if self.lanes != 1:
x += "x%d" % self.lanes
return x
def __eq__(self, other):
return (self.bits == other.bits and
self.type_code == other.type_code and
self.lanes == other.lanes)
def __ne__(self, other):
return not self.__eq__(other)
RPC_SESS_MASK = 128
class TVMContext(ctypes.Structure):
"""TVM context strucure."""
_fields_ = [("device_type", ctypes.c_int),
("device_id", ctypes.c_int)]
MASK2STR = {
1 : 'cpu',
2 : 'gpu',
4 : 'opencl',
5 : 'aocl',
6 : 'sdaccel',
7 : 'vulkan',
8 : 'metal',
9 : 'vpi',
10: 'rocm',
11: 'opengl',
12: 'ext_dev',
}
STR2MASK = {
'llvm': 1,
'stackvm': 1,
'cpu': 1,
'c': 1,
'gpu': 2,
'cuda': 2,
'nvptx': 2,
'cl': 4,
'opencl': 4,
'aocl' : 5,
'aocl_sw_emu' : 5,
'sdaccel': 6,
'vulkan': 7,
'metal': 8,
'vpi': 9,
'rocm': 10,
'opengl': 11,
'ext_dev': 12,
}
def __init__(self, device_type, device_id):
super(TVMContext, self).__init__()
self.device_type = device_type
self.device_id = device_id
@property
def exist(self):
"""Whether this device exist."""
return _api_internal._GetDeviceAttr(
self.device_type, self.device_id, 0) != 0
@property
def max_threads_per_block(self):
"""Maximum number of threads on each block."""
return _api_internal._GetDeviceAttr(
self.device_type, self.device_id, 1)
@property
def warp_size(self):
"""Number of threads that executes in concurrent."""
return _api_internal._GetDeviceAttr(
self.device_type, self.device_id, 2)
@property
def max_shared_memory_per_block(self):
"""Total amount of shared memory per block in bytes."""
return _api_internal._GetDeviceAttr(
self.device_type, self.device_id, 3)
@property
def compute_version(self):
"""Get compute verison number in string.
Currently used to get compute capability of CUDA device.
Returns
-------
version : str
The version string in `major.minor` format.
"""
return _api_internal._GetDeviceAttr(
self.device_type, self.device_id, 4)
@property
def device_name(self):
"""Return the string name of device."""
return _api_internal._GetDeviceAttr(
self.device_type, self.device_id, 5)
@property
def max_clock_rate(self):
"""Return the max clock frequency of device."""
return _api_internal._GetDeviceAttr(
self.device_type, self.device_id, 6)
@property
def multi_processor_count(self):
"""Return the number of compute units of device."""
return _api_internal._GetDeviceAttr(
self.device_type, self.device_id, 7)
@property
def max_thread_dimensions(self):
"""Return the maximum size of each thread axis
Returns
-------
dims: List of int
The maximum length of threadIdx.x, threadIdx.y, threadIdx.z
"""
return json.loads(_api_internal._GetDeviceAttr(
self.device_type, self.device_id, 8))
def sync(self):
"""Synchronize until jobs finished at the context."""
check_call(_LIB.TVMSynchronize(self.device_type, self.device_id, None))
def __eq__(self, other):
return (isinstance(other, TVMContext) and
self.device_id == other.device_id and
self.device_type == other.device_type)
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
if self.device_type >= RPC_SESS_MASK:
tbl_id = self.device_type / RPC_SESS_MASK - 1
dev_type = self.device_type % RPC_SESS_MASK
return "remote[%d]:%s(%d)" % (
tbl_id, TVMContext.MASK2STR[dev_type], self.device_id)
return "%s(%d)" % (
TVMContext.MASK2STR[self.device_type], self.device_id)
class TVMArray(ctypes.Structure):
"""TVMValue in C API"""
_fields_ = [("data", ctypes.c_void_p),
("ctx", TVMContext),
("ndim", ctypes.c_int),
("dtype", TVMType),
("shape", ctypes.POINTER(tvm_shape_index_t)),
("strides", ctypes.POINTER(tvm_shape_index_t)),
("byte_offset", ctypes.c_uint64)]
TVMArrayHandle = ctypes.POINTER(TVMArray)
class TVMNDArrayContainer(ctypes.Structure):
"""TVM NDArray::Container"""
_fields_ = [("dl_tensor", TVMArray),
("manager_ctx", ctypes.c_void_p),
("deleter", ctypes.c_void_p),
("array_type_info", ctypes.c_int32)]
TVMNDArrayContainerHandle = ctypes.POINTER(TVMNDArrayContainer)
| {
"content_hash": "c95cba26a0e819cec737938519d9cecd",
"timestamp": "",
"source": "github",
"line_count": 265,
"max_line_length": 84,
"avg_line_length": 29.528301886792452,
"alnum_prop": 0.5304792332268371,
"repo_name": "mlperf/training_results_v0.7",
"id": "72cff1a10eadbd7d75c23276b043e47cf2d88d16",
"size": "8610",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/tvm/python/tvm/_ffi/runtime_ctypes.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "1731"
},
{
"name": "Awk",
"bytes": "14530"
},
{
"name": "Batchfile",
"bytes": "13130"
},
{
"name": "C",
"bytes": "172914"
},
{
"name": "C++",
"bytes": "13037795"
},
{
"name": "CMake",
"bytes": "113458"
},
{
"name": "CSS",
"bytes": "70255"
},
{
"name": "Clojure",
"bytes": "622652"
},
{
"name": "Cuda",
"bytes": "1974745"
},
{
"name": "Dockerfile",
"bytes": "149523"
},
{
"name": "Groovy",
"bytes": "160449"
},
{
"name": "HTML",
"bytes": "171537"
},
{
"name": "Java",
"bytes": "189275"
},
{
"name": "JavaScript",
"bytes": "98224"
},
{
"name": "Julia",
"bytes": "430755"
},
{
"name": "Jupyter Notebook",
"bytes": "11091342"
},
{
"name": "Lua",
"bytes": "17720"
},
{
"name": "MATLAB",
"bytes": "34903"
},
{
"name": "Makefile",
"bytes": "215967"
},
{
"name": "Perl",
"bytes": "1551186"
},
{
"name": "PowerShell",
"bytes": "13906"
},
{
"name": "Python",
"bytes": "36943114"
},
{
"name": "R",
"bytes": "134921"
},
{
"name": "Raku",
"bytes": "7280"
},
{
"name": "Ruby",
"bytes": "4930"
},
{
"name": "SWIG",
"bytes": "140111"
},
{
"name": "Scala",
"bytes": "1304960"
},
{
"name": "Shell",
"bytes": "1312832"
},
{
"name": "Smalltalk",
"bytes": "3497"
},
{
"name": "Starlark",
"bytes": "69877"
},
{
"name": "TypeScript",
"bytes": "243012"
}
],
"symlink_target": ""
} |
package com.esri.gpt.control.georss;
import com.esri.gpt.catalog.search.OpenSearchProperties;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.esri.gpt.catalog.search.ResourceLink;
import com.esri.gpt.catalog.search.SearchResultRecord;
import com.esri.gpt.catalog.search.SearchResultRecords;
import com.esri.gpt.framework.jsf.MessageBroker;
import com.esri.gpt.framework.util.Val;
import java.io.BufferedWriter;
/**
* ATOM feed writer.
*/
public class AtomFeedWriter implements FeedWriter {
/** The LOGGER. */
private static Logger LOGGER = Logger.getLogger(AtomFeedWriter.class.getName());
/** The DAT e_ forma t_ pattern. */
private final String DATE_FORMAT_PATTERN = "yyyy-MM-dd";
/** The TIM e_ forma t_ pattern. */
private final String TIME_FORMAT_PATTERN = "kk:mm:ss";
/** The _writer. */
private PrintWriter _writer;
/** The _entry base url. */
private String _entryBaseUrl = null;
/** The _target. */
private RecordSnippetWriter.Target _target = RecordSnippetWriter.Target.blank;
/** The _message broker. */
private MessageBroker _messageBroker = null;
/** line separator */
private String lineSeparator;
// constructors ================================================================
/**
* Constructor.
*
* @param writer the writer
*/
public AtomFeedWriter(PrintWriter writer) {
_writer = writer;
lineSeparator = (String) java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("line.separator"));
}
/**
* Constructor.
*
* @param writer the writer
* @param entryBaseUrl provider URL
*/
public AtomFeedWriter(PrintWriter writer, String entryBaseUrl) {
_writer = writer;
_entryBaseUrl = entryBaseUrl;
lineSeparator = (String) java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("line.separator"));
}
// properties
/**
* Sets the entry base url.
*
* @param url the new entry base url
*/
public void setEntryBaseUrl(String url) {
_entryBaseUrl = url;
}
// ==================================================================
/**
* Gets the entry base url.
*
* @return Base URL
*/
public String getEntryBaseUrl() {
return _entryBaseUrl;
}
/**
* Gets links target.
*
* @return links targets
*/
public RecordSnippetWriter.Target getTarget() {
return _target;
}
/**
* Sets links target.
*
* @param target
* links target
*/
public void setTarget(RecordSnippetWriter.Target target) {
_target = target;
}
/**
* Gets the Message Broker.
*
* @return message broker
*/
public MessageBroker getMessageBroker() {
_messageBroker = (_messageBroker != null) ? _messageBroker
: new MessageBroker();
return _messageBroker;
}
/**
* Sets the Message Broker.
*
* @param broker the new _message broker
*/
public void set_messageBroker(MessageBroker broker) {
_messageBroker = broker;
}
// methods
// ==================================================================
/**
* Write Atom Feed.
*
* @param records records to write
*/
@Override
public void write(IFeedRecords records) {
if (_writer == null)
return;
AtomFeed af = new AtomFeed();
String sTitle = _messageBroker.retrieveMessage("catalog.rest.title");
String sDescription = _messageBroker.retrieveMessage("catalog.rest.description");
String sCopyright = _messageBroker.retrieveMessage("catalog.rest.copyright");
String sGenerator = _messageBroker.retrieveMessage("catalog.rest.generator");
if (sTitle.startsWith("???")) sTitle = "";
if (sDescription.startsWith("???")) sDescription = "";
if (sCopyright.startsWith("???")) sCopyright = "";
if (sGenerator.startsWith("???")) sGenerator = "";
af.setTitle(sTitle);
af.setDescription(sDescription);
af.setAuthor(sGenerator);
af.setCopyright(sCopyright);
af.setLink(getEntryBaseUrl());
af.setId(getEntryBaseUrl());
af.setUpdated(new Date());
af.setOsProps(records.getOpenSearchProperties());
for (IFeedRecord record : records) {
AtomEntry ae = new AtomEntry();
ae.setId(record.getUuid());
ae.setPublished(record.getModfiedDate());
ae.setTitle(record.getTitle());
ae.setSummary(record.getAbstract());
for (ResourceLink link : record.getResourceLinks()) {
ae.addResourceLink(link);
}
ae.addResourceLink(record.getResourceLinks().getThumbnail());
if (record.getEnvelope() != null) {
ae.setMinx(record.getEnvelope().getMinX());
ae.setMiny(record.getEnvelope().getMinY());
ae.setMaxx(record.getEnvelope().getMaxX());
ae.setMaxy(record.getEnvelope().getMaxY());
}
af.addEntry(ae);
}
af.WriteTo(_writer);
}
// Private classes
// ==================================================================
/**
* Represents an Atom Entry.
*/
public class AtomEntry {
/** The ENTIT y_ ope n_ tag. */
private final String ENTITY_OPEN_TAG = "<entry>";
/** The ENTIT y_ clos e_ tag. */
private final String ENTITY_CLOSE_TAG = "</entry>";
/** The TITL e_ ope n_ tag. */
private final String TITLE_OPEN_TAG = "<title>";
/** The TITL e_ clos e_ tag. */
private final String TITLE_CLOSE_TAG = "</title>";
// private final String LINK_TAG = "<link type=\"text/html\" href=\"?\"/>";
/** The LIN k_ tag. */
private final String LINK_TAG = "<link href=\"?\"/>";
/** The I d_ ope n_ tag. */
private final String ID_OPEN_TAG = "<id>";
/** The I d_ clos e_ tag. */
private final String ID_CLOSE_TAG = "</id>";
/** The UPDATE d_ ope n_ tag. */
private final String UPDATED_OPEN_TAG = "<updated>";
/** The UPDATE d_ clos e_ tag. */
private final String UPDATED_CLOSE_TAG = "</updated>";
/** The SUMMAR y_ ope n_ tag. */
private final String SUMMARY_OPEN_TAG = "<summary>";
/** The SUMMAR y_ clos e_ tag. */
private final String SUMMARY_CLOSE_TAG = "</summary>";
/** The BO x_ ope n_ tag. */
private final String BOX_OPEN_TAG = "<georss:box>";
/** The BO x_ clos e_ tag. */
private final String BOX_CLOSE_TAG = "</georss:box>";
/** The RES t_ fin d_ pattern. */
private final String REST_FIND_PATTERN = "/rest/document/";
/** The _id. */
private String _id = null;
/** The _title. */
private String _title = null;
/** The _link. */
private LinkedList<String> _link = null;
/** The _published. */
private Date _published = null;
/** The _summary. */
private String _summary = null;
/** The _minx. */
private double _minx = 0;
/** The _miny. */
private double _miny = 0;
/** The _maxx. */
private double _maxx = 0;
/** The _maxy. */
private double _maxy = 0;
/** The custom elements. */
private String customElements;
// methods
// ==================================================================
/**
* Gets the minx.
*
* @return the minx
*/
public double getMinx() {
return _minx;
}
/**
* Gets the miny.
*
* @return the miny
*/
public double getMiny() {
return _miny;
}
/**
* Gets the maxx.
*
* @return the maxx
*/
public double getMaxx() {
return _maxx;
}
/**
* Gets the maxy.
*
* @return the maxy
*/
public double getMaxy() {
return _maxy;
}
/**
* Sets the minx.
*
* @param _minx the new minx
*/
public void setMinx(double _minx) {
this._minx = _minx;
}
/**
* Sets the miny.
*
* @param _miny the new miny
*/
public void setMiny(double _miny) {
this._miny = _miny;
}
/**
* Sets the maxx.
*
* @param _maxx the new maxx
*/
public void setMaxx(double _maxx) {
this._maxx = _maxx;
}
/**
* Sets the maxy.
*
* @param _maxy the new maxy
*/
public void setMaxy(double _maxy) {
this._maxy = _maxy;
}
/**
* Gets the id.
*
* @return the id
*/
public String getId() {
return _id;
}
/**
* Gets the title.
*
* @return the title
*/
public String getTitle() {
return _title;
}
/**
* Gets the links.
*
* @return the links
*/
public LinkedList<String> getLinks() {
return _link;
}
/**
* Gets the published.
*
* @return the published
*/
public Date getPublished() {
return _published;
}
/**
* Gets the summary.
*
* @return the summary
*/
public String getSummary() {
return _summary;
}
/**
* Sets the id.
*
* @param id the new id
*/
public void setId(String id) {
this._id = id;
}
/**
* Sets the title.
*
* @param title the new title
*/
public void setTitle(String title) {
_title = title;
}
/**
* Sets the published.
*
* @param published the new published
*/
public void setPublished(Date published) {
_published = published;
}
/**
* Sets the summary.
*
* @param summary the new summary
*/
public void setSummary(String summary) {
_summary = summary;
}
/**
* Gets the custom elements.
*
* @return the custom elements
*/
public String getCustomElements() {
return customElements;
}
/**
* Sets the custom elements.
*
* @param customElements the new custom elements
*/
public void setCustomElements(String customElements) {
this.customElements = customElements;
}
/**
* Adds the resource link.
*
* @param resourcelink the resourcelink
*/
public void addResourceLink(ResourceLink resourcelink) {
if (resourcelink == null)
return;
if (_link == null)
_link = new LinkedList<String>();
if (resourcelink.getUrl() != null && resourcelink.getUrl().length() > 0)
_link.add(resourcelink.getUrl());
}
/**
* Write to.
*
* @param writer the writer
*/
public void WriteTo(java.io.Writer writer) {
String data = "";
if (writer == null)
return;
try {
writer.append(ENTITY_OPEN_TAG+lineSeparator);
if (getTitle() != null) {
try {
data = TITLE_OPEN_TAG + Val.escapeXml(getTitle()) + TITLE_CLOSE_TAG;
writer.append("\t"+data+lineSeparator);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "", e);
}
}
// add the rest of links if they exist
if (getLinks() != null) {
for (String lnk : getLinks()) {
try {
data = LINK_TAG.replace("?", Val.escapeXml(lnk));
writer.append("\t"+data+lineSeparator);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "", e);
}
}
}
if (getId() != null) {
try {
data = Val.escapeXml(getId());
data = ID_OPEN_TAG + "urn:uuid:" + data.substring(1, data.length() - 1)
+ ID_CLOSE_TAG;
writer.append("\t"+data+lineSeparator);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "", e);
}
}
if (getPublished() != null) {
try {
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_PATTERN);
data = format.format(getPublished());
format = new SimpleDateFormat(TIME_FORMAT_PATTERN);
data = data + "T" + format.format(getPublished()) + "Z";
data = UPDATED_OPEN_TAG + data + UPDATED_CLOSE_TAG;
writer.append("\t"+data+lineSeparator);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "", e);
}
}
if (getSummary() != null) {
try {
data = SUMMARY_OPEN_TAG + Val.escapeXml(getSummary())
+ SUMMARY_CLOSE_TAG;
writer.append("\t"+data+lineSeparator);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "", e);
}
}
/*if (hasEnvelope()) {
try {
data = BOX_OPEN_TAG + getMiny() + " " + getMinx() + " " + getMaxy()
+ " " + getMaxx() + BOX_CLOSE_TAG;
writer.append("\t"+data+lineSeparator);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "", e);
}
}*/
if( getCustomElements() != null) {
writer.append("\t"+Val.chkStr(getCustomElements())+lineSeparator);
}
writer.append(ENTITY_CLOSE_TAG+lineSeparator);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "", e);
}
}
/**
* Checks for envelope.
*
* @return true, if successful
*/
private boolean hasEnvelope() {
return !(getMinx() == 0 && getMiny() == 0 && getMaxx() == 0 && getMaxy() == 0);
}
}
/**
* Represents an Atom Feed.
*/
public class AtomFeed {
/** The ATO m_ header. */
private final String ATOM_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
/** The ATO m_ roo t_ ope n_ tag. */
private String ATOM_ROOT_OPEN_TAG = "<feed xmlns=\"http://www.w3.org/2005/Atom\" xmlns:georss=\"http://www.georss.org/georss\" xmlns:opensearch=\"http://a9.com/-/spec/opensearch/1.1/\">";
/** The ATO m_ roo t_ clos e_ tag. */
private final String ATOM_ROOT_CLOSE_TAG = "</feed>";
/** The COMMEN t_ ope n_ tag. */
private final String COMMENT_OPEN_TAG = "<!--";
/** The COMMEN t_ clos e_ tag. */
private final String COMMENT_CLOSE_TAG = "-->";
/** The TITLE open tag. */
private final String TITLE_OPEN_TAG = "<title>";
/** The TITLE close tag. */
private final String TITLE_CLOSE_TAG = "</title>";
/** The AUTHOR open tag. */
private final String AUTHOR_OPEN_TAG = "<author><name>";
/** The AUTHOR clos e_ tag. */
private final String AUTHOR_CLOSE_TAG = "</name></author>";
/** The LIN k_ tag. */
private final String LINK_TAG = "<link rel=\"self\" href=\"?\"/>";
/** The UPDATED open tag. */
private final String UPDATED_OPEN_TAG = "<updated>";
/** The UPDATED close tag. */
private final String UPDATED_CLOSE_TAG = "</updated>";
/** The ID open tag. */
private final String ID_OPEN_TAG = "<id>";
/** The ID close_ tag. */
private final String ID_CLOSE_TAG = "</id>";
/** The TOTAL results open_ tag. */
private final String TOTAL_RESULTS_OPEN_TAG = "<opensearch:totalResults>";
/** The TOTA l_ result s_ clos e_ tag. */
private final String TOTAL_RESULTS_CLOSE_TAG = "</opensearch:totalResults>";
/** The STAR t_ inde x_ ope n_ tag. */
private final String START_INDEX_OPEN_TAG = "<opensearch:startIndex>";
/** The STAR t_ inde x_ clos e_ tag. */
private final String START_INDEX_CLOSE_TAG = "</opensearch:startIndex>";
/** The ITEM s_ pe r_ pag e_ ope n_ tag. */
private final String ITEMS_PER_PAGE_OPEN_TAG = "<opensearch:itemsPerPage>";
/** The ITEM s_ pe r_ pag e_ clos e_ tag. */
private final String ITEMS_PER_PAGE_CLOSE_TAG = "</opensearch:itemsPerPage>";
/** The _copyright. */
private String _copyright = null;
/** The _description. */
private String _description = null;
/** The _title. */
private String _title = null;
/** The _link. */
private String _link = null;
/** The _updated. */
private Date _updated = null;
/** The _author. */
private String _author = null;
/** The _id. */
private String _id = null;
/** The os props. */
private OpenSearchProperties osProps = null;
/** The _entries. */
private LinkedList<AtomEntry> _entries = null;
/**
* Instantiates a new atom feed.
*/
public AtomFeed() {
_entries = new LinkedList<AtomEntry>();
}
/**
* Adds the entry.
*
* @param ae the ae
*/
public void addEntry(AtomEntry ae) {
if (ae != null) {
_entries.add(ae);
}
}
/**
* Gets the copyright.
*
* @return the copyright
*/
public String getCopyright() {
return _copyright;
}
/**
* Gets the description.
*
* @return the description
*/
public String getDescription() {
return _description;
}
/**
* Gets the author.
*
* @return the author
*/
public String getAuthor() {
return _author;
}
/**
* Entries.
*
* @return the linked list
*/
public LinkedList<AtomEntry> Entries() {
return _entries;
}
/**
* Gets the title.
*
* @return the title
*/
public String getTitle() {
return _title;
}
/**
* Gets the link.
*
* @return the link
*/
public String getLink() {
return _link;
}
/**
* Gets the updated.
*
* @return the updated
*/
public Date getUpdated() {
return _updated;
}
/**
* Gets the id.
*
* @return the id
*/
public String getId() {
return _id;
}
/**
* Gets the os props.
*
* @return the os props
*/
public OpenSearchProperties getOsProps() {
return osProps;
}
/**
* Sets the copyright.
*
* @param copyright the new copyright
*/
public void setCopyright(String copyright) {
this._copyright = copyright;
}
/**
* Sets the description.
*
* @param description the new description
*/
public void setDescription(String description) {
this._description = description;
}
/**
* Sets the author.
*
* @param author the new author
*/
public void setAuthor(String author) {
this._author = author;
}
/**
* Sets the title.
*
* @param title the new title
*/
public void setTitle(String title) {
this._title = title;
}
/**
* Sets the link.
*
* @param link the new link
*/
public void setLink(String link) {
this._link = link;
}
/**
* Sets the updated.
*
* @param updated the new updated
*/
public void setUpdated(Date updated) {
this._updated = updated;
}
/**
* Sets the id.
*
* @param id the new id
*/
public void setId(String id) {
this._id = id;
}
/**
* Sets the os props.
*
* @param osProps the new os props
*/
public void setOsProps(OpenSearchProperties osProps) {
this.osProps = osProps;
}
/**
* Gets the info.
*
* @return the info
*/
public String getInfo() {
StringBuffer sb = new StringBuffer();
if (getDescription() != null) {
sb.append("Description: " + getDescription() + "\n");
}
if (getCopyright() != null) {
sb.append("Copyright: " + getCopyright() + "\n");
}
return sb.toString();
}
/**
* Write preamble.
*
* @param writer the writer
* @throws IOException Signals that an I/O exception has occurred.
*/
public void writePreamble(java.io.Writer writer) throws IOException {
String data = null;
if (writer == null)
return;
writer.append(ATOM_HEADER+lineSeparator);
writer.append(ATOM_ROOT_OPEN_TAG+lineSeparator);
if (getInfo().length() > 0) {
try {
data = Val.escapeXml(getInfo());
writer.append(COMMENT_OPEN_TAG +lineSeparator+ data + COMMENT_CLOSE_TAG+lineSeparator);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "", e);
}
}
if (getId() != null) {
try {
data = Val.escapeXml(getId());
writer.append(ID_OPEN_TAG + data + ID_CLOSE_TAG+lineSeparator);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "", e);
}
}
if (getTitle() != null) {
try {
data = Val.escapeXml(getTitle());
writer.append(TITLE_OPEN_TAG + data + TITLE_CLOSE_TAG+lineSeparator);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "", e);
}
}
if (getLink() != null) {
try {
data = LINK_TAG.replace("?", Val.escapeXml(getEntryBaseUrl()));
writer.append(data+lineSeparator);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "", e);
}
}
if (getAuthor() != null) {
try {
data = Val.escapeXml(getAuthor());
writer.append(AUTHOR_OPEN_TAG + data + AUTHOR_CLOSE_TAG+lineSeparator);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "", e);
}
}
if (getUpdated() != null) {
try {
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_PATTERN);
data = format.format(getUpdated());
format = new SimpleDateFormat(TIME_FORMAT_PATTERN);
data = data + "T" + format.format(getUpdated()) + "Z";
data = UPDATED_OPEN_TAG + data + UPDATED_CLOSE_TAG;
writer.append(data+lineSeparator);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "", e);
}
}
if (getOsProps() != null) {
_writer.println(TOTAL_RESULTS_OPEN_TAG + getOsProps().getNumberOfHits()
+ TOTAL_RESULTS_CLOSE_TAG);
_writer.println(START_INDEX_OPEN_TAG + getOsProps().getStartRecord()
+ START_INDEX_CLOSE_TAG);
_writer.println(ITEMS_PER_PAGE_OPEN_TAG + getOsProps().getRecordsPerPage()
+ ITEMS_PER_PAGE_CLOSE_TAG);
}
}
/**
* Write end.
*
* @param writer the writer
* @throws IOException Signals that an I/O exception has occurred.
*/
public void writeEnd(java.io.Writer writer) throws IOException {
writer.write(ATOM_ROOT_CLOSE_TAG+lineSeparator);
}
/**
* Write to.
*
* @param writer the writer
*/
public void WriteTo(java.io.Writer writer) {
String data = null;
if (writer == null)
return;
try {
writePreamble(writer);
for (AtomEntry ae : Entries()) {
ae.WriteTo(writer);
}
writeEnd(writer);
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "", e);
}
}
public void addStringToXmlHeader(String replace) {
ATOM_ROOT_OPEN_TAG = ATOM_ROOT_OPEN_TAG.replace(">" , replace + ">");
}
}
}
| {
"content_hash": "70ca85eb71179dbfe78ce6448dae03f0",
"timestamp": "",
"source": "github",
"line_count": 939,
"max_line_length": 187,
"avg_line_length": 21.527156549520768,
"alnum_prop": 0.6197684772929652,
"repo_name": "treejames/GeoprocessingAppstore",
"id": "fb680f39cfd20512441a9118bae03b229e5b80f2",
"size": "20911",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/com/esri/gpt/control/georss/AtomFeedWriter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "105786"
},
{
"name": "HTML",
"bytes": "134248"
},
{
"name": "Java",
"bytes": "7261630"
},
{
"name": "JavaScript",
"bytes": "2856789"
},
{
"name": "XSLT",
"bytes": "2154930"
}
],
"symlink_target": ""
} |
goog.provide('ol.test.style.Circle');
goog.require('ol.style.AtlasManager');
goog.require('ol.style.Circle');
goog.require('ol.style.Fill');
goog.require('ol.style.Stroke');
describe('ol.style.Circle', function() {
describe('#constructor', function() {
it('creates a canvas if no atlas is used (no fill-style)', function() {
var style = new ol.style.Circle({radius: 10});
expect(style.getImage()).to.be.an(HTMLCanvasElement);
expect(style.getSize()).to.eql([21, 21]);
expect(style.getImageSize()).to.eql([21, 21]);
expect(style.getOrigin()).to.eql([0, 0]);
expect(style.getAnchor()).to.eql([10.5, 10.5]);
// hit-detection image is created, because no fill style is set
expect(style.getImage()).to.not.be(style.getHitDetectionImage());
expect(style.getHitDetectionImage()).to.be.an(HTMLCanvasElement);
expect(style.getHitDetectionImageSize()).to.eql([21, 21]);
});
it('creates a canvas if no atlas is used (fill-style)', function() {
var style = new ol.style.Circle({
radius: 10,
fill: new ol.style.Fill({
color: '#FFFF00'
})
});
expect(style.getImage()).to.be.an(HTMLCanvasElement);
expect(style.getSize()).to.eql([21, 21]);
expect(style.getImageSize()).to.eql([21, 21]);
expect(style.getOrigin()).to.eql([0, 0]);
expect(style.getAnchor()).to.eql([10.5, 10.5]);
// no hit-detection image is created, because fill style is set
expect(style.getImage()).to.be(style.getHitDetectionImage());
expect(style.getHitDetectionImage()).to.be.an(HTMLCanvasElement);
expect(style.getHitDetectionImageSize()).to.eql([21, 21]);
});
it('adds itself to an atlas manager (no fill-style)', function() {
var atlasManager = new ol.style.AtlasManager({initialSize: 512});
var style = new ol.style.Circle({radius: 10, atlasManager: atlasManager});
expect(style.getImage()).to.be.an(HTMLCanvasElement);
expect(style.getSize()).to.eql([21, 21]);
expect(style.getImageSize()).to.eql([512, 512]);
expect(style.getOrigin()).to.eql([1, 1]);
expect(style.getAnchor()).to.eql([10.5, 10.5]);
// hit-detection image is created, because no fill style is set
expect(style.getImage()).to.not.be(style.getHitDetectionImage());
expect(style.getHitDetectionImage()).to.be.an(HTMLCanvasElement);
expect(style.getHitDetectionImageSize()).to.eql([512, 512]);
});
it('adds itself to an atlas manager (fill-style)', function() {
var atlasManager = new ol.style.AtlasManager({initialSize: 512});
var style = new ol.style.Circle({
radius: 10,
atlasManager: atlasManager,
fill: new ol.style.Fill({
color: '#FFFF00'
})
});
expect(style.getImage()).to.be.an(HTMLCanvasElement);
expect(style.getSize()).to.eql([21, 21]);
expect(style.getImageSize()).to.eql([512, 512]);
expect(style.getOrigin()).to.eql([1, 1]);
expect(style.getAnchor()).to.eql([10.5, 10.5]);
// no hit-detection image is created, because fill style is set
expect(style.getImage()).to.be(style.getHitDetectionImage());
expect(style.getHitDetectionImage()).to.be.an(HTMLCanvasElement);
expect(style.getHitDetectionImageSize()).to.eql([512, 512]);
});
});
describe('#clone', function() {
it('creates a new ol.style.Circle', function() {
var original = new ol.style.Circle();
var clone = original.clone();
expect(clone).to.be.an(ol.style.Circle);
expect(clone).to.not.be(original);
});
it('copies all values', function() {
var original = new ol.style.Circle({
fill: new ol.style.Fill({
color: '#319FD3'
}),
stroke: new ol.style.Stroke({
color: '#319FD3'
}),
radius: 5,
snapToPixel: false
});
original.setOpacity(0.5);
original.setScale(1.5);
var clone = original.clone();
expect(original.getFill().getColor()).to.eql(clone.getFill().getColor());
expect(original.getOpacity()).to.eql(clone.getOpacity());
expect(original.getRadius()).to.eql(clone.getRadius());
expect(original.getScale()).to.eql(clone.getScale());
expect(original.getSnapToPixel()).to.eql(clone.getSnapToPixel());
expect(original.getStroke().getColor()).to.eql(clone.getStroke().getColor());
});
it('the clone does not reference the same objects as the original', function() {
var original = new ol.style.Circle({
fill: new ol.style.Fill({
color: '#319FD3'
}),
stroke: new ol.style.Stroke({
color: '#319FD3'
})
});
var clone = original.clone();
expect(original.getFill()).to.not.be(clone.getFill());
expect(original.getStroke()).to.not.be(clone.getStroke());
clone.getFill().setColor('#012345');
clone.getStroke().setColor('#012345');
expect(original.getFill().getColor()).to.not.eql(clone.getFill().getColor());
expect(original.getStroke().getColor()).to.not.eql(clone.getStroke().getColor());
});
});
describe('#getChecksum', function() {
it('calculates the same hash code for default options', function() {
var style1 = new ol.style.Circle();
var style2 = new ol.style.Circle();
expect(style1.getChecksum()).to.eql(style2.getChecksum());
});
it('calculates not the same hash code (radius)', function() {
var style1 = new ol.style.Circle();
var style2 = new ol.style.Circle({
radius: 5
});
expect(style1.getChecksum()).to.not.eql(style2.getChecksum());
});
it('calculates the same hash code (radius)', function() {
var style1 = new ol.style.Circle({
radius: 5
});
var style2 = new ol.style.Circle({
radius: 5
});
expect(style1.getChecksum()).to.eql(style2.getChecksum());
});
it('calculates not the same hash code (color)', function() {
var style1 = new ol.style.Circle({
radius: 5,
fill: new ol.style.Fill({
color: '#319FD3'
})
});
var style2 = new ol.style.Circle({
radius: 5,
stroke: new ol.style.Stroke({
color: '#319FD3'
})
});
expect(style1.getChecksum()).to.not.eql(style2.getChecksum());
});
it('calculates the same hash code (everything set)', function() {
var style1 = new ol.style.Circle({
radius: 5,
fill: new ol.style.Fill({
color: '#319FD3'
}),
stroke: new ol.style.Stroke({
color: '#319FD3',
lineCap: 'round',
lineDash: [5, 15, 25],
lineJoin: 'miter',
miterLimit: 4,
width: 2
})
});
var style2 = new ol.style.Circle({
radius: 5,
fill: new ol.style.Fill({
color: '#319FD3'
}),
stroke: new ol.style.Stroke({
color: '#319FD3',
lineCap: 'round',
lineDash: [5, 15, 25],
lineJoin: 'miter',
miterLimit: 4,
width: 2
})
});
expect(style1.getChecksum()).to.eql(style2.getChecksum());
});
it('calculates not the same hash code (stroke width differs)', function() {
var style1 = new ol.style.Circle({
radius: 5,
fill: new ol.style.Fill({
color: '#319FD3'
}),
stroke: new ol.style.Stroke({
color: '#319FD3',
lineCap: 'round',
lineDash: [5, 15, 25],
lineJoin: 'miter',
miterLimit: 4,
width: 3
})
});
var style2 = new ol.style.Circle({
radius: 5,
fill: new ol.style.Fill({
color: '#319FD3'
}),
stroke: new ol.style.Stroke({
color: '#319FD3',
lineCap: 'round',
lineDash: [5, 15, 25],
lineJoin: 'miter',
miterLimit: 4,
width: 2
})
});
expect(style1.getChecksum()).to.not.eql(style2.getChecksum());
});
it('invalidates a cached checksum if values change (fill)', function() {
var style1 = new ol.style.Circle({
radius: 5,
fill: new ol.style.Fill({
color: '#319FD3'
}),
stroke: new ol.style.Stroke({
color: '#319FD3'
})
});
var style2 = new ol.style.Circle({
radius: 5,
fill: new ol.style.Fill({
color: '#319FD3'
}),
stroke: new ol.style.Stroke({
color: '#319FD3'
})
});
expect(style1.getChecksum()).to.eql(style2.getChecksum());
style1.getFill().setColor('red');
expect(style1.getChecksum()).to.not.eql(style2.getChecksum());
});
it('invalidates a cached checksum if values change (stroke)', function() {
var style1 = new ol.style.Circle({
radius: 5,
fill: new ol.style.Fill({
color: '#319FD3'
}),
stroke: new ol.style.Stroke({
color: '#319FD3'
})
});
var style2 = new ol.style.Circle({
radius: 5,
fill: new ol.style.Fill({
color: '#319FD3'
}),
stroke: new ol.style.Stroke({
color: '#319FD3'
})
});
expect(style1.getChecksum()).to.eql(style2.getChecksum());
style1.getStroke().setWidth(4);
expect(style1.getChecksum()).to.not.eql(style2.getChecksum());
});
});
});
| {
"content_hash": "1068294c79152001f2c610441cc7b669",
"timestamp": "",
"source": "github",
"line_count": 288,
"max_line_length": 87,
"avg_line_length": 33.06944444444444,
"alnum_prop": 0.5685636287274255,
"repo_name": "fblackburn/ol3",
"id": "83ebbedbef03b2e6c197a58f4ee7fe1549d12bed",
"size": "9524",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/spec/ol/style/circle.test.js",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "23645"
},
{
"name": "GLSL",
"bytes": "2162"
},
{
"name": "HTML",
"bytes": "11925"
},
{
"name": "JavaScript",
"bytes": "3651021"
},
{
"name": "Makefile",
"bytes": "10426"
},
{
"name": "Python",
"bytes": "5840"
},
{
"name": "Shell",
"bytes": "3977"
}
],
"symlink_target": ""
} |
package org.xllapp.api.util;
import java.util.Map;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.core.JsonParser;
/**
* json工具类.
*
* @author dylan.chen Sep 21, 2013
*
*/
public class JSONHelper {
private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final static ObjectMapper LCWU_OBJECT_MAPPER = new ObjectMapper();
static{
OBJECT_MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES,true);
OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES,true);
LCWU_OBJECT_MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
LCWU_OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES,true);
LCWU_OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES,true);
LCWU_OBJECT_MAPPER.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
}
/**
* 将json字符串转换成Map对象
*
* json类型与java类型的对应关系查看:http://wiki.fasterxml.com/JacksonInFiveMinutess
*
* @author: 陈作朋 Aug 18, 2014
* @param json
* @return Map
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static Map<String,Object> toMap(String json) throws Exception {
return OBJECT_MAPPER.readValue(json, Map.class);
}
/**
* 将对象转换成json字符串
*
* @author: 陈作朋 Aug 18, 2014
* @param object
* @param camelCaseToLowerCaseWithUnderscores 将小写下划线分割的json属性名到驼峰格式的java属性名
* @return String
* @throws Exception
*/
public static String toJSONString(Object object, boolean camelCaseToLowerCaseWithUnderscores) throws Exception {
ObjectMapper mapper = camelCaseToLowerCaseWithUnderscores ? LCWU_OBJECT_MAPPER : OBJECT_MAPPER;
return mapper.writeValueAsString(object);
}
/**
* 将对象转换成json字符串
*
* @author: 陈作朋 Aug 18, 2014
* @param object
* @return String
* @throws Exception
*/
public static String toJSONString(Object object) throws Exception {
return toJSONString(object, false);
}
/**
* 类似toJSONString()方法,除了在转换过程出现异常时,返回""(空串).
*
* @author: 陈作朋 Aug 18, 2014
* @param object
* @param camelCaseToLowerCaseWithUnderscores 将小写下划线分割的json属性名到驼峰格式的java属性名
* @return String
*/
public static String toJSONStringQuietly(Object object, boolean camelCaseToLowerCaseWithUnderscores) {
ObjectMapper mapper = camelCaseToLowerCaseWithUnderscores ? LCWU_OBJECT_MAPPER : OBJECT_MAPPER;
try {
return mapper.writeValueAsString(object);
} catch (Exception e) {
return "";
}
}
/**
* 类似toJSONString()方法,除了在转换过程出现异常时,返回""(空串).
*
* @author: 陈作朋 Aug 18, 2014
* @param object
* @return String
*/
public static String toJSONStringQuietly(Object object) {
return toJSONStringQuietly(object, false);
}
@SuppressWarnings("unchecked")
public static <T> T getValue(String json, String... paths) throws Exception {
Object value = null;
Map<String, Object> node = OBJECT_MAPPER.readValue(json, Map.class);
for (int i = 0; i < paths.length; i++) {
value = node.get(paths[i]);
if (i == paths.length - 1) {
break;
} else if (value instanceof Map) {
node = (Map<String, Object>) value;
} else {
return null;
}
}
return (T)value;
}
}
| {
"content_hash": "b8d3085c35a32fc41bee644494e8c031",
"timestamp": "",
"source": "github",
"line_count": 119,
"max_line_length": 113,
"avg_line_length": 28.369747899159663,
"alnum_prop": 0.7313388625592417,
"repo_name": "chenzuopeng/xllapp-api-core",
"id": "45bad885504dc3e43d61b7c296d40ada98f115fc",
"size": "3660",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/xllapp/api/util/JSONHelper.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "207806"
},
{
"name": "XML",
"bytes": "3161"
}
],
"symlink_target": ""
} |
package com.franktan.popularmovies.model;
/**
* Created by tan on 27/08/2015.
*/
@SuppressWarnings("SimplifiableIfStatement")
public class Review {
private String id;
private String author;
private String content;
private String url;
public Review () {}
public Review (String id, String author, String content, String url) {
this.id = id;
this.author = author;
this.content = content;
this.url = url;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Review review = (Review) o;
if (!id.equals(review.id)) return false;
if (!author.equals(review.author)) return false;
if (!content.equals(review.content)) return false;
return url.equals(review.url);
}
@Override
public int hashCode() {
int result = id.hashCode();
result = 31 * result + author.hashCode();
result = 31 * result + content.hashCode();
result = 31 * result + url.hashCode();
return result;
}
@Override
public String toString() {
return "Review{" +
"author='" + author + '\'' +
", id='" + id + '\'' +
", content='" + content + '\'' +
", url='" + url + '\'' +
'}';
}
}
| {
"content_hash": "7ad105597d527422bac67bdbd22954a2",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 74,
"avg_line_length": 22.523255813953487,
"alnum_prop": 0.5338151781104801,
"repo_name": "frank-tan/Popular-Movies",
"id": "fb758c8c436708d176bb56176cdeb7bb4c99c551",
"size": "1937",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/franktan/popularmovies/model/Review.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "384235"
}
],
"symlink_target": ""
} |
package org.broadinstitute.hellbender.tools.examples;
import com.google.common.annotations.VisibleForTesting;
import htsjdk.variant.variantcontext.VariantContext;
import org.broadinstitute.barclay.argparser.Argument;
import org.broadinstitute.barclay.argparser.CommandLineProgramProperties;
import org.broadinstitute.hellbender.cmdline.StandardArgumentDefinitions;
import org.broadinstitute.hellbender.cmdline.programgroups.ExampleProgramGroup;
import org.broadinstitute.hellbender.engine.*;
import org.broadinstitute.hellbender.utils.SimpleInterval;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
* Counts the number of times each reference context is seen as well as how many times it's overlapped by reads and variants.
* Why you would want to do this is a mystery.
*
* This is a toy example to illustrate how to implement a ReferenceWalker.
*/
@CommandLineProgramProperties(
summary = "Example of how to implement a ReferenceWalker that uses reads and features as well as a custom window",
oneLineSummary = "Example of how to implement a ReferenceWalker",
programGroup = ExampleProgramGroup.class,
omitFromCommandLine = true)
public class ExampleReferenceWalker extends ReferenceWalker {
@Argument(fullName = StandardArgumentDefinitions.VARIANT_LONG_NAME,
shortName = StandardArgumentDefinitions.VARIANT_SHORT_NAME,
doc="variants to count overlaps of")
private FeatureInput<VariantContext> variants;
@VisibleForTesting
final Map<String, OverlapCounts> contextCounts = new HashMap<>();
@Override
protected SimpleInterval getReferenceWindow(SimpleInterval locus) {
// add one base of padding to each side of each reference locus.
return new SimpleInterval(locus.getContig(), Math.max(locus.getStart() -1, 1), locus.getStart()+1);
}
@Override
public void apply(ReferenceContext referenceContext, ReadsContext readsContext, FeatureContext featureContext) {
final byte[] bases = referenceContext.getBases();
final String baseString = new String(bases);
final OverlapCounts counts = contextCounts.getOrDefault(baseString, new OverlapCounts());
if(readsContext.iterator().hasNext()){
counts.overlappedByReads++;
}
if(!featureContext.getValues(variants).isEmpty()){
counts.overlappedByVariants++;
}
counts.timesSeen++;
contextCounts.put(baseString, counts);
}
@Override
public Object onTraversalSuccess(){
contextCounts.entrySet().stream()
.sorted(Comparator.comparing(Entry::getKey))
.forEachOrdered(entry -> System.out.println(entry.getKey() + " " + entry.getValue().toString()));
return 0;
}
@VisibleForTesting
static class OverlapCounts {
long timesSeen = 0;
long overlappedByReads = 0;
long overlappedByVariants = 0;
@Override
public String toString(){
return String.format("Seen: %d Reads %d Variants %d", timesSeen, overlappedByReads, overlappedByVariants);
}
}
}
| {
"content_hash": "bdb9b4f5ee2830aaa41201c28fc994f9",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 125,
"avg_line_length": 39.34567901234568,
"alnum_prop": 0.7194854094759963,
"repo_name": "broadinstitute/hellbender",
"id": "870fb36a135d3ff76cc7b4dff1fb977723f41f51",
"size": "3187",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/main/java/org/broadinstitute/hellbender/tools/examples/ExampleReferenceWalker.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "1878"
},
{
"name": "C++",
"bytes": "60687"
},
{
"name": "Java",
"bytes": "7458782"
},
{
"name": "Python",
"bytes": "10963"
},
{
"name": "R",
"bytes": "27481"
},
{
"name": "Shell",
"bytes": "11688"
}
],
"symlink_target": ""
} |
console.log('imported-module.js running');
const MODULE_EXPORTED_VALUE = 'MODULE';
export default MODULE_EXPORTED_VALUE
| {
"content_hash": "b1fe5576cdb97263bc33f519ba95bfcd",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 42,
"avg_line_length": 40,
"alnum_prop": 0.7916666666666666,
"repo_name": "nwjs/chromium.src",
"id": "040f8880f7b8f78dee0cb026096a838de70710b3",
"size": "120",
"binary": false,
"copies": "7",
"ref": "refs/heads/nw70",
"path": "third_party/blink/web_tests/http/tests/inspector-protocol/fetch/resources/service-workers/imported-module.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>svg</title>
<link rel="stylesheet" href="../../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../../../index.html" title="Chapter 1. Geometry">
<link rel="up" href="../svg.html" title="SVG (Scalable Vector Graphics)">
<link rel="prev" href="../svg.html" title="SVG (Scalable Vector Graphics)">
<link rel="next" href="svg_mapper.html" title="svg_mapper">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../svg.html"><img src="../../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../svg.html"><img src="../../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="svg_mapper.html"><img src="../../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h5 class="title">
<a name="geometry.reference.io.svg.svg"></a><a class="link" href="svg.html" title="svg">svg</a>
</h5></div></div></div>
<p>
<a class="indexterm" name="idp15080800"></a>
Manipulator to stream geometries as SVG.
</p>
<h6>
<a name="geometry.reference.io.svg.svg.h0"></a>
<span class="phrase"><a name="geometry.reference.io.svg.svg.synopsis"></a></span><a class="link" href="svg.html#geometry.reference.io.svg.svg.synopsis">Synopsis</a>
</h6>
<p>
</p>
<pre class="programlisting"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> <span class="identifier">Geometry</span><span class="special">></span>
<span class="identifier">svg_manipulator</span><span class="special"><</span><span class="identifier">Geometry</span><span class="special">></span> <span class="identifier">svg</span><span class="special">(</span><span class="identifier">Geometry</span> <span class="keyword">const</span> <span class="special">&</span> <span class="identifier">geometry</span><span class="special">,</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">string</span> <span class="keyword">const</span> <span class="special">&</span> <span class="identifier">style</span><span class="special">,</span> <span class="keyword">int</span> <span class="identifier">size</span> <span class="special">=</span> <span class="special">-</span><span class="number">1</span><span class="special">)</span></pre>
<p>
</p>
<h6>
<a name="geometry.reference.io.svg.svg.h1"></a>
<span class="phrase"><a name="geometry.reference.io.svg.svg.parameters"></a></span><a class="link" href="svg.html#geometry.reference.io.svg.svg.parameters">Parameters</a>
</h6>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Type
</p>
</th>
<th>
<p>
Concept
</p>
</th>
<th>
<p>
Name
</p>
</th>
<th>
<p>
Description
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
Geometry const &
</p>
</td>
<td>
<p>
Any type fulfilling a Geometry Concept
</p>
</td>
<td>
<p>
geometry
</p>
</td>
<td>
<p>
A model of the specified concept
</p>
</td>
</tr>
<tr>
<td>
<p>
std::string const &
</p>
</td>
<td>
</td>
<td>
<p>
style
</p>
</td>
<td>
<p>
String containing verbatim SVG style information
</p>
</td>
</tr>
<tr>
<td>
<p>
int
</p>
</td>
<td>
</td>
<td>
<p>
size
</p>
</td>
<td>
<p>
Optional size (used for SVG points) in SVG pixels. For linestrings,
specify linewidth in the SVG style information
</p>
</td>
</tr>
</tbody>
</table></div>
<h6>
<a name="geometry.reference.io.svg.svg.h2"></a>
<span class="phrase"><a name="geometry.reference.io.svg.svg.header"></a></span><a class="link" href="svg.html#geometry.reference.io.svg.svg.header">Header</a>
</h6>
<p>
<code class="computeroutput"><span class="preprocessor">#include</span> <span class="special"><</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">geometry</span><span class="special">/</span><span class="identifier">io</span><span class="special">/</span><span class="identifier">svg</span><span class="special">/</span><span class="identifier">write_svg</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">></span></code>
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2009-2013 Barend Gehrels, Bruno Lalande, Mateusz Loskot, Adam Wulkiewicz<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../svg.html"><img src="../../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../svg.html"><img src="../../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="svg_mapper.html"><img src="../../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"content_hash": "2fa67cb458e55222b32bac40f7b8f541",
"timestamp": "",
"source": "github",
"line_count": 161,
"max_line_length": 840,
"avg_line_length": 46.192546583850934,
"alnum_prop": 0.5203711173860428,
"repo_name": "gnu3ra/SCC15HPCRepast",
"id": "5ea55a899373f71d4f939f2f649830d2c56107ff",
"size": "7437",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "INSTALLATION/boost_1_54_0/libs/geometry/doc/html/geometry/reference/io/svg/svg.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "166901"
},
{
"name": "Awk",
"bytes": "4270"
},
{
"name": "Batchfile",
"bytes": "59453"
},
{
"name": "C",
"bytes": "89044644"
},
{
"name": "C#",
"bytes": "171870"
},
{
"name": "C++",
"bytes": "149286410"
},
{
"name": "CMake",
"bytes": "1277735"
},
{
"name": "CSS",
"bytes": "275497"
},
{
"name": "Cuda",
"bytes": "26749"
},
{
"name": "DIGITAL Command Language",
"bytes": "396318"
},
{
"name": "FORTRAN",
"bytes": "5955918"
},
{
"name": "Groff",
"bytes": "1536123"
},
{
"name": "HTML",
"bytes": "152716955"
},
{
"name": "IDL",
"bytes": "14"
},
{
"name": "Java",
"bytes": "1703162"
},
{
"name": "JavaScript",
"bytes": "132031"
},
{
"name": "Lex",
"bytes": "44890"
},
{
"name": "LiveScript",
"bytes": "299224"
},
{
"name": "Logos",
"bytes": "17671"
},
{
"name": "Makefile",
"bytes": "10089555"
},
{
"name": "Max",
"bytes": "36857"
},
{
"name": "Objective-C",
"bytes": "4756"
},
{
"name": "PHP",
"bytes": "74480"
},
{
"name": "Perl",
"bytes": "1444604"
},
{
"name": "Perl6",
"bytes": "9917"
},
{
"name": "PostScript",
"bytes": "4003"
},
{
"name": "Pure Data",
"bytes": "1710"
},
{
"name": "Python",
"bytes": "2280373"
},
{
"name": "QML",
"bytes": "593"
},
{
"name": "Rebol",
"bytes": "354"
},
{
"name": "Scilab",
"bytes": "3012"
},
{
"name": "Shell",
"bytes": "11997985"
},
{
"name": "Tcl",
"bytes": "1172"
},
{
"name": "TeX",
"bytes": "696679"
},
{
"name": "Visual Basic",
"bytes": "11578"
},
{
"name": "XSLT",
"bytes": "771726"
},
{
"name": "Yacc",
"bytes": "140274"
}
],
"symlink_target": ""
} |
package com.atlassian.jira.plugins.dvcs.model.dev;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import com.google.gson.annotations.SerializedName;
/**
*
*
*/
@XmlRootElement
@XmlAccessorType (XmlAccessType.FIELD)
public class RestPullRequest
{
private RestUser author;
@SerializedName("createdOn")
private long createdOn;
@SerializedName("updatedOn")
private long updatedOn;
private long id;
private String title;
private String url;
private String status;
private RestRef source;
private RestRef destination;
private List<RestParticipant> participants;
@SerializedName("commentCount")
private int commentCount;
private List<RestPrCommit> commits;
public RestUser getAuthor()
{
return author;
}
public void setAuthor(final RestUser author)
{
this.author = author;
}
public long getCreatedOn()
{
return createdOn;
}
public void setCreatedOn(final long createdOn)
{
this.createdOn = createdOn;
}
public long getId()
{
return id;
}
public void setId(final long id)
{
this.id = id;
}
public String getTitle()
{
return title;
}
public void setTitle(final String title)
{
this.title = title;
}
public String getUrl()
{
return url;
}
public void setUrl(final String url)
{
this.url = url;
}
public String getStatus()
{
return status;
}
public void setStatus(final String status)
{
this.status = status;
}
public long getUpdatedOn()
{
return updatedOn;
}
public void setUpdatedOn(final long updatedOn)
{
this.updatedOn = updatedOn;
}
public RestRef getSource()
{
return source;
}
public void setSource(final RestRef source)
{
this.source = source;
}
public RestRef getDestination()
{
return destination;
}
public void setDestination(final RestRef destination)
{
this.destination = destination;
}
public List<RestParticipant> getParticipants()
{
return participants;
}
public void setParticipants(final List<RestParticipant> participants)
{
this.participants = participants;
}
public int getCommentCount()
{
return commentCount;
}
public void setCommentCount(final int commentCount)
{
this.commentCount = commentCount;
}
public List<RestPrCommit> getCommits()
{
return commits;
}
public void setCommits(final List<RestPrCommit> commits)
{
this.commits = commits;
}
}
| {
"content_hash": "2b073f4045e13d8b21e616cb0ea5f936",
"timestamp": "",
"source": "github",
"line_count": 155,
"max_line_length": 73,
"avg_line_length": 18.419354838709676,
"alnum_prop": 0.6266199649737303,
"repo_name": "markphip/testing",
"id": "d86ed6678dd2e149aab07b0d938216f7582e438f",
"size": "2855",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "jira-dvcs-connector-api/src/main/java/com/atlassian/jira/plugins/dvcs/model/dev/RestPullRequest.java",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "23883"
},
{
"name": "Java",
"bytes": "2849213"
},
{
"name": "JavaScript",
"bytes": "67272"
},
{
"name": "Shell",
"bytes": "1442"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<link href="resources/grid.css" rel="stylesheet">
<link href="resources/grid-alignment.css" rel="stylesheet">
<script src="../../resources/check-layout.js"></script>
<style>
body {
margin: 0;
}
.grid {
grid: 50px 50px / 100px 100px;
position: relative;
width: 200px;
height: 300px;
}
.verticalGrid {
width: 300px;
height: 200px;
}
.cell {
width: 20px;
height: 40px;
}
</style>
</head>
<body onload="checkLayout('.grid')">
<p>This test checks that the align-content property is applied correctly.</p>
<div style="position: relative">
<p>direction: LTR | align-content: 'center'</p>
<div class="grid alignContentCenter" data-expected-width="200" data-expected-height="300">
<div class="cell firstRowFirstColumn" data-offset-x="0" data-offset-y="50" data-expected-width="20" data-expected-height="40"></div>
<div class="firstRowSecondColumn" data-offset-x="50" data-offset-y="50" data-expected-width="50" data-expected-height="100"></div>
<div class="secondRowFirstColumn" data-offset-x="0" data-offset-y="150" data-expected-width="50" data-expected-height="100"></div>
<div class="cell secondRowSecondColumn" data-offset-x="50" data-offset-y="150" data-expected-width="20" data-expected-height="40"></div>
</div>
</div>
<div style="position: relative">
<p>direction: LTR | align-content: 'left'</p>
<div class="grid alignContentLeft" data-expected-width="200" data-expected-height="300">
<div class="cell firstRowFirstColumn" data-offset-x="0" data-offset-y="0" data-expected-width="20" data-expected-height="40"></div>
<div class="firstRowSecondColumn" data-offset-x="50" data-offset-y="0" data-expected-width="50" data-expected-height="100"></div>
<div class="secondRowFirstColumn" data-offset-x="0" data-offset-y="100" data-expected-width="50" data-expected-height="100"></div>
<div class="cell secondRowSecondColumn" data-offset-x="50" data-offset-y="100" data-expected-width="20" data-expected-height="40"></div>
</div>
</div>
<div style="position: relative">
<p>direction: LTR | align-content: 'right'</p>
<div class="grid alignContentRight" data-expected-width="200" data-expected-height="300">
<div class="cell firstRowFirstColumn" data-offset-x="0" data-offset-y="0" data-expected-width="20" data-expected-height="40"></div>
<div class="firstRowSecondColumn" data-offset-x="50" data-offset-y="0" data-expected-width="50" data-expected-height="100"></div>
<div class="secondRowFirstColumn" data-offset-x="0" data-offset-y="100" data-expected-width="50" data-expected-height="100"></div>
<div class="cell secondRowSecondColumn" data-offset-x="50" data-offset-y="100" data-expected-width="20" data-expected-height="40"></div>
</div>
</div>
<div style="position: relative">
<p>direction: LTR | align-content: 'start'</p>
<div class="grid alignContentStart" data-expected-width="200" data-expected-height="300">
<div class="cell firstRowFirstColumn" data-offset-x="0" data-offset-y="0" data-expected-width="20" data-expected-height="40"></div>
<div class="firstRowSecondColumn" data-offset-x="50" data-offset-y="0" data-expected-width="50" data-expected-height="100"></div>
<div class="secondRowFirstColumn" data-offset-x="0" data-offset-y="100" data-expected-width="50" data-expected-height="100"></div>
<div class="cell secondRowSecondColumn" data-offset-x="50" data-offset-y="100" data-expected-width="20" data-expected-height="40"></div>
</div>
</div>
<div style="position: relative">
<p>direction: LTR | align-content: 'end'</p>
<div class="grid alignContentEnd" data-expected-width="200" data-expected-height="300">
<div class="cell firstRowFirstColumn" data-offset-x="0" data-offset-y="100" data-expected-width="20" data-expected-height="40"></div>
<div class="firstRowSecondColumn" data-offset-x="50" data-offset-y="100" data-expected-width="50" data-expected-height="100"></div>
<div class="secondRowFirstColumn" data-offset-x="0" data-offset-y="200" data-expected-width="50" data-expected-height="100"></div>
<div class="cell secondRowSecondColumn" data-offset-x="50" data-offset-y="200" data-expected-width="20" data-expected-height="40"></div>
</div>
</div>
<div style="position: relative">
<p>direction: LTR | align-content: 'flex-start'</p>
<div class="grid alignContentFlexStart" data-expected-width="200" data-expected-height="300">
<div class="cell firstRowFirstColumn" data-offset-x="0" data-offset-y="0" data-expected-width="20" data-expected-height="40"></div>
<div class="firstRowSecondColumn" data-offset-x="50" data-offset-y="0" data-expected-width="50" data-expected-height="100"></div>
<div class="secondRowFirstColumn" data-offset-x="0" data-offset-y="100" data-expected-width="50" data-expected-height="100"></div>
<div class="cell secondRowSecondColumn" data-offset-x="50" data-offset-y="100" data-expected-width="20" data-expected-height="40"></div>
</div>
</div>
<div style="position: relative">
<p>direction: LTR | align-content: 'flex-end</p>
<div class="grid alignContentFlexEnd" data-expected-width="200" data-expected-height="300">
<div class="cell firstRowFirstColumn" data-offset-x="0" data-offset-y="100" data-expected-width="20" data-expected-height="40"></div>
<div class="firstRowSecondColumn" data-offset-x="50" data-offset-y="100" data-expected-width="50" data-expected-height="100"></div>
<div class="secondRowFirstColumn" data-offset-x="0" data-offset-y="200" data-expected-width="50" data-expected-height="100"></div>
<div class="cell secondRowSecondColumn" data-offset-x="50" data-offset-y="200" data-expected-width="20" data-expected-height="40"></div>
</div>
</div>
<!-- Default alignment and initial values. -->
<div style="position: relative">
<p>direction: LTR | align-content: 'auto' (resolved to 'start')</p>
<div class="grid" data-expected-width="200" data-expected-height="300">
<div class="cell firstRowFirstColumn" data-offset-x="0" data-offset-y="0" data-expected-width="20" data-expected-height="40"></div>
<div class="firstRowSecondColumn" data-offset-x="50" data-offset-y="0" data-expected-width="50" data-expected-height="100"></div>
<div class="secondRowFirstColumn" data-offset-x="0" data-offset-y="100" data-expected-width="50" data-expected-height="100"></div>
<div class="cell secondRowSecondColumn" data-offset-x="50" data-offset-y="100" data-expected-width="20" data-expected-height="40"></div>
</div>
</div>
<!-- RTL direction. -->
<div style="position: relative">
<p>direction: RTL | align-content: 'center'</p>
<div class="grid directionRTL alignContentCenter" data-expected-width="200" data-expected-height="300">
<div class="cell firstRowFirstColumn" data-offset-x="180" data-offset-y="50" data-expected-width="20" data-expected-height="40"></div>
<div class="firstRowSecondColumn" data-offset-x="100" data-offset-y="50" data-expected-width="50" data-expected-height="100"></div>
<div class="secondRowFirstColumn" data-offset-x="150" data-offset-y="150" data-expected-width="50" data-expected-height="100"></div>
<div class="cell secondRowSecondColumn" data-offset-x="130" data-offset-y="150" data-expected-width="20" data-expected-height="40"></div>
</div>
</div>
<div style="position: relative">
<p>direction: RTL | align-content: 'left'</p>
<div class="grid directionRTL alignContentLeft" data-expected-width="200" data-expected-height="300">
<div class="cell firstRowFirstColumn" data-offset-x="180" data-offset-y="0" data-expected-width="20" data-expected-height="40"></div>
<div class="firstRowSecondColumn" data-offset-x="100" data-offset-y="0" data-expected-width="50" data-expected-height="100"></div>
<div class="secondRowFirstColumn" data-offset-x="150" data-offset-y="100" data-expected-width="50" data-expected-height="100"></div>
<div class="cell secondRowSecondColumn" data-offset-x="130" data-offset-y="100" data-expected-width="20" data-expected-height="40"></div>
</div>
</div>
<div style="position: relative">
<p>direction: RTL | align-content: 'right'</p>
<div class="grid directionRTL alignContentRight" data-expected-width="200" data-expected-height="300">
<div class="cell firstRowFirstColumn" data-offset-x="180" data-offset-y="0" data-expected-width="20" data-expected-height="40"></div>
<div class="firstRowSecondColumn" data-offset-x="100" data-offset-y="0" data-expected-width="50" data-expected-height="100"></div>
<div class="secondRowFirstColumn" data-offset-x="150" data-offset-y="100" data-expected-width="50" data-expected-height="100"></div>
<div class="cell secondRowSecondColumn" data-offset-x="130" data-offset-y="100" data-expected-width="20" data-expected-height="40"></div>
</div>
</div>
<div style="position: relative">
<p>direction: RTL | align-content: 'start'</p>
<div class="grid directionRTL alignContentStart" data-expected-width="200" data-expected-height="300">
<div class="cell firstRowFirstColumn" data-offset-x="180" data-offset-y="0" data-expected-width="20" data-expected-height="40"></div>
<div class="firstRowSecondColumn" data-offset-x="100" data-offset-y="0" data-expected-width="50" data-expected-height="100"></div>
<div class="secondRowFirstColumn" data-offset-x="150" data-offset-y="100" data-expected-width="50" data-expected-height="100"></div>
<div class="cell secondRowSecondColumn" data-offset-x="130" data-offset-y="100" data-expected-width="20" data-expected-height="40"></div>
</div>
</div>
<div style="position: relative">
<p>direction: RTL | align-content: 'end'</p>
<div class="grid directionRTL alignContentEnd" data-expected-width="200" data-expected-height="300">
<div class="cell firstRowFirstColumn" data-offset-x="180" data-offset-y="100" data-expected-width="20" data-expected-height="40"></div>
<div class="firstRowSecondColumn" data-offset-x="100" data-offset-y="100" data-expected-width="50" data-expected-height="100"></div>
<div class="secondRowFirstColumn" data-offset-x="150" data-offset-y="200" data-expected-width="50" data-expected-height="100"></div>
<div class="cell secondRowSecondColumn" data-offset-x="130" data-offset-y="200" data-expected-width="20" data-expected-height="40"></div>
</div>
</div>
</body>
</html>
| {
"content_hash": "30a066b419c1abb46fc10853da4ac585",
"timestamp": "",
"source": "github",
"line_count": 167,
"max_line_length": 145,
"avg_line_length": 63.73652694610779,
"alnum_prop": 0.68836903419767,
"repo_name": "Workday/OpenFrame",
"id": "fa7ce4d63901e35887120aa92a959242cc1f9caf",
"size": "10644",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "third_party/WebKit/LayoutTests/fast/css-grid-layout/grid-align-content.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<?php
//
// default settings
$DEFAULT_THEME = "_default";
$BLOG_SEARCH_PARAM = 's';
$BLOG_POST_ID_PARAM = 'p';
$BLOG_POST_DATE_FORMAT = "F j, Y";
$GOOGLE_ANALYTICS_TRACKING_CODE = <<<EOT
<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', '%{TRACKING_ID}', 'auto');
ga('send', 'pageview');
</script>
EOT;
$GOOGLE_ANALYTICS_TRACKING_ID = null;
//
// config|settings include
include 'config/settings.php';
includeThemeFileIfExists('_include-theme.php');
//
// some updates after include
setMenuBlog(getBlogTitle());
//
// config|settings getters and setters
function setAuthorName($name) {
global $AUTHOR_NAME;
$AUTHOR_NAME = htmlspecialchars($name);
}
function getAuthorName() {
global $AUTHOR_NAME;
return $AUTHOR_NAME;
}
function printAuthorName() {
echo getAuthorName();
}
function setAuthorTitle($title) {
global $AUTHOR_TITLE;
$AUTHOR_TITLE = htmlspecialchars($title);
}
function getAuthorTitle() {
global $AUTHOR_TITLE;
return $AUTHOR_TITLE;
}
function printAuthorTitle() {
echo getAuthorTitle();
}
function setAuthorDescription($description) {
global $AUTHOR_DESCRIPTION;
$AUTHOR_DESCRIPTION = htmlspecialchars($description);
}
function getAuthorDescription() {
global $AUTHOR_DESCRIPTION;
return $AUTHOR_DESCRIPTION;
}
function printAuthorDescription() {
echo getAuthorDescription();
}
function printAuthorBirthday() {
global $AUTHOR_BIRTHDAY;
echo $AUTHOR_BIRTHDAY;
}
function printAuthorAddress() {
global $AUTHOR_ADDRESS;
echo $AUTHOR_ADDRESS;
}
function setAuthorKeywords($keywords) {
global $AUTHOR_KEYWORDS;
$AUTHOR_KEYWORDS = htmlspecialchars($keywords);
}
function printAuthorKeywords($prefix = '', $sufix = '') {
global $AUTHOR_KEYWORDS;
echo $prefix . $AUTHOR_KEYWORDS . $sufix;
}
function setAuthorProfileLinkedIn($user) {
global $AUTHOR_PROFILES;
$AUTHOR_PROFILES['LinkedIn'] = 'http://www.linkedin.com/in/' . $user;
}
function setAuthorProfileGooglePlus($user) {
global $AUTHOR_PROFILES;
$AUTHOR_PROFILES['Google+'] = 'http://plus.google.com/' . $user;
}
function setAuthorProfileTwitter($user) {
global $AUTHOR_PROFILES;
$AUTHOR_PROFILES['Twitter'] = 'http://twitter.com/' . $user;
}
function setAuthorProfileGitHub($user) {
global $AUTHOR_PROFILES;
$AUTHOR_PROFILES['GitHub'] = 'http://github.com/' . $user;
}
function setAuthorProfileSourceForge($user) {
global $AUTHOR_PROFILES;
$AUTHOR_PROFILES['SourceForge'] = 'http://sourceforge.net/u/' . $user . '/profile/';
}
function getAuthorProfiles() {
global $AUTHOR_PROFILES;
return $AUTHOR_PROFILES;
}
function hasAuthorProfiles() {
return count(getAuthorProfiles()) > 0;
}
function printAuthorProfiles() {
if (hasAuthorProfiles()) {
if (!includeThemeFileIfExists('author-profiles.php')) {
includeDefaultThemeFileIfExists('author-profiles.php');
}
}
}
function setBlogTitle($title) {
global $BLOG_TITLE;
$BLOG_TITLE = htmlspecialchars($title);
}
function getBlogTitle() {
global $BLOG_TITLE;
return $BLOG_TITLE;
}
function printBlogTitle() {
echo getBlogTitle();
}
function setBlogDescription($description) {
global $BLOG_DESCRIPTION;
$BLOG_DESCRIPTION = htmlspecialchars($description);
}
function getBlogDescription() {
global $BLOG_DESCRIPTION;
return $BLOG_DESCRIPTION;
}
function printBlogDescription() {
echo getBlogDescription();
}
function setBlogKeywords($keywords) {
global $BLOG_KEYWORDS;
$BLOG_KEYWORDS = htmlspecialchars($keywords);
}
function getBlogKeywords() {
global $BLOG_KEYWORDS;
return $BLOG_KEYWORDS;
}
function printBlogKeywords($prefix = '', $sufix = '') {
echo $prefix . getBlogKeywords() . $sufix;
}
function setMenuBlog($title) {
global $MENU;
$MENU['blog.php'] = $title;
}
function getMenu() {
global $MENU;
return $MENU;
}
function printMenuItems($ulClass=null) {
if (function_exists('theme_printMenuItems')) {
theme_printMenuItems($ulClass);
}
else {
if (empty($ulClass)) {
echo '<ul>';
} else {
echo '<ul class="' . $ulClass . '">';
}
echo PHP_EOL;
foreach (getMenu() as $link => $title ) {
echo ' <li><a href="' . $link . '">' . $title . '</a></li>' . PHP_EOL;
}
echo '</ul>';
}
}
function setGoogleAnalyticsTrackingId($id) {
global $GOOGLE_ANALYTICS_TRACKING_ID;
$GOOGLE_ANALYTICS_TRACKING_ID = $id;
}
function printGoogleAnalyticsTrackingCode() {
global $GOOGLE_ANALYTICS_TRACKING_CODE;
global $GOOGLE_ANALYTICS_TRACKING_ID;
if (isset($GOOGLE_ANALYTICS_TRACKING_ID)) {
$buffer = $GOOGLE_ANALYTICS_TRACKING_CODE;
echo str_replace('%{TRACKING_ID}', $GOOGLE_ANALYTICS_TRACKING_ID, $GOOGLE_ANALYTICS_TRACKING_CODE);
}
}
function getLogo($folder, $size) {
$logo = 'config/' . $folder . '/logo-' . $size . '.png';
if (file_exists($logo)) {
return $logo;
}
$logo = 'config/' . $folder . '/logo-' . $size . '.jpg';
if (file_exists($logo)) {
return $logo;
}
$logo = 'config/' . $folder . '/logo-696.png';
if (file_exists($logo)) {
return $logo;
}
$logo = 'config/' . $folder . '/logo-696.jpg';
if (file_exists($logo)) {
return $logo;
}
throwMissingImageException($folder . ' logo');
}
//
// page type
$isIndex = false;
$isBlog = false;
$isBlogPost = false;
$isBlogFeed = false;
$isBlogSearch = false;
function isIndex() {
global $isIndex;
return $isIndex;
}
function setIsIndex() {
global $isIndex;
$isIndex = true;
}
function isBlog() {
global $isBlog;
return $isBlog;
}
function setIsBlog() {
global $isBlog;
$isBlog = true;
}
function isBlogPost() {
global $isBlogPost;
return $isBlogPost;
}
function setIsBlogPost() {
global $isBlogPost;
$isBlogPost = true;
}
function isBlogFeed() {
global $isBlogFeed;
return $isBlogFeed;
}
function setIsBlogFeed() {
global $isBlogFeed;
$isBlogFeed = true;
}
function isBlogSearch() {
global $isBlogSearch;
return $isBlogSearch;
}
function setIsBlogSearch() {
global $isBlogSearch;
$isBlogSearch = true;
}
//
// page content type
function setContentType($contentType) {
header('Content-Type: ' . $contentType . '; charset=UTF-8');
}
function setContentTypeHTML() {
setContentType('text/html');
}
function setContentTypeTEXT() {
setContentType('text/plain');
}
function setContentTypeRSS() {
setContentType('application/rss+xml');
}
function setContentTypeXML() {
setContentType('application/xml');
}
//
// themes files
function setTheme($theme) {
global $THEME;
global $DEFAULT_THEME;
if (isset($theme)) {
$THEME = $theme;
} else {
$THEME = $DEFAULT_THEME;
}
}
function getThemeFile($file) {
global $THEME;
return "themes/" . $THEME . "/" . $file;
}
function printThemeFile($file) {
echo getThemeFile($file);
}
function includeThemeFile($file) {
include getThemeFile($file);
}
function includeThemeFileIfExists($file) {
$file = getThemeFile($file);
if (file_exists($file)) {
include $file;
return true;
} else {
return false;
}
}
function getDefaultThemeFile($file) {
global $DEFAULT_THEME;
return "themes/" . $DEFAULT_THEME . "/" . $file;
}
function printDefaultThemeFile($file) {
echo getDefaultThemeFile($file);
}
function includeDefaultThemeFile($file) {
include getDefaultThemeFile($file);
}
function includeDefaultThemeFileIfExists($file) {
$file = getDefaultThemeFile($file);
if (file_exists($file)) {
include $file;
return true;
} else {
return false;
}
}
function includeThemeHtmlPrefix() {
include '_theme-html-prefix.php';
}
function includeThemeHtmlSuffix() {
include '_theme-html-suffix.php';
}
//
// index
function getIndexLink() {
return 'index.php';
}
function printIndexLink() {
echo getIndexLink();
}
//
// index
// - icon
function getIndexIcon() {
return 'config/index/icon.png';
}
//
// index
// - logo
function getIndexLogo($size) {
return getLogo('index', $size);
}
function printIndexLogo($size) {
echo getIndexLogo($size);
}
//
// index
// - experience
global $indexExperience;
function setIndexExperience($indexExperienceNew) {
global $indexExperience;
$indexExperience = $indexExperienceNew;
}
function getIndexExperience() {
global $indexExperience;
checkIfIsSet($indexExperience);
return $indexExperience;
}
function readIndexExperience() {
setIndexExperience(new DOMDocument());
getIndexExperience()->loadXML(file_get_contents('content/index/experience.xml'));
}
function printIndexExperienceTitle() {
global $indexExperience;
echo $indexExperience->documentElement->getAttribute("title");
}
function printIndexExperience() {
global $indexExperience;
foreach($indexExperience->getElementsByTagName('position') as $position) {
$title = $position->getElementsByTagName("title")->item(0)->textContent;
$company = $position->getElementsByTagName("company")->item(0)->textContent;
$period = $position->getElementsByTagName("period")->item(0)->textContent;
$location = $position->getElementsByTagName("location")->item(0)->textContent;
$description = $position->getElementsByTagName("description");
if ($description->length > 0) {
$description = $description->item(0)->textContent;
} else {
$description = "";
}
printExperiencePosition($title, $company, $period, $location, $description);
}
}
//
// index
// - skills
global $indexSkills;
function setIndexSkills($indexSkillsNew) {
global $indexSkills;
$indexSkills = $indexSkillsNew;
}
function getIndexSkills() {
global $indexSkills;
checkIfIsSet($indexSkills);
return $indexSkills;
}
function readIndexSkills() {
setIndexSkills(new DOMDocument());
getIndexSkills()->loadXML(file_get_contents('content/index/skills.xml'));
}
function printIndexSkillsTitle() {
global $indexSkills;
echo $indexSkills->documentElement->getAttribute("title");
}
function printIndexSkills() {
global $indexSkills;
foreach($indexSkills->getElementsByTagName('group') as $group) {
$title = $group->getElementsByTagName("title")->item(0)->textContent;
$description = $group->getElementsByTagName("description")->item(0)->textContent;
printSkillsGroup($title, $description);
}
}
//
// index
// - languages
global $indexLanguages;
function setIndexLanguages($indexLanguagesNew) {
global $indexLanguages;
$indexLanguages = $indexLanguagesNew;
}
function getIndexLanguages() {
global $indexLanguages;
checkIfIsSet($indexLanguages);
return $indexLanguages;
}
function readIndexLanguages() {
setIndexLanguages(new DOMDocument());
getIndexLanguages()->loadXML(file_get_contents('content/index/languages.xml'));
}
function printIndexLanguagesTitle() {
global $indexLanguages;
echo $indexLanguages->documentElement->getAttribute("title");
}
function printIndexLanguages() {
global $indexLanguages;
foreach($indexLanguages->getElementsByTagName('language') as $language) {
$name = $language->getElementsByTagName("name")->item(0)->textContent;
$level = $language->getElementsByTagName("level")->item(0)->textContent;
printLanguagesLanguage($name, $level);
}
}
//
// blog
function getBlogLink() {
return 'blog.php';
}
function printBlogLink() {
echo getBlogLink();
}
//
// blog
// - icon
function getBlogIcon() {
return 'config/blog/icon.png';
}
//
// blog
// - logo
function getBlogLogo($size) {
return getLogo('blog', $size);
}
function printBlogLogo($size) {
echo getBlogLogo($size);
}
//
// blog
// - search
function getBlogSearchParam() {
global $BLOG_SEARCH_PARAM;
return $BLOG_SEARCH_PARAM;
}
function printBlogSearchParam() {
echo getBlogSearchParam();
}
global $blogSearchQuery;
function setBlogSearchQuery($blogSearchQueryNew) {
global $blogSearchQuery;
$blogSearchQuery = $blogSearchQueryNew;
}
function getBlogSearchQuery() {
global $blogSearchQuery;
//checkIfIsSet($blogSearchQuery);
return $blogSearchQuery;
}
function printBlogSearchQuery() {
echo getBlogSearchQuery();
}
global $blogSearchResult;
function setBlogSearchResult($blogSearchResultNew) {
global $blogSearchResult;
$blogSearchResult = $blogSearchResultNew;
}
function getBlogSearchResult() {
global $blogSearchResult;
checkIfIsSet($blogSearchResult);
return $blogSearchResult;
}
function printBlogSearchResult() {
echo getBlogSearchResult();
}
//
// blog post ID
function getBlogPostIdParam() {
global $BLOG_POST_ID_PARAM;
return $BLOG_POST_ID_PARAM;
}
global $blogPostId;
function setBlogPostId($blogPostIdNew) {
global $blogPostId;
$blogPostId = $blogPostIdNew;
}
function getBlogPostId() {
global $blogPostId;
checkIfIsSet($blogPostId);
return $blogPostId;
}
function getBlogPostLink() {
return getBlogLink() . '?' . getBlogPostIdParam() . '=' . getBlogPostId();
}
function printBlogPostLink() {
echo getBlogPostLink();
}
function existsBlogPost() {
return getBlogPostId() && file_exists('content/blog/' . getBlogPostId());
}
//
// blog post config
global $postConfig;
function setBlogPostConfig($blogPostConfigNew) {
global $postConfig;
$postConfig = $blogPostConfigNew;
}
function getBlogPostConfig($key = null, $keyIsMandatory = true) {
global $postConfig;
checkIfIsSet($postConfig);
if (isset($key)) {
if ($keyIsMandatory) {
checkIfIsSet($postConfig, $key);
return $postConfig[$key];
} else {
if (isset($postConfig[$key])) {
return $postConfig[$key];
} else {
return null;
}
}
} else {
return $postConfig;
}
}
function readBlogPostConfig() {
setBlogPostConfig(json_decode(file_get_contents('content/blog/' . getBlogPostId() . '/config.json'), TRUE));
}
//
// blog post config
// - title
function getBlogPostTitle() {
return getBlogPostConfig('title');
}
function printBlogPostTitle() {
echo getBlogPostTitle();
}
//
// blog post config
// - date
function getBlogPostDateFormat() {
global $BLOG_POST_DATE_FORMAT;
return $BLOG_POST_DATE_FORMAT;
}
function getBlogPostDate($format = null) {
if (isset($format)) {
return date($format, strtotime(getBlogPostConfig('date')));
} else {
return date(getBlogPostDateFormat(), strtotime(getBlogPostConfig('date')));
}
}
function printBlogPostDate($format = null) {
echo getBlogPostDate($format);
}
function printBlogPostDateForHtmlTimeTag() {
echo getBlogPostDate('Y-m-d');
}
function getBlogPostDateModified($format = null) {
$dateModified = getBlogPostConfig('date-modified', false);
if ($dateModified !== null) {
if (isset($format)) {
return date($format, strtotime($dateModified));
} else {
return date(getBlogPostDateFormat(), strtotime($dateModified));
}
}
else {
return getBlogPostDate($format);
}
}
//
// blog post config
// - author
function getBlogPostAuthor() {
$author = getBlogPostConfig('author', false);
if ($author === null) {
return getAuthorName();
}
return $author;
}
function hasBlogPostAuthor() {
return getBlogPostConfig('author', false) !== null;
}
function printBlogPostAuthor() {
echo getBlogPostAuthor();
}
//
// blog post config
// - author-image
function getBlogPostAuthorImage($size) {
$size = sprintf("%03d", $size);
$author = getBlogPostConfig('author', false);
if ($author === null) {
$image = 'config/blog/author-' . $size . '.png';
if (file_exists($image)) {
return $image;
}
$image = 'config/blog/author-' . $size . '.jpg';
if (file_exists($image)) {
return $image;
}
$image = 'config/blog/author.png';
if (file_exists($image)) {
return $image;
}
$image = 'config/blog/author.jpg';
if (file_exists($image)) {
return $image;
}
throwMissingImageException('author image');
}
$email = getBlogPostConfig('author-email', false);
if ($email === null) {
return getGravatarImg(null, $size);
}
return getGravatarImg($email, $size);
}
function printBlogPostAuthorImage($size) {
echo getBlogPostAuthorImage($size);
}
//
// blog post config
// - author-website
function getBlogPostAuthorWebsite() {
$author = getBlogPostConfig('author', false);
if ($author === null) {
return getAbsoluteLink();
}
$website = getBlogPostConfig('author-website', false);
if ($website === null) {
return '';
}
return $website;
}
function printBlogPostAuthorWebsite() {
echo getBlogPostAuthorWebsite();
}
//
// blog post config
// - keywords
function getBlogPostKeywords() {
return getBlogPostConfig('keywords');
}
function printBlogPostKeywords() {
$isFirst = true;
foreach (getBlogPostKeywords() as $keyword) {
if ($isFirst) {
$isFirst = false;
} else {
echo ', ';
}
echo $keyword;
}
}
//
// blog post config
// - description
function getBlogPostDescription() {
return getBlogPostConfig('description');
}
function printBlogPostDescription() {
echo getBlogPostDescription();
}
//
// blog post config
// - resources
function getBlogPostResources() {
return getBlogPostConfig('resources', false);
}
function hasBlogPostResources() {
return getBlogPostResources() !== null;
}
function printBlogPostResources() {
global $postConfig;
echo PHP_EOL;
echo '<b>Resources</b>' . PHP_EOL;
echo '<ul>' . PHP_EOL;
foreach (getBlogPostResources() as $resource) {
echo '<li>';
if (is_array($resource)) {
echo '<a href="' . $resource[1] . '">' . $resource[0] . '</a>';
} else {
echo $resource;
}
echo '</li>';
echo PHP_EOL;
}
echo '</ul>';
}
//
// blog post image
function getBlogPostImage($size = '696') {
$image = 'content/blog/' . getBlogPostId() . '/image-' . $size . '.png';
if (file_exists($image)) {
return $image;
}
$image = 'content/blog/' . getBlogPostId() . '/image-' . $size . '.jpg';
if (file_exists($image)) {
return $image;
}
foreach (getBlogPostKeywords() as $keyword) {
$keyword = preg_replace('/\s+/', '-', $keyword);
$image = 'config/content/blog/images/' . $keyword . '-' . $size . '.png';
if (file_exists($image)) {
return $image;
}
$image = 'config/content/blog/images/' . $keyword . '-' . $size . '.jpg';
if (file_exists($image)) {
return $image;
}
}
return getBlogLogo($size);
}
//
// blog post content
global $blogPostContent;
function setBlogPostContent($blogPostContentNew) {
global $blogPostContent;
$blogPostContent = $blogPostContentNew;
}
function getBlogPostContent() {
global $blogPostContent;
return $blogPostContent;
}
function printBlogPostContent() {
$blogPostContentBuffer = getBlogPostContent();
if (!isset($blogPostContentBuffer)) {
throw new LogicException('blog post content is not read');
}
$blogPostContentBuffer = str_replace('="images/', '="content/blog/' . getBlogPostId() . '/images/', $blogPostContentBuffer);
$blogPostContentBuffer = str_replace(
array('<pre>' . "\r\n",
'<pre>' . "\r",
'<pre>' . "\n",
'<pre>' . "\n\r"),
'<pre>',
$blogPostContentBuffer);
if (!isBlogFeed() && function_exists('updateBlogPostContent')) {
$blogPostContentBuffer = updateBlogPostContent($blogPostContentBuffer);
}
echo $blogPostContentBuffer;
}
function readBlogPostContent() {
setBlogPostContent(file_get_contents('content/blog/' . getBlogPostId() . '/content.html'));
}
function getBlogPostFolders() {
return array_diff(scandir('content/blog/', 1), array(".", ".."));
}
//
// blog post share
// - on Twiter
function printBlogPostShareOnTwiterLink() {
$link = 'https://twitter.com/intent/tweet';
$link .= '?text=' . urlencode(getBlogPostTitle());
$link .= '&url=' . urlencode(getAbsoluteLink(getBlogPostLink()));
echo $link;
}
//
// HTML components
function getIndexHtmlTitle() {
return getAuthorName() . ' - ' . getAuthorTitle();
}
function getBlogHtmlTitle() {
return getBlogTitle() . ' | ' . getAuthorName();
}
function getBlogPostHtmlTitle() {
return getBlogPostTitle() . ' | ' . getAuthorName();
}
function getBlogSearchHtmlTitle() {
return 'Search: ' . getBlogSearchQuery() . ' | ' . getBlogTitle();
}
function printHtmlHeadTitle() {
if (isIndex()) {
echo getIndexHtmlTitle();
}
else if (isBlog()) {
if (isBlogPost()) {
echo getBlogPostHtmlTitle();
}
else if (isBlogSearch()) {
echo getBlogSearchHtmlTitle();
}
else {
echo getBlogHtmlTitle();
}
}
else {
throwUnknownPageTypeException();
}
}
function getIndexHtmlDescription() {
return getAuthorDescription();
}
function getBlogHtmlDescription() {
return getBlogTitle() . ' - ' . getBlogDescription();
}
function getBlogPostHtmlDescription() {
return getBlogPostDescription();
}
function getBlogSearchHtmlDescription() {
return 'Search: ' . getBlogSearchQuery() . ' | ' . getBlogHtmlDescription();
}
function printHtmlHeadMetaDescription() {
if (isIndex()) {
echo getIndexHtmlDescription();
}
else if (isBlog()) {
if (isBlogPost()) {
echo getBlogPostHtmlDescription();
}
else if (isBlogSearch()) {
echo getBlogSearchHtmlDescription();
}
else {
echo getBlogHtmlDescription();
}
}
else {
throwUnknownPageTypeException();
}
}
function printHtmlHeadMetaKeywords() {
if (isIndex()) {
printAuthorKeywords();
}
else if (isBlog()) {
if (isBlogPost()) {
printBlogPostKeywords();
}
else if (isBlogSearch()) {
printBlogKeywords('', ', ');
printBlogSearchQuery();
}
else {
printAuthorKeywords();
printBlogKeywords(', ', '');
}
}
else {
throwUnknownPageTypeException();
}
}
function printHtmlHeadMetaAuthor() {
if (isIndex()) {
printAuthorName();
}
else if (isBlog()) {
if (isBlogPost()) {
printBlogPostAuthor();
}
else {
printAuthorName();
}
}
else {
throwUnknownPageTypeException();
}
}
function printHtmlHeadLinkIcon() {
if (isIndex()) {
echo getIndexIcon();
}
else if (isBlog()) {
echo getBlogIcon();
}
else {
throwUnknownPageTypeException();
}
}
function printHtmlHeadLinkCanonical() {
echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}
function printHtmlHeadLinkShortlink() {
echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}
//
// utility funtions
function getAbsoluteLink($page = null) {
$prefix = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
$host = $_SERVER ['HTTP_HOST'];
$request = $_SERVER ['REQUEST_URI'];
$link = $prefix . $host;
if (strcmp('/', $request) !== 0) {
$link .= $request;
if (!endsWith($link, '/')) {
$link = dirname($link);
}
}
if ($page !== null) {
if (!endsWith($link, '/')) {
$link .= '/';
}
$link .= $page;
}
return $link;
}
function endsWith($string, $test) {
$strlen = strlen($string);
$testlen = strlen($test);
if ($testlen > $strlen) return false;
return substr_compare($string, $test, $strlen - $testlen, $testlen) === 0;
}
function throwUnknownPageTypeException() {
throw new LogicException('unknown page type');
}
function throwMissingImageException($image) {
throw new LogicException('missing image: ' . $image);
}
function checkIfIsSet($param, $index = null) {
if (isset($index)) {
if (!isset($param[$index])) {
throw new Exception('variable not set or NULL');
}
} else {
if (!isset($param)) {
throw new Exception('variable not set or NULL');
}
}
}
function redirect($url) {
header('Location: ' . $url);
exit();
}
function getGravatarImg($email, $size) {
$url = 'http://www.gravatar.com/avatar/';
if ($email != null) {
$url .= md5(strtolower(trim($email)));
}
$url .= '?d=mm';
$url .= '&size=' . $size;
return $url;
}
//
// google structured data
$GOOGLE_STRUCTURED_DATA_WEBSITE = <<<EOT
<script type="application/ld+json">
{
"@context" : "http://schema.org",
"@type" : "WebSite",
"name" : "%name%",
"url" : "%url%",
"potentialAction": {
"@type": "SearchAction",
"target": "%target%={search_term_string}",
"query-input": "required name=search_term_string"
},
"author": {
"@type": "Person",
"name": "%author.name%",
"url": "%author.url%"
}
}
</script>
EOT;
$GOOGLE_STRUCTURED_DATA_BLOG = <<<EOT
<script type="application/ld+json">
{
"@context" : "http://schema.org",
"@type" : "Blog",
"name" : "%name%",
"url" : "%url%",
"potentialAction": {
"@type": "SearchAction",
"target": "%target%={search_term_string}",
"query-input": "required name=search_term_string"
},
"author": {
"@type": "Person",
"name": "%author.name%",
"url": "%author.url%"
}
}
</script>
EOT;
$GOOGLE_STRUCTURED_DATA_BREADCRUMB_LIST = <<<EOT
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "BreadcrumbList",
"itemListElement": [{
"@type": "ListItem",
"position": 1,
"item": {
"@id": "%id1%",
"name": "%name1%"
}
}]
}
</script>
EOT;
$GOOGLE_STRUCTURED_DATA_BLOG_POSTING = <<<EOT
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "BlogPosting",
"mainEntityOfPage": {
"@type": "WebPage",
"@id": "%mainEntityOfPage.id%"
},
"headline": "%headline%",
"description": "%description%",
"datePublished": "%datePublished%",
"dateModified": "%dateModified%",
"image": {
"@type": "ImageObject",
"url": "%image.url%",
"width": %image.width%,
"height": %image.height%
},
"author": {
"@type": "Person",
"name": "%author.name%",
"url": "%author.url%"
},
"publisher": {
"@type": "Organization",
"name": "%publisher.name%",
"url": "%publisher.url%",
"logo": {
"@type": "ImageObject",
"url": "%publisher.logo.url%",
"width": %publisher.logo.width%,
"height": %publisher.logo.height%
}
}
}
</script>
EOT;
$GOOGLE_STRUCTURED_DATA_PERSON = <<<EOT
<script type="application/ld+json">
{
"@context" : "http://schema.org",
"@type" : "Person",
"name" : "%name%",
"url" : "%url%",
"sameAs" : [%sameas%
]
}
</script>
EOT;
function printGoogleStructuredData() {
if (isBlogSearch() || isBlogFeed()) {
return;
}
global $GOOGLE_STRUCTURED_DATA_WEBSITE;
global $GOOGLE_STRUCTURED_DATA_BLOG;
global $GOOGLE_STRUCTURED_DATA_BREADCRUMB_LIST;
global $GOOGLE_STRUCTURED_DATA_BLOG_POSTING;
global $GOOGLE_STRUCTURED_DATA_PERSON;
$buffer = '';
if (isIndex()) {
$bufferWebSite = $GOOGLE_STRUCTURED_DATA_WEBSITE;
$bufferWebSite = str_replace("%name%", getIndexHtmlTitle(), $bufferWebSite);
$bufferWebSite = str_replace("%url%", getAbsoluteLink(), $bufferWebSite);
$bufferWebSite = str_replace("%target%", getAbsoluteLink(getBlogLink() . '?' . getBlogSearchParam()), $bufferWebSite);
$bufferWebSite = str_replace("%author.name%", getAuthorName(), $bufferWebSite);
$bufferWebSite = str_replace("%author.url%", getAbsoluteLink(), $bufferWebSite);
$buffer .= $bufferWebSite;
}
else if (isBlog()) {
if (isBlogPost()) {
//
// BreadcrumbList
$bufferBreadcrumbList = $GOOGLE_STRUCTURED_DATA_BREADCRUMB_LIST;
$bufferBreadcrumbList = str_replace("%id1%", getAbsoluteLink(getBlogLink()), $bufferBreadcrumbList);
$bufferBreadcrumbList = str_replace("%name1%", getBlogHtmlTitle(), $bufferBreadcrumbList);
$buffer .= $bufferBreadcrumbList;
//
// BlogPosting
$bufferBlogPosting = $GOOGLE_STRUCTURED_DATA_BLOG_POSTING;
$bufferBlogPosting = str_replace('%mainEntityOfPage.id%', getAbsoluteLink(getBlogPostLink()), $bufferBlogPosting);
$bufferBlogPosting = str_replace('%headline%', getBlogPostTitle(), $bufferBlogPosting);
$bufferBlogPosting = str_replace('%description%', getBlogPostDescription(), $bufferBlogPosting);
$bufferBlogPosting = str_replace('%datePublished%', getBlogPostDate('c'), $bufferBlogPosting);
$bufferBlogPosting = str_replace('%dateModified%', getBlogPostDateModified('c'), $bufferBlogPosting);
$image = getAbsoluteLink(getBlogPostImage());
$imageSize = getimagesize($image);
$bufferBlogPosting = str_replace('%image.url%', $image, $bufferBlogPosting);
$bufferBlogPosting = str_replace('%image.width%', $imageSize[0], $bufferBlogPosting);
$bufferBlogPosting = str_replace('%image.height%', $imageSize[1], $bufferBlogPosting);
$bufferBlogPosting = str_replace('%author.name%', getBlogPostAuthor(), $bufferBlogPosting);
$bufferBlogPosting = str_replace('%author.url%', getBlogPostAuthorWebsite(), $bufferBlogPosting);
$bufferBlogPosting = str_replace('%publisher.name%', getBlogHtmlTitle(), $bufferBlogPosting);
$bufferBlogPosting = str_replace('%publisher.url%', getAbsoluteLink(getBlogLink()), $bufferBlogPosting);
$bufferBlogPosting = str_replace('%publisher.logo.url%', getAbsoluteLink(getBlogLogo('060')), $bufferBlogPosting);
$bufferBlogPosting = str_replace('%publisher.logo.width%', '60', $bufferBlogPosting);
$bufferBlogPosting = str_replace('%publisher.logo.height%', '60', $bufferBlogPosting);
$buffer .= $bufferBlogPosting;
}
else if (isBlogSearch()) {
// do nothing (at the moment)
}
else if (isBlogFeed()) {
// do nothing (at the moment)
}
else {
$bufferBlog = $GOOGLE_STRUCTURED_DATA_BLOG;
$bufferBlog = str_replace("%name%", getBlogHtmlTitle(), $bufferBlog);
$bufferBlog = str_replace("%url%", getAbsoluteLink(getBlogLink()), $bufferBlog);
$bufferBlog = str_replace("%target%", getAbsoluteLink(getBlogLink(). '?' . getBlogSearchParam()), $bufferBlog);
$bufferBlog = str_replace("%author.name%", getAuthorName(), $bufferBlog);
$bufferBlog = str_replace("%author.url%", getAbsoluteLink(), $bufferBlog);
$buffer .= $bufferBlog;
}
}
$bufferPerson = $GOOGLE_STRUCTURED_DATA_PERSON;
$bufferPerson = str_replace("%name%", getAuthorName(), $bufferPerson);
$bufferPerson = str_replace("%url%", getAbsoluteLink(), $bufferPerson);
$bufferSameAs = '';
if (hasAuthorProfiles()) {
foreach (getAuthorProfiles() as $title => $link ) {
$bufferSameAs .= PHP_EOL . ' "' . $link . '",';
}
}
$bufferSameAs = substr($bufferSameAs, 0, strlen($bufferSameAs) - 1);
$bufferPerson = str_replace("%sameas%", $bufferSameAs, $bufferPerson);
$buffer .= $bufferPerson;
echo $buffer;
}
?>
| {
"content_hash": "34918e97b4e07a32428ada13b5eb3a76",
"timestamp": "",
"source": "github",
"line_count": 1444,
"max_line_length": 125,
"avg_line_length": 21.68213296398892,
"alnum_prop": 0.6437765498738381,
"repo_name": "cristian-sulea/php-personal-web-site",
"id": "22fc3896432f001c2680fa6c49ada01d62332791",
"size": "31309",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "php-personal-web-site/WebContent/_include.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "156"
},
{
"name": "CSS",
"bytes": "97929"
},
{
"name": "HTML",
"bytes": "12865"
},
{
"name": "PHP",
"bytes": "48568"
}
],
"symlink_target": ""
} |
package com.cb.model;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import java.io.Serializable;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Indexed;
/**
* This class is used to represent an address with address,
* city, province and postal-code information.
*
* @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
*/
@Embeddable
@Indexed
public class Address extends BaseObject implements Serializable {
private static final long serialVersionUID = 3617859655330969141L;
private String address;
private String city;
private String province;
private String country;
private String postalCode;
@Column(length = 150)
@Field
public String getAddress() {
return address;
}
@Column(length = 50)
@Field
public String getCity() {
return city;
}
@Column(length = 100)
@Field
public String getProvince() {
return province;
}
@Column(length = 100)
@Field
public String getCountry() {
return country;
}
@Column(name = "postal_code", length = 15)
@Field(analyze= Analyze.NO)
public String getPostalCode() {
return postalCode;
}
public void setAddress(String address) {
this.address = address;
}
public void setCity(String city) {
this.city = city;
}
public void setCountry(String country) {
this.country = country;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public void setProvince(String province) {
this.province = province;
}
/**
* Overridden equals method for object comparison. Compares based on hashCode.
*
* @param o Object to compare
* @return true/false based on hashCode
*/
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Address)) {
return false;
}
final Address address1 = (Address) o;
return this.hashCode() == address1.hashCode();
}
/**
* Overridden hashCode method - compares on address, city, province, country and postal code.
*
* @return hashCode
*/
public int hashCode() {
int result;
result = (address != null ? address.hashCode() : 0);
result = 29 * result + (city != null ? city.hashCode() : 0);
result = 29 * result + (province != null ? province.hashCode() : 0);
result = 29 * result + (country != null ? country.hashCode() : 0);
result = 29 * result + (postalCode != null ? postalCode.hashCode() : 0);
return result;
}
/**
* Returns a multi-line String with key=value pairs.
*
* @return a String representation of this class.
*/
public String toString() {
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
.append("country", this.country)
.append("address", this.address)
.append("province", this.province)
.append("postalCode", this.postalCode)
.append("city", this.city).toString();
}
}
| {
"content_hash": "87dabc0429ce3c55f3f98f73f764cae9",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 97,
"avg_line_length": 26.936507936507937,
"alnum_prop": 0.619917501473188,
"repo_name": "deng947/nbstudio",
"id": "fe88d79648532656816f6b0b6c7dc41f2a8a1e55",
"size": "3394",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/cb/model/Address.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "51170"
},
{
"name": "Java",
"bytes": "528616"
},
{
"name": "JavaScript",
"bytes": "8849"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Liquid.NET.Constants;
using Liquid.NET.Symbols;
using Liquid.NET.Tags;
using Liquid.NET.Utils;
namespace Liquid.NET.Rendering
{
public class IncludeRenderer
{
public static string LOCALREGISTRY_FILE_KEY = "include";
private readonly RenderingVisitor _renderingVisitor;
public IncludeRenderer(RenderingVisitor renderingVisitor)
{
_renderingVisitor = renderingVisitor;
}
public void Render(IncludeTag includeTag,
ITemplateContext templateContext)
{
if (templateContext.FileSystem == null)
{
AddRenderingErrorToResult(new LiquidError{Message = " ERROR: FileSystem is not defined"});
return;
}
String virtualFileName = null;
LiquidExpressionEvaluator.Eval(includeTag.VirtualFileExpression, templateContext)
.WhenError(AddRenderingErrorToResult)
.WhenSuccess(result => { virtualFileName = ValueCaster.RenderAsString(result); });
if (virtualFileName == null) { return; }
//virtualFileName = ValueCaster.RenderAsString(virtualFilenameVar.SuccessResult.Value);
String snippet = templateContext.FileSystem.Include(templateContext, virtualFileName);
templateContext.SymbolTableStack.DefineLocalRegistry(LOCALREGISTRY_FILE_KEY, virtualFileName);
RenderSnippet(includeTag, templateContext, snippet, virtualFileName);
}
private void RenderSnippet(IncludeTag includeTag, ITemplateContext templateContext, String snippet,
String virtualFileName)
{
var snippetAstTry = CreateAstFromSnippet(templateContext, snippet, virtualFileName);
if (snippetAstTry.IsLeft)
{
foreach (var err in snippetAstTry.Left)
{
AddParsingErrorToResult(err);
}
return;
}
var snippetAst = snippetAstTry.Right;
//zzz
if (includeTag.ForExpression != null)
{
LiquidExpressionEvaluator.Eval(includeTag.ForExpression, templateContext)
.WhenError(AddRenderingErrorToResult)
.WhenSuccess(result =>
{
if (result.Value is LiquidHash)
{
// it seems to render as a single element if it's a dictionary.
RenderFromLiquidHash(includeTag, templateContext, virtualFileName, snippetAst);
}
else
{
RenderFromLiquidExpression(includeTag, templateContext, virtualFileName, result, snippetAst);
}
});
}
else
{
RenderIncludeBlock(includeTag, templateContext, virtualFileName, snippetAst);
}
}
private void RenderIncludeBlock(IncludeTag includeTag, ITemplateContext templateContext, String virtualFileName,
LiquidAST snippetAst)
{
Action<SymbolTable> action = localBlockScope =>
{
if (includeTag.WithExpression != null)
{
var withExpression = LiquidExpressionEvaluator.Eval(includeTag.WithExpression, templateContext);
localBlockScope.DefineLocalVariable(virtualFileName, withExpression.SuccessResult);
}
};
RenderBlock(includeTag, templateContext, snippetAst, action);
}
private void RenderFromLiquidExpression(IncludeTag includeTag, ITemplateContext templateContext, String virtualFileName,
Option<ILiquidValue> forExpressionOption, LiquidAST snippetAst)
{
ValueCaster.Cast<ILiquidValue, LiquidCollection>(forExpressionOption.Value)
.WhenError(AddRenderingErrorToResult)
.WhenSuccess(result =>
{
foreach (Option<ILiquidValue> val in (LiquidCollection) result.Value)
{
var val1 = val;
RenderBlock(includeTag, templateContext, snippetAst, localBlockScope => localBlockScope.DefineLocalVariable(virtualFileName, val1));
}
});
}
private void RenderFromLiquidHash(IncludeTag includeTag, ITemplateContext templateContext, String virtualFileName,
LiquidAST snippetAst)
{
Action<SymbolTable> action = localBlockScope => localBlockScope.DefineLocalVariable(
virtualFileName, LiquidExpressionEvaluator.Eval(includeTag.ForExpression, templateContext).SuccessResult);
RenderBlock(includeTag, templateContext, snippetAst, action);
}
private static Either<IList<LiquidError>, LiquidAST> CreateAstFromSnippet(ITemplateContext templateContext, String snippet,
String virtualFileName)
{
IList<LiquidError> parsingErrors = new List<LiquidError>();
var snippetAst = templateContext.ASTGenerator(snippet, parsingErrors.Add);
foreach (var error in parsingErrors.Where(error => String.IsNullOrEmpty(error.TokenSource)))
{
error.TokenSource = virtualFileName;
}
return parsingErrors.Any() ?
Either.Left<IList<LiquidError>, LiquidAST>(parsingErrors) :
Either.Right<IList<LiquidError>, LiquidAST>(snippetAst);
}
private void AddRenderingErrorToResult(LiquidError errorResult)
{
_renderingVisitor.RegisterRenderingError(errorResult);
}
private void AddParsingErrorToResult(LiquidError errorResult)
{
_renderingVisitor.RegisterParsingError(errorResult);
}
// public static LiquidAST GenerateSnippetAst(string snippet)
// {
// return new CachingLiquidASTGenerator(new LiquidASTGenerator()).Generate(snippet);
// //return new LiquidASTGenerator().Generate(snippet);
// }
private void RenderWithLocalScope(ITemplateContext templateContext, SymbolTable localBlockScope, TreeNode<IASTNode> rootNode)
{
templateContext.SymbolTableStack.Push(localBlockScope);
_renderingVisitor.StartWalking(rootNode);
templateContext.SymbolTableStack.Pop();
}
private static void DefineLocalVariables(
ITemplateContext templateContext,
SymbolTable localBlockScope,
IDictionary<string, TreeNode<LiquidExpression>> definitions)
{
foreach (var def in definitions)
{
var def1 = def;
LiquidExpressionEvaluator.Eval(def.Value, templateContext)
//.WhenError( err => //TODO: Is this necessary?
.WhenSuccess( result =>
localBlockScope.DefineLocalVariable(def1. Key,result));
}
}
private void RenderBlock(
IncludeTag includeTag,
ITemplateContext templateContext,
LiquidAST snippetAst,
Action<SymbolTable> renderAction)
{
var localBlockScope = new SymbolTable();
DefineLocalVariables(templateContext, localBlockScope, includeTag.Definitions);
renderAction(localBlockScope);
RenderWithLocalScope(templateContext, localBlockScope, snippetAst.RootNode);
}
}
}
| {
"content_hash": "0a92376cffac0ca1b0608e13291be7c7",
"timestamp": "",
"source": "github",
"line_count": 196,
"max_line_length": 156,
"avg_line_length": 40.704081632653065,
"alnum_prop": 0.5931311105540236,
"repo_name": "mikebridge/Liquid.NET",
"id": "103521a25790dae40652335392b37f229cd413a9",
"size": "7980",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Liquid.NET/src/Rendering/IncludeRenderer.cs",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ANTLR",
"bytes": "15619"
},
{
"name": "C",
"bytes": "1488"
},
{
"name": "C#",
"bytes": "838212"
},
{
"name": "Liquid",
"bytes": "2783"
},
{
"name": "Ruby",
"bytes": "10779"
}
],
"symlink_target": ""
} |
import Adafruit_Nokia_LCD as LCD
import Adafruit_GPIO.SPI as SPI
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
from re import sub
# Edison software SPI config:
SCLK = 35 # 10
DIN = 26 # 11
DC = 25 # 32
RST = 45 # 46
CS = 31 # 23
disp = LCD.PCD8544(DC, RST, SCLK, DIN, CS)
with open('contrast.txt', "r") as f:
contrast = int(sub('\\n', '', f.read()))
disp.begin(contrast = contrast)
image = Image.open('splash.png').resize((LCD.LCDWIDTH, LCD.LCDHEIGHT), Image.ANTIALIAS).convert('1')
draw = ImageDraw.Draw(image)
disp.image(image)
disp.display()
| {
"content_hash": "31e987504572a5bdce4921282070cd81",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 100,
"avg_line_length": 24.375,
"alnum_prop": 0.6905982905982906,
"repo_name": "projectbuendia/server-status",
"id": "01b78579525ad7dec2895be9788bea08c2cdf83c",
"size": "608",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "splash_screen.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "195458"
},
{
"name": "R",
"bytes": "1111"
},
{
"name": "Shell",
"bytes": "6172"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core" xmlns:wsc="http://www.mulesoft.org/schema/mule/wsc"
xmlns:http="http://www.mulesoft.org/schema/mule/http"
xmlns="http://www.mulesoft.org/schema/mule/core"
xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/wsc http://www.mulesoft.org/schema/mule/wsc/current/mule-wsc.xsd
http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd">
<configuration-properties doc:name="Configuration properties" file="mule-artifact.properties" />
<http:listener-config name="HTTP_Listener_config" doc:name="HTTP Listener config" doc:id="007cd910-ecad-41fd-a651-663fbfbd8e04" >
<http:listener-connection host="0.0.0.0" port="${http.port}" />
</http:listener-config>
<wsc:config name="Web_Service_Consumer_Config" doc:name="Web Service Consumer Config" doc:id="b371c47f-a4ef-41e9-91c7-b6bacc67fb2e" >
<wsc:connection wsdlLocation="tshirt.wsdl" service="TshirtService" port="TshirtServicePort" address="http://tshirt-service.cloudhub.io" />
</wsc:config>
<flow name="proxying-a-soap-apiFlow" doc:id="12a66cac-aeb4-4d23-b3ea-f3e13a60b7df" >
<http:listener config-ref="HTTP_Listener_config" path="/listInventory" doc:name="Listener" doc:id="dc219f5b-33ec-43eb-bd82-009319c610d8" outputMimeType="application/xml"/>
<wsc:consume config-ref="Web_Service_Consumer_Config" doc:name="Inventory service" doc:id="b4850a7c-18ad-47d8-a19d-cb05ca45d70f" operation="ListInventory">
</wsc:consume>
<ee:transform doc:name="Create response" doc:id="8a3e2c81-37e3-49f8-9b25-4c4399e0e272" >
<ee:message >
<ee:set-payload ><![CDATA[%dw 2.0
output application/xml
---
payload.body]]></ee:set-payload>
</ee:message>
</ee:transform>
</flow>
</mule>
| {
"content_hash": "c3ef392f83e9c18dca6c5fcbda432669",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 308,
"avg_line_length": 73.70967741935483,
"alnum_prop": 0.7557986870897155,
"repo_name": "ICfl/anypoint-examples",
"id": "90193605bcfc8775fe013f0afe6aff8c9e5c7681",
"size": "2285",
"binary": false,
"copies": "2",
"ref": "refs/heads/4.1",
"path": "proxying-a-soap-api/src/main/mule/proxying-a-soap-api.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "2244"
},
{
"name": "Java",
"bytes": "5318"
},
{
"name": "RAML",
"bytes": "8431"
}
],
"symlink_target": ""
} |
package com.microsoft.azure.management.network.v2020_04_01;
import com.microsoft.azure.arm.collection.SupportsCreating;
import com.microsoft.azure.arm.resources.collection.SupportsDeletingByResourceGroup;
import com.microsoft.azure.arm.resources.collection.SupportsBatchDeletion;
import com.microsoft.azure.arm.resources.collection.SupportsGettingByResourceGroup;
import rx.Observable;
import com.microsoft.azure.arm.resources.collection.SupportsListingByResourceGroup;
import com.microsoft.azure.arm.collection.SupportsListing;
import com.microsoft.azure.management.network.v2020_04_01.implementation.VpnSitesInner;
import com.microsoft.azure.arm.model.HasInner;
/**
* Type representing VpnSites.
*/
public interface VpnSites extends SupportsCreating<VpnSite.DefinitionStages.Blank>, SupportsDeletingByResourceGroup, SupportsBatchDeletion, SupportsGettingByResourceGroup<VpnSite>, SupportsListingByResourceGroup<VpnSite>, SupportsListing<VpnSite>, HasInner<VpnSitesInner> {
}
| {
"content_hash": "c412ef740db92d5a2fa978924b362b6a",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 273,
"avg_line_length": 51.73684210526316,
"alnum_prop": 0.8596134282807731,
"repo_name": "selvasingh/azure-sdk-for-java",
"id": "94d9ca80fe555d9f95ca4d1b90b46c94bc058d5f",
"size": "1213",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sdk/network/mgmt-v2020_04_01/src/main/java/com/microsoft/azure/management/network/v2020_04_01/VpnSites.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "29891970"
},
{
"name": "JavaScript",
"bytes": "6198"
},
{
"name": "PowerShell",
"bytes": "160"
},
{
"name": "Shell",
"bytes": "609"
}
],
"symlink_target": ""
} |
Riddle::Client::Versions[:search] = 0x117
Riddle::Client::Versions[:excerpt] = 0x102
class Riddle::Client
private
# Generation of the message to send to Sphinx for an excerpts request.
def excerpts_message(options)
message = Message.new
message.append [0, excerpt_flags(options)].pack('N2') # 0 = mode
message.append_string options[:index]
message.append_string options[:words]
# options
message.append_string options[:before_match]
message.append_string options[:after_match]
message.append_string options[:chunk_separator]
message.append_ints options[:limit], options[:around]
message.append_ints options[:limit_passages], options[:limit_words]
message.append_ints options[:start_passage_id]
message.append_string options[:html_strip_mode]
if Versions[:excerpt] >= 0x103
message.append_string options[:passage_boundary]
end
message.append_array options[:docs]
message.to_s
end
end | {
"content_hash": "22df2b5dc1963ebc7a405a63659b32ee",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 72,
"avg_line_length": 30.9375,
"alnum_prop": 0.702020202020202,
"repo_name": "Napolskih/thinking-sphinx",
"id": "961edba652f6cdf1101a20f6eea8ede0a00a2485",
"size": "990",
"binary": false,
"copies": "7",
"ref": "refs/heads/my",
"path": "vendor/riddle/lib/riddle/1.10/client.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Gherkin",
"bytes": "29622"
},
{
"name": "Ruby",
"bytes": "715181"
}
],
"symlink_target": ""
} |
//
// CommentsView.m
// Fashion
//
// Created by MRH-MAC on 15/7/9.
// Copyright (c) 2015年 MRH-MAC. All rights reserved.
//
#import "CommentsView.h"
@implementation CommentsView
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
@end
| {
"content_hash": "f90bfad7c2152294945ab1859862819a",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 74,
"avg_line_length": 16.782608695652176,
"alnum_prop": 0.694300518134715,
"repo_name": "Mrh08512/Fashion_Show",
"id": "d328c3c472ea82c808d4be1bc0d24b39e17c164b",
"size": "388",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Fashion1/Fashion/Controller/Mian/View/CommentsView.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "6059"
},
{
"name": "Objective-C",
"bytes": "1161308"
}
],
"symlink_target": ""
} |
package com.joywifi.knowledge.controller.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.joywifi.knowledge.annotation.CheckToken;
public class CheckTokenInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!(handler instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
CheckToken annotation = handlerMethod.getMethodAnnotation(CheckToken.class);
if (annotation == null) {
return true;
}
boolean removeToken = annotation.removeToken();
if (removeToken) {
if (isRepeatSubmit(request)) {
request.setAttribute("error", "重复提交");
return false;
}
request.getSession(false).removeAttribute("token");
}
return true;
}
private boolean isRepeatSubmit(HttpServletRequest request) {
String serverToken = (String) request.getSession(false).getAttribute("token");
if (serverToken == null) {
return true;
}
String clinetToken = request.getParameter("token");
if (clinetToken == null) {
return true;
}
if (!serverToken.equals(clinetToken)) {
return true;
}
return false;
}
} | {
"content_hash": "6c37b7e7fdd9a6d0beff17a2954956fe",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 121,
"avg_line_length": 31.46153846153846,
"alnum_prop": 0.652200488997555,
"repo_name": "roaki/knowledge-base",
"id": "f088c42b339f8563e273267b39b0c487115132bc",
"size": "1644",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/joywifi/knowledge/controller/interceptor/CheckTokenInterceptor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "821012"
},
{
"name": "HTML",
"bytes": "87747"
},
{
"name": "Java",
"bytes": "210787"
},
{
"name": "JavaScript",
"bytes": "1966367"
}
],
"symlink_target": ""
} |
package net.kuujo.copycat.io.transport;
import net.kuujo.copycat.io.Buffer;
import net.kuujo.copycat.util.Assert;
import net.kuujo.copycat.util.Listener;
import net.kuujo.copycat.util.Listeners;
import net.kuujo.copycat.util.ReferenceCounted;
import net.kuujo.copycat.util.concurrent.Context;
import net.kuujo.copycat.util.concurrent.Futures;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
/**
* Local connection.
*
* @author <a href="http://github.com/kuujo">Jordan Halterman</a>
*/
public class LocalConnection implements Connection {
private final UUID id;
private final Context context;
private final Set<LocalConnection> connections;
private LocalConnection connection;
private final Map<Class, HandlerHolder> handlers = new ConcurrentHashMap<>();
private final Listeners<Throwable> exceptionListeners = new Listeners<>();
private final Listeners<Connection> closeListeners = new Listeners<>();
public LocalConnection(UUID id, Context context) {
this(id, context, null);
}
public LocalConnection(UUID id, Context context, Set<LocalConnection> connections) {
this.id = id;
this.context = context;
this.connections = connections;
}
/**
* Connects the connection to another connection.
*/
public LocalConnection connect(LocalConnection connection) {
this.connection = connection;
return this;
}
@Override
public UUID id() {
return id;
}
/**
* Returns the current execution context.
*/
private Context getContext() {
Context context = Context.currentContext();
Assert.state(context != null, "not on a Copycat thread");
return context;
}
@Override
public <T, U> CompletableFuture<U> send(T request) {
Assert.notNull(request, "request");
Context context = getContext();
CompletableFuture<U> future = new CompletableFuture<>();
Buffer requestBuffer = context.serializer().writeObject(request);
connection.<U>receive(requestBuffer.flip()).whenCompleteAsync((responseBuffer, error) -> {
int status = responseBuffer.readByte();
if (status == 1) {
future.complete(context.serializer().readObject(responseBuffer));
} else {
future.completeExceptionally(context.serializer().readObject(responseBuffer));
}
responseBuffer.release();
}, context.executor());
if (request instanceof ReferenceCounted) {
((ReferenceCounted) request).release();
}
return future;
}
/**
* Receives a message.
*/
@SuppressWarnings("unchecked")
private CompletableFuture<Buffer> receive(Buffer requestBuffer) {
Context context = getContext();
Object request = context.serializer().readObject(requestBuffer);
requestBuffer.release();
HandlerHolder holder = handlers.get(request.getClass());
if (holder != null) {
MessageHandler<Object, Object> handler = holder.handler;
CompletableFuture<Buffer> future = new CompletableFuture<>();
holder.context.executor().execute(() -> {
handler.handle(request).whenCompleteAsync((response, error) -> {
Buffer responseBuffer = context.serializer().allocate();
if (error == null) {
responseBuffer.writeByte(1);
context.serializer().writeObject(response, responseBuffer);
} else {
responseBuffer.writeByte(0);
context.serializer().writeObject(error, responseBuffer);
}
future.complete(responseBuffer.flip());
if (response instanceof ReferenceCounted) {
((ReferenceCounted) response).release();
}
}, context.executor());
});
return future;
}
return Futures.exceptionalFuture(new TransportException("no handler registered"));
}
@Override
public <T, U> Connection handler(Class<T> type, MessageHandler<T, U> handler) {
Assert.notNull(type, "type");
if (handler != null) {
handlers.put(type, new HandlerHolder(handler, getContext()));
} else {
handlers.remove(type);
}
return this;
}
@Override
public Listener<Throwable> exceptionListener(Consumer<Throwable> listener) {
return exceptionListeners.add(Assert.notNull(listener, "listener"));
}
@Override
public Listener<Connection> closeListener(Consumer<Connection> listener) {
return closeListeners.add(Assert.notNull(listener, "listener"));
}
@Override
public CompletableFuture<Void> close() {
doClose();
connection.doClose();
return getContext().execute(() -> null);
}
/**
* Closes the connection.
*/
private void doClose() {
if (connections != null)
connections.remove(this);
for (Consumer<Connection> closeListener : closeListeners) {
context.executor().execute(() -> closeListener.accept(this));
}
}
/**
* Holds message handler and thread context.
*/
protected static class HandlerHolder {
private final MessageHandler handler;
private final Context context;
private HandlerHolder(MessageHandler handler, Context context) {
this.handler = handler;
this.context = context;
}
}
}
| {
"content_hash": "e4358a764546719059af3415a4ad18cf",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 94,
"avg_line_length": 29.407821229050278,
"alnum_prop": 0.6859802431610942,
"repo_name": "aruanruan/copycat",
"id": "86d4ea6026420a26b01f7e1a8ffca863915d8139",
"size": "5874",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "local/src/main/java/net/kuujo/copycat/io/transport/LocalConnection.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1349656"
},
{
"name": "Shell",
"bytes": "321"
}
],
"symlink_target": ""
} |
/******************************************************************************
This source file is part of the Avogadro project.
This source code is released under the 3-Clause BSD License, (see "LICENSE").
******************************************************************************/
#ifndef AVOGADRO_QTGUI_PERSISTENTATOM_H
#define AVOGADRO_QTGUI_PERSISTENTATOM_H
#include <avogadro/core/avogadrocore.h>
namespace Avogadro {
namespace QtGui {
/**
* @class PersistentAtom persistentatom.h <avogadro/qtcore/persistentatom.h>
* @brief The PersistentAtom object provides a container for a persistent atom
* reference that can be held onto. The atom() method gets the underlying atom
* using the unique ID mechanism of the molecule.
*/
template <typename Molecule_T>
class PersistentAtom
{
public:
typedef Molecule_T MoleculeType;
typedef typename Molecule_T::AtomType AtomType;
/**
* @brief Create a persistent atom, with the specified unique id.
* @param m The molecule the persistent atom belongs to.
* @param uniqueId The unique identifier for the atom.
*/
explicit PersistentAtom(MoleculeType* m = nullptr, Index uniqueId = MaxIndex)
: m_molecule(m), m_uniqueId(uniqueId)
{
}
/**
* @brief Create a persistent atom from a standard atom object.
* @param a The atom that a persistent reference should be created for.
*/
explicit PersistentAtom(const AtomType& a);
/**
* @brief Set the molecule and unique ID for the persistent object.
* @param m The molecule that contains the atom.
* @param uniqueId The unique ID of the atom.
*/
void set(MoleculeType* m, Index uniqueId);
/**
* @brief Set the persistent atom from a standard atom object.
* @param a The atom that a persistent reference should be created for.
*/
void set(const AtomType& a);
/**
* @brief Reset the object to an invalid state.
*/
void reset();
/**
* @return True if the persistent atom is valid.
*/
bool isValid() const;
/**
* @return The molecule the atom is a part of.
*/
MoleculeType* molecule() const { return m_molecule; }
/**
* @brief The persistent unique ID of the atom.
* @return The unique ID of the atom.
*/
Index uniqueIdentifier() const { return m_uniqueId; }
/**
* @brief Obtain the atom being held by the persistent object.
* @return A reference to the atom held by the object.
*/
AtomType atom() const;
private:
MoleculeType* m_molecule;
Index m_uniqueId;
};
template <typename Molecule_T>
PersistentAtom<Molecule_T>::PersistentAtom(const AtomType& a)
: m_molecule(dynamic_cast<MoleculeType*>(a.molecule()))
{
m_uniqueId = m_molecule ? m_molecule->atomUniqueId(a) : MaxIndex;
}
template <typename Molecule_T>
void PersistentAtom<Molecule_T>::set(MoleculeType* m, Index uniqueId)
{
m_molecule = m;
m_uniqueId = uniqueId;
}
template <typename Molecule_T>
void PersistentAtom<Molecule_T>::set(const AtomType& a)
{
m_molecule = dynamic_cast<MoleculeType*>(a.molecule());
m_uniqueId = m_molecule ? m_molecule->atomUniqueId(a) : MaxIndex;
}
template <typename Molecule_T>
void PersistentAtom<Molecule_T>::reset()
{
set(nullptr, MaxIndex);
}
template <typename Molecule_T>
bool PersistentAtom<Molecule_T>::isValid() const
{
return atom().isValid();
}
template <typename Molecule_T>
typename Molecule_T::AtomType PersistentAtom<Molecule_T>::atom() const
{
return m_molecule ? m_molecule->atomByUniqueId(m_uniqueId) : AtomType();
}
} // End of QtGui namespace
} // End of Avogadro namespace
#endif // AVOGADRO_QTGUI_PERSISTENTATOM_H
| {
"content_hash": "2cd248fcb448200fd35e999d65931b09",
"timestamp": "",
"source": "github",
"line_count": 130,
"max_line_length": 79,
"avg_line_length": 27.592307692307692,
"alnum_prop": 0.6780039029829942,
"repo_name": "OpenChemistry/avogadrolibs",
"id": "1e0027f6c8c94bf20c8222db5820f48e73e04cd0",
"size": "3587",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "avogadro/qtgui/persistentatom.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "2436"
},
{
"name": "C++",
"bytes": "4162333"
},
{
"name": "CMake",
"bytes": "93732"
},
{
"name": "Dockerfile",
"bytes": "395"
},
{
"name": "GLSL",
"bytes": "21319"
},
{
"name": "Perl",
"bytes": "13067"
},
{
"name": "Python",
"bytes": "33352"
},
{
"name": "Shell",
"bytes": "4879"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView android:id="@+id/thumbImage"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerInParent="true"
android:background="@drawable/imgw_border"
/>
<ProgressBar
android:id="@+id/pb"
android:layout_centerInParent="true"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:id="@+id/overlay"
android:layout_width="48px"
android:layout_height="48px"
android:layout_marginRight="4dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
/>
<CheckBox
android:id="@+id/check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:visibility="invisible"/>
</RelativeLayout> | {
"content_hash": "dd491d5e76dab5d7b69d9d0fb59a9083",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 74,
"avg_line_length": 33.30555555555556,
"alnum_prop": 0.6472060050041701,
"repo_name": "FrancescoPileo/FacePlusPlusTester",
"id": "22a641d3ffcb1ce652faf589af7d589a79795701",
"size": "1199",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/layout/gallery_item.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "436775"
}
],
"symlink_target": ""
} |
"""A library containing exception types used by Endpoints ProtoRPC services."""
import httplib
from protorpc import remote
class ServiceException(remote.ApplicationError):
"""Base class for request/service exceptions in Endpoints."""
def __init__(self, message=None):
super(ServiceException, self).__init__(message,
httplib.responses[self.http_status])
class BadRequestException(ServiceException):
"""Bad request exception that is mapped to a 400 response."""
http_status = httplib.BAD_REQUEST
class UnauthorizedException(ServiceException):
"""Unauthorized exception that is mapped to a 401 response."""
http_status = httplib.UNAUTHORIZED
class ForbiddenException(ServiceException):
"""Forbidden exception that is mapped to a 403 response."""
http_status = httplib.FORBIDDEN
class NotFoundException(ServiceException):
"""Not found exception that is mapped to a 404 response."""
http_status = httplib.NOT_FOUND
class ConflictException(ServiceException):
"""Conflict exception that is mapped to a 409 response."""
http_status = httplib.CONFLICT
class GoneException(ServiceException):
"""Resource Gone exception that is mapped to a 410 response."""
http_status = httplib.GONE
class PreconditionFailedException(ServiceException):
"""Precondition Failed exception that is mapped to a 412 response."""
http_status = httplib.PRECONDITION_FAILED
class RequestEntityTooLargeException(ServiceException):
"""Request entity too large exception that is mapped to a 413 response."""
http_status = httplib.REQUEST_ENTITY_TOO_LARGE
class InternalServerErrorException(ServiceException):
"""Internal server exception that is mapped to a 500 response."""
http_status = httplib.INTERNAL_SERVER_ERROR
| {
"content_hash": "4ccfbdaa72df80bd448e08a2579bc29c",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 79,
"avg_line_length": 28.93548387096774,
"alnum_prop": 0.750278706800446,
"repo_name": "justingrayston/gae-python-endpoints-patch",
"id": "25c6513ff33ff705ac1ab4c191fee7a0d0700848",
"size": "2395",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "endpoints-1.0/endpoints/api_exceptions.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "135881"
}
],
"symlink_target": ""
} |
<?php
namespace DreamFactory\Core\Models;
use DreamFactory\Core\Components\RegisterContact;
use DreamFactory\Core\Database\Schema\RelationSchema;
use DreamFactory\Core\Events\UserCreatingEvent;
use DreamFactory\Core\Events\UserDeletedEvent;
use DreamFactory\Core\Exceptions\NotFoundException;
use DreamFactory\Core\Exceptions\ForbiddenException;
use DreamFactory\Core\Exceptions\InternalServerErrorException;
use DreamFactory\Core\Exceptions\BadRequestException;
use DreamFactory\Core\Utility\DataFormatter;
use DreamFactory\Core\Utility\JWTUtilities;
use DreamFactory\Core\Utility\Session;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;
use Validator;
/**
* User
*
* @property integer $id
* @property string $name
* @property string $username
* @property string $first_name
* @property string $last_name
* @property string $email
* @property string $phone
* @property string $confirm_code
* @property string $remember_token
* @property string $adldap
* @property string $oauth_provider
* @property string $security_question
* @property string $security_answer
* @property int $default_app_id
* @property boolean $is_active
* @property boolean $is_sys_admin
* @property string $last_login_date
* @property string $created_date
* @property string $last_modified_date
* @method static \Illuminate\Database\Query\Builder|User whereId($value)
* @method static \Illuminate\Database\Query\Builder|User whereName($value)
* @method static \Illuminate\Database\Query\Builder|User whereFirstName($value)
* @method static \Illuminate\Database\Query\Builder|User whereLastName($value)
* @method static \Illuminate\Database\Query\Builder|User whereEmail($value)
* @method static \Illuminate\Database\Query\Builder|User whereIsActive($value)
* @method static \Illuminate\Database\Query\Builder|User whereIsSysAdmin($value)
* @method static \Illuminate\Database\Query\Builder|User whereCreatedDate($value)
* @method static \Illuminate\Database\Query\Builder|User whereLastModifiedDate($value)
*/
class User extends BaseSystemModel implements AuthenticatableContract, CanResetPasswordContract
{
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'user';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'username',
'ldap_username',
'first_name',
'last_name',
'email',
'is_active',
'phone',
'security_question',
'security_answer',
'adldap',
'oauth_provider',
'last_login_date',
'default_app_id',
'saml'
];
/**
* Input validation rules.
*
* @type array
*/
protected $rules = [
'name' => 'required|max:255',
'email' => 'required|email|max:255',
'username' => 'min:6|unique:user,username|regex:/^\S*$/u|nullable'
];
/**
* Appended fields.
*
* @var array
*/
protected $appends = ['confirmed', 'expired'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['is_sys_admin', 'password', 'remember_token', 'security_answer', 'confirm_code'];
/**
* Field type casting
*
* @var array
*/
protected $casts = ['is_active' => 'boolean', 'is_sys_admin' => 'boolean', 'id' => 'integer'];
/**
* Gets account confirmation status.
*
* @return string
*/
public function getConfirmedAttribute()
{
$code = $this->confirm_code;
if ($code === 'y' || is_null($code)) {
return true;
} else {
return false;
}
}
/**
* Shows confirmation expiration.
*
* @return bool
*/
public function getExpiredAttribute()
{
return $this->isConfirmationExpired();
}
/**
* Checks to se if confirmation period is expired.
*
* @return bool
*/
public function isConfirmationExpired()
{
$ttl = \Config::get('df.confirm_code_ttl', 1440);
$lastModTime = strtotime($this->last_modified_date);
$code = $this->confirm_code;
if ('y' !== $code && !is_null($code) && ((time() - $lastModTime) > ($ttl * 60))) {
return true;
} else {
return false;
}
}
/**
* Assigns a role to a user for all apps in the system.
*
* @param $user
* @param $defaultRole
*
* @return bool
* @throws \Exception
*/
public static function applyDefaultUserAppRole($user, $defaultRole)
{
$apps = App::all();
if (count($apps) === 0) {
return false;
}
foreach ($apps as $app) {
if (!UserAppRole::whereUserId($user->id)->whereAppId($app->id)->exists()) {
$userAppRoleData = [
'user_id' => $user->id,
'app_id' => $app->id,
'role_id' => $defaultRole
];
UserAppRole::create($userAppRoleData);
}
}
return true;
}
/**
* Applies App to Role mapping to a user.
*
* @param User $user
* @param integer $serviceId
*/
public static function applyAppRoleMapByService($user, $serviceId)
{
$maps = AppRoleMap::whereServiceId($serviceId)->get();
foreach ($maps as $map) {
UserAppRole::whereUserId($user->id)->whereAppId($map->app_id)->delete();
$userAppRoleData = [
'user_id' => $user->id,
'app_id' => $map->app_id,
'role_id' => $map->role_id
];
UserAppRole::create($userAppRoleData);
}
}
/**
* {@inheritdoc}
*/
public function validate($data, $throwException = true)
{
$loginAttribute = strtolower(config('df.login_attribute', 'email'));
if ($loginAttribute === 'username') {
$this->rules['username'] = str_replace('|nullable', '|required', $this->rules['username']);
}
return parent::validate($data, $throwException);
}
/**
* @param $password
*
* @throws \DreamFactory\Core\Exceptions\BadRequestException
*/
public static function validatePassword($password)
{
$data = [
'password' => $password
];
$rule = [
'password' => 'min:6'
];
$validator = Validator::make($data, $rule);
if ($validator->fails()) {
$msg = $validator->errors()->getMessages();
$errorString = DataFormatter::validationErrorsToString($msg);
throw new BadRequestException('Invalid data supplied.' . $errorString, null, null, $msg);
}
}
/**
* {@inheritdoc}
*/
protected static function createInternal($record, $params = [])
{
try {
if (!isset($record['name'])) {
// potentially combine first and last
$first = (isset($record['first_name']) ? $record['first_name'] : null);
$last = (isset($record['last_name']) ? $record['last_name'] : null);
$name = (!empty($first)) ? $first : '';
$name .= (!empty($name) && !empty($last)) ? ' ' : '';
$name .= (!empty($last)) ? $last : '';
if (empty($name)) {
// use the first part of their email or the username
$email = (isset($record['email']) ? $record['email'] : null);
$name = (!empty($email) && strpos($email, '@')) ? strstr($email, '@', true) : '';
}
$record['name'] = $name;
}
$password = array_get($record, 'password');
if (!empty($password)) {
static::validatePassword($password);
}
$model = static::create($record);
if (array_get_bool($params, 'admin') && array_get_bool($record, 'is_sys_admin')) {
$model->is_sys_admin = 1;
}
$model->password = $password;
$model->save();
} catch (\Exception $ex) {
if (!$ex instanceof ForbiddenException && !$ex instanceof BadRequestException) {
throw new InternalServerErrorException('Failed to create resource: ' . $ex->getMessage());
} else {
throw $ex;
}
}
return static::buildResult($model, $params);
}
/**
* {@inheritdoc}
*/
public static function updateInternal($id, $record, $params = [])
{
if (empty($record)) {
throw new BadRequestException('There are no fields in the record to create . ');
}
if (empty($id)) {
//Todo:perform logging below
//Log::error( 'Update request with no id supplied: ' . print_r( $record, true ) );
throw new BadRequestException('Identifying field "id" can not be empty for update request . ');
}
/** @type User $model */
$model = static::find($id);
if (!$model instanceof Model) {
throw new NotFoundException("Record with identifier '$id' not found.");
}
$pk = $model->primaryKey;
// Remove the PK from the record since this is an update
unset($record[$pk]);
try {
if ($model->is_sys_admin && !array_get_bool($params, 'admin')) {
throw new ForbiddenException('Not allowed to change an admin user.');
} elseif (array_get_bool($params, 'admin') && !$model->is_sys_admin) {
throw new BadRequestException('Cannot update a non-admin user.');
}
$password = array_get($record, 'password');
if (!empty($password)) {
$model->password = $password;
static::validatePassword($password);
}
$model->update($record);
return static::buildResult($model, $params);
} catch (\Exception $ex) {
if (!$ex instanceof ForbiddenException && !$ex instanceof BadRequestException) {
throw new InternalServerErrorException('Failed to update resource: ' . $ex->getMessage());
} else {
throw $ex;
}
}
}
/**
* {@inheritdoc}
*/
public function update(array $attributes = [], array $options = [])
{
$oldEmail = $this->email;
$updated = parent::update($attributes);
if ($updated && $this->is_sys_admin) {
$newEmail = $this->email;
if (('user@example.com' === $oldEmail) && ('user@example.com' !== $newEmail)) {
// Register user
RegisterContact::registerUser($this);
}
}
return $updated;
}
/**
* {@inheritdoc}
*/
public static function deleteInternal($id, $record, $params = [])
{
if (empty($record)) {
throw new BadRequestException('There are no fields in the record to create . ');
}
if (empty($id)) {
//Todo:perform logging below
//Log::error( 'Update request with no id supplied: ' . print_r( $record, true ) );
throw new BadRequestException('Identifying field "id" can not be empty for update request . ');
}
/** @type User $model */
$model = static::find($id);
if (!$model instanceof Model) {
throw new NotFoundException("Record with identifier '$id' not found.");
}
try {
if ($model->is_sys_admin && !array_get_bool($params, 'admin')) {
throw new ForbiddenException('Not allowed to delete an admin user.');
} elseif (array_get_bool($params, 'admin') && !$model->is_sys_admin) {
throw new BadRequestException('Cannot delete a non-admin user.');
} elseif (Session::getCurrentUserId() === $model->id) {
throw new ForbiddenException('Cannot delete your account.');
}
$result = static::buildResult($model, $params);
if ('sqlsrv' === $model->getConnection()->getDriverName()) {
// cleanup references not happening automatically due to schema setup
$references = $model->getReferences();
/** @type RelationSchema $reference */
foreach ($references as $reference) {
if ((RelationSchema::HAS_ONE === $reference->type) &&
(('created_by_id' === $reference->refField[0]) ||
('last_modified_by_id' === $reference->refField[0]))
) {
$stmt =
'update [' .
$reference->refTable .
'] set [' .
$reference->refField[0] .
'] = null where [' .
$reference->refField[0] .
'] = ' .
$id;
if (0 !== $rows = \DB::update($stmt)) {
\Log::debug('found rows: ' . $rows);
}
} elseif ((RelationSchema::HAS_MANY === $reference->type) &&
(('created_by_id' === $reference->refField[0]) ||
('last_modified_by_id' === $reference->refField[0]))
) {
$stmt =
'update [' .
$reference->refTable .
'] set [' .
$reference->refField[0] .
'] = null where [' .
$reference->refField[0] .
'] = ' .
$id;
if (0 !== $rows = \DB::update($stmt)) {
\Log::debug('found rows: ' . $rows);
}
} elseif ((RelationSchema::BELONGS_TO === $reference->type) &&
(('created_by_id' === $reference->field[0]) ||
('last_modified_by_id' === $reference->field[0]))
) {
$stmt =
'update [' .
$reference->refTable .
'] set [' .
$reference->field[0] .
'] = null where [' .
$reference->field[0] .
'] = ' .
$id . ' and [' . $reference->refField[0] . '] != ' . $id;
if (0 !== $rows = \DB::update($stmt)) {
\Log::debug('found rows: ' . $rows);
}
}
}
}
$model->delete();
return $result;
} catch (\Exception $ex) {
if (!$ex instanceof ForbiddenException && !$ex instanceof BadRequestException) {
throw new InternalServerErrorException('Failed to delete resource: ' . $ex->getMessage());
} else {
throw $ex;
}
}
}
/**
* Encrypts security answer.
*
* @param string $value
*/
public function setSecurityAnswerAttribute($value)
{
$this->attributes['security_answer'] = Hash::make($value);
}
/**
* Encrypts password.
*
* @param $password
*/
public function setPasswordAttribute($password)
{
if (!empty($password)) {
$password = Hash::make($password);
JWTUtilities::invalidateTokenByUserId($this->id);
// When password is set user account must be confirmed. Confirming user
// account here with confirm_code = null.
// confirm_code = 'y' indicates cases where account is confirmed by user
// using confirmation email.
if (isset($this->attributes['confirm_code']) && $this->attributes['confirm_code'] !== 'y') {
$this->attributes['confirm_code'] = null;
}
}
$this->attributes['password'] = $password;
}
/**
* Updates password hash directly.
* This is used by package import in order to preserve
* user password during import.
*
* @param $hash
*/
public function updatePasswordHash($hash)
{
$this->attributes['password'] = $hash;
$this->save();
}
public static function boot()
{
parent::boot();
static::creating(
function (User $user){
event(new UserCreatingEvent($user));
}
);
static::saved(
function (User $user){
if (!$user->is_active) {
JWTUtilities::invalidateTokenByUserId($user->id);
}
\Cache::forget('user:' . $user->id);
}
);
static::deleted(
function (User $user){
JWTUtilities::invalidateTokenByUserId($user->id);
\Cache::forget('user:' . $user->id);
event(new UserDeletedEvent($user));
}
);
}
/**
* Returns user info cached, or reads from db if not present.
* Pass in a key to return a portion/index of the cached data.
*
* @param int $id
* @param null|string $key
* @param null $default
*
* @return mixed|null
*/
public static function getCachedInfo($id, $key = null, $default = null)
{
$cacheKey = 'user:' . $id;
$result = \Cache::remember($cacheKey, \Config::get('df.default_cache_ttl'), function () use ($id){
$user = static::whereId($id)->first();
if (empty($user)) {
throw new NotFoundException("User not found.");
}
if (!$user->is_active) {
throw new ForbiddenException("User is not active.");
}
$userInfo = $user->toArray();
$userInfo['is_sys_admin'] = $user->is_sys_admin;
return $userInfo;
});
if (is_null($result)) {
return $default;
}
if (is_null($key)) {
return $result;
}
return (isset($result[$key]) ? $result[$key] : $default);
}
/**
* @return boolean
*/
public static function adminExists()
{
return \Cache::rememberForever('admin_exists', function (){
return static::whereIsActive(1)->whereIsSysAdmin(1)->exists();
});
}
public static function resetAdminExists()
{
return \Cache::forget('admin_exists');
}
/**
* Creates first admin user.
*
* @param array $data
*
* @return User|boolean
*/
public static function createFirstAdmin(array &$data)
{
if (empty($data['username'])) {
$data['username'] = $data['email'];
}
$validationRules = [
'name' => 'required|max:255',
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
'email' => 'required|email|max:255|unique:user',
'password' => 'required|confirmed|min:6',
'username' => 'min:6|unique:user,username|regex:/^\S*$/u|required',
'phone' => 'required|max:32',
];
$validator = Validator::make($data, $validationRules);
if ($validator->fails()) {
$errors = $validator->getMessageBag()->all();
$data = array_merge($data, ['errors' => $errors, 'version' => \Config::get('app.version')]);
return false;
} else {
/** @type User $user */
$attributes = array_only($data, ['name', 'first_name', 'last_name', 'email', 'username', 'phone']);
$attributes['is_active'] = 1;
$user = static::create($attributes);
$user->password = array_get($data, 'password');
$user->is_sys_admin = 1;
$user->save();
InstanceId::getInstanceIdOrGenerate();
// Register user
RegisterContact::registerUser($user);
// Reset admin_exists flag in cache.
\Cache::forever('admin_exists', true);
return $user;
}
}
public function save(array $options = [])
{
if ($this->exists) {
// Check uniqueness of username excluding this user that is being updated.
$usernameRules = explode('|', $this->rules['username']);
$usernameRules[1] .= ',' . $this->id;
$this->rules['username'] = implode('|', $usernameRules);
}
$loginAttribute = strtolower(config('df.login_attribute', 'email'));
$username = array_get($this->attributes, 'username');
if ($loginAttribute !== 'username' && empty($username)) {
$this->attributes['username'] = $this->attributes['email'];
}
return parent::save($options);
}
protected static function getModelFromTable($table)
{
if ('lookup' === $table) {
return UserLookup::class;
}
return parent::getModelFromTable($table);
}
}
| {
"content_hash": "8921101e1262c59a612f46fbcbee762c",
"timestamp": "",
"source": "github",
"line_count": 676,
"max_line_length": 111,
"avg_line_length": 32.41568047337278,
"alnum_prop": 0.5090585497193447,
"repo_name": "dreamfactorysoftware/df-core",
"id": "701706b82f1b04b1e464a9260b44029d16be0fce",
"size": "21913",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Models/User.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "1012751"
}
],
"symlink_target": ""
} |
using System;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using CountingApp.Core.Config;
namespace CountingApp.IdentityServer
{
public class Program
{
public static void Main(string[] args)
{
Console.Title = "CountingApp.IdentityServer";
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseUrls(Uris.IdentityServerUri)
.Build();
}
}
| {
"content_hash": "8307f6bcd26ff0050506f1fc8f7ce800",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 61,
"avg_line_length": 25.08695652173913,
"alnum_prop": 0.6117850953206239,
"repo_name": "DMokhnatkin/CountingApp",
"id": "913d69596cdafb544d89177904fceef99bb0a6b2",
"size": "579",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "CountingApp/CountingApp.IdentityServer/Program.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "295285"
}
],
"symlink_target": ""
} |
#pragma once
#include <aws/securityhub/SecurityHub_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/securityhub/model/IpOrganizationDetails.h>
#include <aws/securityhub/model/Country.h>
#include <aws/securityhub/model/City.h>
#include <aws/securityhub/model/GeoLocation.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace SecurityHub
{
namespace Model
{
/**
* <p>For <code>AwsApiAction</code>, <code>NetworkConnectionAction</code>, and
* <code>PortProbeAction</code>, <code>RemoteIpDetails</code> provides information
* about the remote IP address that was involved in the action.</p><p><h3>See
* Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/securityhub-2018-10-26/ActionRemoteIpDetails">AWS
* API Reference</a></p>
*/
class AWS_SECURITYHUB_API ActionRemoteIpDetails
{
public:
ActionRemoteIpDetails();
ActionRemoteIpDetails(Aws::Utils::Json::JsonView jsonValue);
ActionRemoteIpDetails& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The IP address.</p>
*/
inline const Aws::String& GetIpAddressV4() const{ return m_ipAddressV4; }
/**
* <p>The IP address.</p>
*/
inline bool IpAddressV4HasBeenSet() const { return m_ipAddressV4HasBeenSet; }
/**
* <p>The IP address.</p>
*/
inline void SetIpAddressV4(const Aws::String& value) { m_ipAddressV4HasBeenSet = true; m_ipAddressV4 = value; }
/**
* <p>The IP address.</p>
*/
inline void SetIpAddressV4(Aws::String&& value) { m_ipAddressV4HasBeenSet = true; m_ipAddressV4 = std::move(value); }
/**
* <p>The IP address.</p>
*/
inline void SetIpAddressV4(const char* value) { m_ipAddressV4HasBeenSet = true; m_ipAddressV4.assign(value); }
/**
* <p>The IP address.</p>
*/
inline ActionRemoteIpDetails& WithIpAddressV4(const Aws::String& value) { SetIpAddressV4(value); return *this;}
/**
* <p>The IP address.</p>
*/
inline ActionRemoteIpDetails& WithIpAddressV4(Aws::String&& value) { SetIpAddressV4(std::move(value)); return *this;}
/**
* <p>The IP address.</p>
*/
inline ActionRemoteIpDetails& WithIpAddressV4(const char* value) { SetIpAddressV4(value); return *this;}
/**
* <p>The internet service provider (ISP) organization associated with the remote
* IP address.</p>
*/
inline const IpOrganizationDetails& GetOrganization() const{ return m_organization; }
/**
* <p>The internet service provider (ISP) organization associated with the remote
* IP address.</p>
*/
inline bool OrganizationHasBeenSet() const { return m_organizationHasBeenSet; }
/**
* <p>The internet service provider (ISP) organization associated with the remote
* IP address.</p>
*/
inline void SetOrganization(const IpOrganizationDetails& value) { m_organizationHasBeenSet = true; m_organization = value; }
/**
* <p>The internet service provider (ISP) organization associated with the remote
* IP address.</p>
*/
inline void SetOrganization(IpOrganizationDetails&& value) { m_organizationHasBeenSet = true; m_organization = std::move(value); }
/**
* <p>The internet service provider (ISP) organization associated with the remote
* IP address.</p>
*/
inline ActionRemoteIpDetails& WithOrganization(const IpOrganizationDetails& value) { SetOrganization(value); return *this;}
/**
* <p>The internet service provider (ISP) organization associated with the remote
* IP address.</p>
*/
inline ActionRemoteIpDetails& WithOrganization(IpOrganizationDetails&& value) { SetOrganization(std::move(value)); return *this;}
/**
* <p>The country where the remote IP address is located.</p>
*/
inline const Country& GetCountry() const{ return m_country; }
/**
* <p>The country where the remote IP address is located.</p>
*/
inline bool CountryHasBeenSet() const { return m_countryHasBeenSet; }
/**
* <p>The country where the remote IP address is located.</p>
*/
inline void SetCountry(const Country& value) { m_countryHasBeenSet = true; m_country = value; }
/**
* <p>The country where the remote IP address is located.</p>
*/
inline void SetCountry(Country&& value) { m_countryHasBeenSet = true; m_country = std::move(value); }
/**
* <p>The country where the remote IP address is located.</p>
*/
inline ActionRemoteIpDetails& WithCountry(const Country& value) { SetCountry(value); return *this;}
/**
* <p>The country where the remote IP address is located.</p>
*/
inline ActionRemoteIpDetails& WithCountry(Country&& value) { SetCountry(std::move(value)); return *this;}
/**
* <p>The city where the remote IP address is located.</p>
*/
inline const City& GetCity() const{ return m_city; }
/**
* <p>The city where the remote IP address is located.</p>
*/
inline bool CityHasBeenSet() const { return m_cityHasBeenSet; }
/**
* <p>The city where the remote IP address is located.</p>
*/
inline void SetCity(const City& value) { m_cityHasBeenSet = true; m_city = value; }
/**
* <p>The city where the remote IP address is located.</p>
*/
inline void SetCity(City&& value) { m_cityHasBeenSet = true; m_city = std::move(value); }
/**
* <p>The city where the remote IP address is located.</p>
*/
inline ActionRemoteIpDetails& WithCity(const City& value) { SetCity(value); return *this;}
/**
* <p>The city where the remote IP address is located.</p>
*/
inline ActionRemoteIpDetails& WithCity(City&& value) { SetCity(std::move(value)); return *this;}
/**
* <p>The coordinates of the location of the remote IP address.</p>
*/
inline const GeoLocation& GetGeoLocation() const{ return m_geoLocation; }
/**
* <p>The coordinates of the location of the remote IP address.</p>
*/
inline bool GeoLocationHasBeenSet() const { return m_geoLocationHasBeenSet; }
/**
* <p>The coordinates of the location of the remote IP address.</p>
*/
inline void SetGeoLocation(const GeoLocation& value) { m_geoLocationHasBeenSet = true; m_geoLocation = value; }
/**
* <p>The coordinates of the location of the remote IP address.</p>
*/
inline void SetGeoLocation(GeoLocation&& value) { m_geoLocationHasBeenSet = true; m_geoLocation = std::move(value); }
/**
* <p>The coordinates of the location of the remote IP address.</p>
*/
inline ActionRemoteIpDetails& WithGeoLocation(const GeoLocation& value) { SetGeoLocation(value); return *this;}
/**
* <p>The coordinates of the location of the remote IP address.</p>
*/
inline ActionRemoteIpDetails& WithGeoLocation(GeoLocation&& value) { SetGeoLocation(std::move(value)); return *this;}
private:
Aws::String m_ipAddressV4;
bool m_ipAddressV4HasBeenSet;
IpOrganizationDetails m_organization;
bool m_organizationHasBeenSet;
Country m_country;
bool m_countryHasBeenSet;
City m_city;
bool m_cityHasBeenSet;
GeoLocation m_geoLocation;
bool m_geoLocationHasBeenSet;
};
} // namespace Model
} // namespace SecurityHub
} // namespace Aws
| {
"content_hash": "f8b25cdf038cf7ca5c4a3a10e12856d5",
"timestamp": "",
"source": "github",
"line_count": 234,
"max_line_length": 134,
"avg_line_length": 31.982905982905983,
"alnum_prop": 0.6628808123997862,
"repo_name": "awslabs/aws-sdk-cpp",
"id": "e91292529dfa82ea44cc3e72546f6deaff0f1cae",
"size": "7603",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "aws-cpp-sdk-securityhub/include/aws/securityhub/model/ActionRemoteIpDetails.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "7596"
},
{
"name": "C++",
"bytes": "61740540"
},
{
"name": "CMake",
"bytes": "337520"
},
{
"name": "Java",
"bytes": "223122"
},
{
"name": "Python",
"bytes": "47357"
}
],
"symlink_target": ""
} |
var mongoose = require('mongoose')
, Schema = mongoose.Schema
, Mixed = Schema.Types.Mixed
, ObjectId = Schema.ObjectId;
var Page = new Schema({
title : String,
slug : String,
template : String,
data : Object
});
Page.pre('save', function (next) {
// Do something.
next();
});
module.exports.PageSchema = Page;
var Post = new Schema({
slug : String,
title : String,
content : String,
author : String,
img : String,
next : Object,
prev : Object,
timestamp : Date
});
Post.pre('save', function (next) {
// Do something.
next();
});
module.exports.PostSchema = Post;
var Author = new Schema({
name : String,
social_media : Array
});
Author.pre('save', function (next) {
// Do something.
next();
});
module.exports.AuthorSchema = Author;
var User = new Schema({
username : String,
password : String,
permissions : Boolean
});
User.pre('save', function (next) {
// Do something.
next();
});
module.exports.UserSchema = User; | {
"content_hash": "98052c3d84a75eaaa6bc4fc7883070be",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 37,
"avg_line_length": 17.983606557377048,
"alnum_prop": 0.5706472196900638,
"repo_name": "derekcaneja/node-cms",
"id": "af4ca79dfb19b36929c502fde67d6370d968b043",
"size": "1097",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/dataAdapter/models/schemas.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "25302"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>CSS Overflow Test: Intrinsic size of a "overflow:auto" vertical scroll container</title>
<link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
<link rel="author" title="Ting-Yu Lin" href="mailto:tlin@mozilla.com">
<link rel="help" href="https://drafts.csswg.org/css-overflow-3/#overflow-properties">
<link rel="match" href="overflow-scroll-intrinsic-001-ref.html">
<style>
.container {
border: 1px solid black;
width: 100px;
display: inline-block;
}
</style>
<div class="container" style="writing-mode: vertical-rl; overflow-x: scroll;"></div>
<div class="container" style="writing-mode: vertical-rl; overflow-y: scroll;"></div>
<div class="container" style="writing-mode: vertical-lr; overflow-x: scroll;"></div>
<div class="container" style="writing-mode: vertical-lr; overflow-y: scroll;"></div>
</html>
| {
"content_hash": "220e86304a9b92229ba8e82ef94d180b",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 97,
"avg_line_length": 40.30434782608695,
"alnum_prop": 0.6936353829557713,
"repo_name": "nwjs/chromium.src",
"id": "093fd283c77b71e7f73914761cc086e10c12a0d6",
"size": "927",
"binary": false,
"copies": "18",
"ref": "refs/heads/nw70",
"path": "third_party/blink/web_tests/external/wpt/css/css-overflow/overflow-scroll-intrinsic-001.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
#ifndef ALIPHOSFASTRECPARTICLE_H
#define ALIPHOSFASTRECPARTICLE_H
/* $Id$ */
/* History of cvs commits:
*
* $Log$
* Revision 1.36 2005/05/28 14:19:04 schutz
* Compilation warnings fixed by T.P.
*
*/
//_________________________________________________________________________
// A Particle modified by PHOS response and produced by AliPHOSvFast
// This is also a base class for AliPHOSRecParticle produced by AliPHOSPIDv1
// Defines the particle type
// To become a general class of AliRoot ?
//--
//*-- Author: Yves Schutz (SUBATECH)
// --- ROOT system ---
class TClonesArray;
#include "TParticle.h"
#include "AliPID.h"
// --- Standard library ---
// --- AliRoot header files ---
class AliPHOSFastRecParticle : public TParticle {
public:
AliPHOSFastRecParticle() ;
AliPHOSFastRecParticle(const AliPHOSFastRecParticle & rp) ; // ctor
AliPHOSFastRecParticle(const TParticle & p) ; // ctor
virtual ~AliPHOSFastRecParticle(){ } //dtor
AliPHOSFastRecParticle & operator = (const AliPHOSFastRecParticle & /*rp*/);
virtual Int_t DistancetoPrimitive(Int_t px, Int_t py) ;
virtual void Draw(Option_t *option) ;
virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py) ;
Int_t GetIndexInList() const {
// returns the index of this in the list
return fIndexInList ;
}
virtual Int_t GetNPrimaries() const {return 0 ;}
virtual const TParticle * GetPrimary(Int_t) const {return 0 ;}
Int_t GetType() const {
// returns the type of the particle
return fType ;
}
void SetPIDBit(UInt_t fSet) {
// Set PID bit number fSet
fType |= (1<<fSet) ;
}
Bool_t TestPIDBit(UInt_t fTest) const {
// Check PID bit number fTest
if (fType & (1<<fTest) ) return kTRUE ;
else return kFALSE ;
}
Bool_t IsPhoton (TString purity = "low") const;
Bool_t IsPi0 (TString purity = "low") const;
Bool_t IsElectron (TString purity = "low") const;
Bool_t IsHardPhoton () const;
Bool_t IsHardPi0 () const;
Bool_t IsHadron () const;
Bool_t IsChargedHadron () const;
Bool_t IsNeutralHadron () const;
Bool_t IsFastChargedHadron() const;
Bool_t IsSlowChargedHadron() const;
Bool_t IsFastNeutralHadron() const;
Bool_t IsSlowNeutralHadron() const;
Bool_t IsEleCon(TString purity = "low") const;
TString Name() const ;
virtual void Paint(Option_t * option="");
virtual void Print(const Option_t * = "") const ;
void SetTof(Float_t tof) { fTof = tof ; }
Float_t ToF() const { return fTof ; }
void SetType(Int_t type) ;
void SetIndexInList(Int_t val) {
// sets the value of the index in the list
fIndexInList = val ;
}
//This has to disappear
enum EParticleType { kTYPE = 8,
kUNDEFINED=-1,
kNEUTRALEMFAST, kNEUTRALHAFAST, kNEUTRALEMSLOW, kNEUTRALHASLOW,
kCHARGEDEMFAST, kCHARGEDHAFAST, kCHARGEDEMSLOW, kCHARGEDHASLOW } ;
typedef TClonesArray FastRecParticlesList ;
protected:
Int_t fIndexInList ; // the index of this RecParticle in the list stored in TreeR (to be set by analysis)
Float_t fTof ; // time of fliht
Int_t fType ; // particle type obtained by "virtual" reconstruction
Float_t fPID[AliPID::kSPECIESCN] ; // PID probability densities
private:
ClassDef(AliPHOSFastRecParticle,2) // Reconstructed Particle produced by the fast simulation
};
#endif // AliPHOSFASTRECPARTICLE_H
| {
"content_hash": "22921b04610dceb2df6773489fd8cd26",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 107,
"avg_line_length": 30.443478260869565,
"alnum_prop": 0.6443873179091688,
"repo_name": "jgrosseo/AliRoot",
"id": "d9a55e165f449f4573e0d36af61cdb0b743e5514",
"size": "3653",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "PHOS/PHOSbase/AliPHOSFastRecParticle.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "3864"
},
{
"name": "C",
"bytes": "14273296"
},
{
"name": "C++",
"bytes": "91789387"
},
{
"name": "CMake",
"bytes": "1170233"
},
{
"name": "CSS",
"bytes": "9136"
},
{
"name": "Cuda",
"bytes": "51347"
},
{
"name": "Fortran",
"bytes": "33197149"
},
{
"name": "HTML",
"bytes": "9500549"
},
{
"name": "M4",
"bytes": "77872"
},
{
"name": "Makefile",
"bytes": "824266"
},
{
"name": "Objective-C",
"bytes": "288081"
},
{
"name": "PHP",
"bytes": "10833197"
},
{
"name": "Pascal",
"bytes": "2295"
},
{
"name": "Perl",
"bytes": "12019"
},
{
"name": "PostScript",
"bytes": "1946897"
},
{
"name": "Python",
"bytes": "57204"
},
{
"name": "Shell",
"bytes": "290626"
},
{
"name": "SourcePawn",
"bytes": "7668"
},
{
"name": "TeX",
"bytes": "936449"
}
],
"symlink_target": ""
} |
require 'open-uri'
require 'archive/tar/minitar'
require 'tempfile'
require 'fog/octocloud/requests/compute/convert_cube'
module Fog
module Compute
class Octocloud
class Real
def local_import_box(boxname, src, md5, opts = {})
target = @box_dir.join(boxname)
target.mkdir unless target.exist?
begin
import_file(target, src, opts)
rescue Exception => e
target.rmtree
raise e
end
File.open(target.join('.md5'), 'w') {|f| f.write(md5) }
end
end
end
end
end
| {
"content_hash": "79a88b431c67b14734bda73099f8d4a3",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 65,
"avg_line_length": 19.866666666666667,
"alnum_prop": 0.5704697986577181,
"repo_name": "lstoll/fog-octocloud",
"id": "00108e8a75d3aba112a836420c92e8c02665648c",
"size": "596",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/fog/octocloud/requests/compute/local_import_box.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "66165"
},
{
"name": "Shell",
"bytes": "88"
}
],
"symlink_target": ""
} |
var f = require('./Foo');
var j = require('jquery');
f();
| {
"content_hash": "758490fe325b7b23fddf3d38c8b24bcb",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 26,
"avg_line_length": 19.333333333333332,
"alnum_prop": 0.5517241379310345,
"repo_name": "koala-framework/koala-framework",
"id": "7b183ec07ff468d40db1af4481d3e0a7045a4c22",
"size": "58",
"binary": false,
"copies": "2",
"ref": "refs/heads/5.4",
"path": "tests/Kwf/Assets/ModuleDeps/Test.js",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "49755"
},
{
"name": "JavaScript",
"bytes": "1120596"
},
{
"name": "PHP",
"bytes": "7076782"
},
{
"name": "SCSS",
"bytes": "92667"
},
{
"name": "Smarty",
"bytes": "229096"
},
{
"name": "Twig",
"bytes": "33150"
}
],
"symlink_target": ""
} |
<ly-slider [ngClass]="classes.slider" [value]="76"></ly-slider>
<ly-slider [ngClass]="classes.slider" [value]="[11, 50]" [color]="'primary'"></ly-slider>
| {
"content_hash": "d64f7fd54d7e2bba8b64a7feb51ac333",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 89,
"avg_line_length": 77,
"alnum_prop": 0.6493506493506493,
"repo_name": "A-l-y-l-e/Alyle-UI",
"id": "97b1c3a92a663775c9bac0c8bfcd203f7ba32c59",
"size": "154",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/app/docs/components/slider-demo/basic-slider/basic-slider.component.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1958186"
},
{
"name": "JavaScript",
"bytes": "6569"
},
{
"name": "Shell",
"bytes": "4177"
},
{
"name": "TypeScript",
"bytes": "1142002"
}
],
"symlink_target": ""
} |
/**
* jqGrid English Translation
* Tony Tomov tony@trirand.com
* modified by Oleg Kiriljuk oleg.kiriljuk@ok-soft-gmbh.com
* http://trirand.com/blog/
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
**/
/*jslint white: true */
/*global jQuery */
(function ($) {
"use strict";
var locInfo = {
name: "English (United States)",
nameEnglish: "English (United States)",
isRTL: false,
defaults: {
recordtext: "View {0} - {1} of {2}",
emptyrecords: "No records to view",
loadtext: "Loading...",
pgtext: "Page {0} of {1}",
pgfirst: "First Page",
pglast: "Last Page",
pgnext: "Next Page",
pgprev: "Previous Page",
pgrecs: "Records per Page",
showhide: "Toggle Expand Collapse Grid",
savetext: "Saving..."
},
search: {
caption: "Search...",
Find: "Find",
Reset: "Reset",
odata: [
{ oper: "eq", text: "equal" },
{ oper: "ne", text: "not equal" },
{ oper: "lt", text: "less" },
{ oper: "le", text: "less or equal" },
{ oper: "gt", text: "greater" },
{ oper: "ge", text: "greater or equal" },
{ oper: "bw", text: "begins with" },
{ oper: "bn", text: "does not begin with" },
{ oper: "in", text: "is in" },
{ oper: "ni", text: "is not in" },
{ oper: "ew", text: "ends with" },
{ oper: "en", text: "does not end with" },
{ oper: "cn", text: "contains" },
{ oper: "nc", text: "does not contain" },
{ oper: "nu", text: "is null" },
{ oper: "nn", text: "is not null" }
],
groupOps: [
{ op: "AND", text: "all" },
{ op: "OR", text: "any" }
],
operandTitle: "Click to select search operation.",
resetTitle: "Reset Search Value"
},
edit: {
addCaption: "Add Record",
editCaption: "Edit Record",
bSubmit: "Submit",
bCancel: "Cancel",
bClose: "Close",
saveData: "Data has been changed! Save changes?",
bYes: "Yes",
bNo: "No",
bExit: "Cancel",
msg: {
required: "Field is required",
number: "Please, enter valid number",
minValue: "value must be greater than or equal to ",
maxValue: "value must be less than or equal to",
email: "is not a valid e-mail",
integer: "Please, enter valid integer value",
date: "Please, enter valid date value",
url: "is not a valid URL. Prefix required ('http://' or 'https://')",
nodefined: " is not defined!",
novalue: " return value is required!",
customarray: "Custom function should return array!",
customfcheck: "Custom function should be present in case of custom checking!"
}
},
view: {
caption: "View Record",
bClose: "Close"
},
del: {
caption: "Delete",
msg: "Delete selected record(s)?",
bSubmit: "Delete",
bCancel: "Cancel"
},
nav: {
edittext: "",
edittitle: "Edit selected row",
addtext: "",
addtitle: "Add new row",
deltext: "",
deltitle: "Delete selected row",
searchtext: "",
searchtitle: "Find records",
refreshtext: "",
refreshtitle: "Reload Grid",
alertcap: "Warning",
alerttext: "Please, select row",
viewtext: "",
viewtitle: "View selected row"
},
col: {
caption: "Select columns",
bSubmit: "Ok",
bCancel: "Cancel"
},
errors: {
errcap: "Error",
nourl: "No url is set",
norecords: "No records to process",
model: "Length of colNames <> colModel!"
},
formatter: {
integer: {
thousandsSeparator: ",",
defaultValue: "0"
},
number: {
decimalSeparator: ".",
thousandsSeparator: ",",
decimalPlaces: 2,
defaultValue: "0.00"
},
currency: {
decimalSeparator: ".",
thousandsSeparator: ",",
decimalPlaces: 2,
prefix: "",
suffix: "",
defaultValue: "0.00"
},
date: {
dayNames: [
"Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat",
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
],
monthNames: [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
],
AmPm: ["am", "pm", "AM", "PM"],
S: function (j) {
var ending = ["st", "nd", "rd", "th"];
return j < 11 || j > 13 ? ending[Math.min((j - 1) % 10, 3)] : "th";
},
srcformat: "Y-m-d",
newformat: "n/j/Y",
masks: {
// see http://php.net/manual/en/function.date.php for PHP format used in jqGrid
// and see http://docs.jquery.com/UI/Datepicker/formatDate
// and https://github.com/jquery/globalize#dates for alternative formats used frequently
// one can find on https://github.com/jquery/globalize/tree/master/lib/cultures many
// information about date, time, numbers and currency formats used in different countries
// one should just convert the information in PHP format
// short date:
// n - Numeric representation of a month, without leading zeros
// j - Day of the month without leading zeros
// Y - A full numeric representation of a year, 4 digits
// example: 3/1/2012 which means 1 March 2012
ShortDate: "n/j/Y", // in jQuery UI Datepicker: "M/d/yyyy"
// long date:
// l - A full textual representation of the day of the week
// F - A full textual representation of a month
// d - Day of the month, 2 digits with leading zeros
// Y - A full numeric representation of a year, 4 digits
LongDate: "l, F d, Y", // in jQuery UI Datepicker: "dddd, MMMM dd, yyyy"
// long date with long time:
// l - A full textual representation of the day of the week
// F - A full textual representation of a month
// d - Day of the month, 2 digits with leading zeros
// Y - A full numeric representation of a year, 4 digits
// g - 12-hour format of an hour without leading zeros
// i - Minutes with leading zeros
// s - Seconds, with leading zeros
// A - Uppercase Ante meridiem and Post meridiem (AM or PM)
FullDateTime: "l, F d, Y g:i:s A", // in jQuery UI Datepicker: "dddd, MMMM dd, yyyy h:mm:ss tt"
// month day:
// F - A full textual representation of a month
// d - Day of the month, 2 digits with leading zeros
MonthDay: "F d", // in jQuery UI Datepicker: "MMMM dd"
// short time (without seconds)
// g - 12-hour format of an hour without leading zeros
// i - Minutes with leading zeros
// A - Uppercase Ante meridiem and Post meridiem (AM or PM)
ShortTime: "g:i A", // in jQuery UI Datepicker: "h:mm tt"
// long time (with seconds)
// g - 12-hour format of an hour without leading zeros
// i - Minutes with leading zeros
// s - Seconds, with leading zeros
// A - Uppercase Ante meridiem and Post meridiem (AM or PM)
LongTime: "g:i:s A", // in jQuery UI Datepicker: "h:mm:ss tt"
// month with year
// Y - A full numeric representation of a year, 4 digits
// F - A full textual representation of a month
YearMonth: "F, Y" // in jQuery UI Datepicker: "MMMM, yyyy"
}
}
}
};
$.jgrid = $.jgrid || {};
$.extend(true, $.jgrid, {
defaults: {
locale: "en-US"
},
locales: {
// In general the property name is free, but it's recommended to use the names based on
// http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
// http://rishida.net/utils/subtags/ and RFC 5646. See Appendix A of RFC 5646 for examples.
// One can use the lang attribute to specify language tags in HTML, and the xml:lang attribute for XML
// if it exists. See http://www.w3.org/International/articles/language-tags/#extlang
"en-US": locInfo
}
});
}(jQuery)); | {
"content_hash": "8e21aedc5e4394f764c92b4e58f33890",
"timestamp": "",
"source": "github",
"line_count": 224,
"max_line_length": 140,
"avg_line_length": 44.825892857142854,
"alnum_prop": 0.4641967931480928,
"repo_name": "PayPal-Opportunity-Hack-Chennai-2015/PCVC-Organization",
"id": "7eb7c81d2ccc0946a7a8effddf811b91f5a54580",
"size": "10041",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "view/js/grid.locale-en.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "170290"
},
{
"name": "HTML",
"bytes": "7519"
},
{
"name": "Java",
"bytes": "26257"
},
{
"name": "JavaScript",
"bytes": "978652"
},
{
"name": "PHP",
"bytes": "114097"
}
],
"symlink_target": ""
} |
package com.xeiam.xchange.dto.trade;
import java.math.BigDecimal;
/**
* <p>
* DTO representing a Wallet
* </p>
* <p>
* This is simply defined by an amount of money in a given currency, contained in the cash object.
* </p>
* <p>
* This class is immutable.
* </p>
*/
public final class Wallet {
private final String currency;
private final String description;
private final BigDecimal balance;
/**
* Constructor
*
* @param currency The underlying currency
* @param balance The balance
*/
public Wallet(String currency, BigDecimal balance) {
this.currency = currency;
this.balance = balance;
this.description = "";
}
/**
* Additional constructor with optional description
*
* @param description Optional description to distinguish same currency Wallets
*/
public Wallet(String currency, BigDecimal balance, String description) {
this.currency = currency;
this.balance = balance;
this.description = description;
}
public String getCurrency() {
return currency;
}
public BigDecimal getBalance() {
return balance;
}
public String getDescription() {
return description;
}
@Override
public String toString() {
return "Wallet [currency=" + currency + ", balance=" + balance + ", description=" + description + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((balance == null) ? 0 : balance.hashCode());
result = prime * result + ((currency == null) ? 0 : currency.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Wallet other = (Wallet) obj;
if (balance == null) {
if (other.balance != null) {
return false;
}
}
else if (!balance.equals(other.balance)) {
return false;
}
if (currency == null) {
if (other.currency != null) {
return false;
}
}
else if (!currency.equals(other.currency)) {
return false;
}
if (description == null) {
if (other.description != null) {
return false;
}
}
else if (!description.equals(other.description)) {
return false;
}
return true;
}
}
| {
"content_hash": "d9eee8e86fac681062d63724e12954f1",
"timestamp": "",
"source": "github",
"line_count": 119,
"max_line_length": 106,
"avg_line_length": 20.915966386554622,
"alnum_prop": 0.6050622740056247,
"repo_name": "Achterhoeker/XChange",
"id": "e03d8595def7797836c65e050cdef2687996d607",
"size": "2489",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "xchange-core/src/main/java/com/xeiam/xchange/dto/trade/Wallet.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "2830566"
}
],
"symlink_target": ""
} |
@implementation TelDataBase
+(TelDataBase*)shareTelDataBase
{
static TelDataBase* telDatabase = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
telDatabase = [[TelDataBase alloc]init];
});
return telDatabase;
}
- (FMDatabase *)db{
if (!_db) {
_db = [FMDatabase databaseWithPath:[self getPathOfFmdb]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:[self getPathOfFmdb]]) {
NSLog(@"还未创建数据库,现在正在创建数据库");
if ([_db open]) {
// NSString *creatIpListStr = [NSString stringWithFormat:@"CREATE TABLE %@ (host text, port text, wifiName text ,wifiPass text ,userName text ,password text ,Service1Enable integer , Service1VlanId integer , Service1VlanPri integer , Service1Mode integer , Service1Portmap text)", IPLISTNAME];
NSString *creatIpListStr = [NSString stringWithFormat:@"CREATE TABLE %@ (host text, port text, wifiName text ,wifiPass text )", IPLISTNAME];
[_db executeUpdate:creatIpListStr];
BOOL res = [_db executeUpdate:creatIpListStr];
if (!res) {
NSLog(@"error when insert db table");
} else {
NSLog(@"success to insert db table");
}
}else{
NSLog(@"database open error");
}
}
}
return _db;
}
//是否保存当前wifi
- (BOOL)isSaveWifiName:(NSString *)wifiName{
NSMutableArray *ipArr = [[TelDataBase shareTelDataBase]queryIpListData];
NSMutableArray *idArr = [[NSMutableArray alloc]initWithCapacity:0];
if ([ipArr count] > 0) {
for (int i = 0; i< [ipArr count]; i ++) {
ipModel* ip = [ipArr objectAtIndex:i];
NSString *wifiStr = ip.wifiName;
[idArr addObject:wifiStr];
}
if ([idArr containsObject:wifiName]) {
return YES;
}else{
return NO;
}
}else{
return NO;
}
}
//查询ip数据
- (NSMutableArray *)queryIpListData
{
NSMutableArray *array = [[NSMutableArray alloc]initWithCapacity:0];
[self.db open];
NSString *querySql =[NSString stringWithFormat:@"select * from '%@' ",IPLISTNAME];
FMResultSet *resultSet = [self.db executeQuery:querySql];
// 2.遍历结果
while ([resultSet next]) {
NSString *host = [resultSet stringForColumn:@"host"];
NSString *port = [resultSet stringForColumn:@"port"];
NSString* wifiName = [resultSet stringForColumn:@"wifiName"];
NSString* wifiPass = [resultSet stringForColumn:@"wifiPass"];
// NSString* userName = [resultSet stringForColumn:@"userName"];
// NSString* password = [resultSet stringForColumn:@"password"];
// NSString* Service1Enable = [resultSet stringForColumn:@"Service1Enable"];
// NSString* Service1VlanId = [resultSet stringForColumn:@"Service1VlanId"];
// NSString* Service1Mode = [resultSet stringForColumn:@"Service1Mode"];
// NSString* Service1Portmap = [resultSet stringForColumn:@"Service1Portmap"];
ipModel* ip = [[ipModel alloc]init];
ip.host = host;
ip.port = port;
ip.wifiName = wifiName;
ip.wifiPass = wifiPass;
[array addObject:ip];
}
[self.db close];
return array;
}
//插入ip数据
- (BOOL)savehort:(NSString *)hort port:(NSString *)port wifiName:(NSString *)wifiName wifiPass:(NSString*)wifiPass{
if ([self.db open]) {
NSString *insertSql= [NSString stringWithFormat:
@"INSERT INTO '%@' (host, port, wifiName, wifiPass) VALUES ('%@', '%@', '%@', '%@')",
IPLISTNAME, hort, port, wifiName, wifiPass];
BOOL res = [self.db executeUpdate:insertSql];
if (!res) {
NSLog(@"error when insert db table");
} else {
NSLog(@"success to insert db table");
}
[self.db close];
return res;
}
return NO;
}
//删除数据
- (BOOL)deleteDataWithWifiName:(NSString*)wifiName
{
[self.db open];
NSString *deleteSql=[NSString stringWithFormat:@"delete from %@ where wifiName = '%@' ",IPLISTNAME,wifiName];
BOOL result = [self.db executeUpdate:deleteSql];
if(result){
NSLog(@"删除数据成功");
}else{
NSLog(@"删除数据失败");
}
[self.db close];
return result;
}
-(NSString*)getPathOfFmdb{
//获取路径数组
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documents = [paths objectAtIndex:0];
//进行路径的拼接
NSLog(@"%@",paths[0]);
return [documents stringByAppendingPathComponent:@"ipdataList.db"];
}
@end
| {
"content_hash": "1a609d121fc15663e1e4c640f3ea7320",
"timestamp": "",
"source": "github",
"line_count": 147,
"max_line_length": 308,
"avg_line_length": 33.04761904761905,
"alnum_prop": 0.5891313297653356,
"repo_name": "jiangyicheng/telnetiOSApp",
"id": "bee9b1034bc904b7b1d01164c99b2ac4d551ed5a",
"size": "5205",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "telnetIosApp/telnetIosApp/GCD/TelDataBase.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "114160"
},
{
"name": "Objective-C",
"bytes": "806628"
},
{
"name": "Ruby",
"bytes": "158"
}
],
"symlink_target": ""
} |
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Tickformatstop(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "indicator.gauge.axis"
_path_str = "indicator.gauge.axis.tickformatstop"
_valid_props = {"dtickrange", "enabled", "name", "templateitemname", "value"}
# dtickrange
# ----------
@property
def dtickrange(self):
"""
range [*min*, *max*], where "min", "max" - dtick values which
describe some zoom level, it is possible to omit "min" or "max"
value by passing "null"
The 'dtickrange' property is an info array that may be specified as:
* a list or tuple of 2 elements where:
(0) The 'dtickrange[0]' property accepts values of any type
(1) The 'dtickrange[1]' property accepts values of any type
Returns
-------
list
"""
return self["dtickrange"]
@dtickrange.setter
def dtickrange(self, val):
self["dtickrange"] = val
# enabled
# -------
@property
def enabled(self):
"""
Determines whether or not this stop is used. If `false`, this
stop is ignored even within its `dtickrange`.
The 'enabled' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["enabled"]
@enabled.setter
def enabled(self, val):
self["enabled"] = val
# name
# ----
@property
def name(self):
"""
When used in a template, named items are created in the output
figure in addition to any items the figure already has in this
array. You can modify these items in the output figure by
making your own item with `templateitemname` matching this
`name` alongside your modifications (including `visible: false`
or `enabled: false` to hide it). Has no effect outside of a
template.
The 'name' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["name"]
@name.setter
def name(self, val):
self["name"] = val
# templateitemname
# ----------------
@property
def templateitemname(self):
"""
Used to refer to a named item in this array in the template.
Named items from the template will be created even without a
matching item in the input figure, but you can modify one by
making an item with `templateitemname` matching its `name`,
alongside your modifications (including `visible: false` or
`enabled: false` to hide it). If there is no template or no
matching item, this item will be hidden unless you explicitly
show it with `visible: true`.
The 'templateitemname' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["templateitemname"]
@templateitemname.setter
def templateitemname(self, val):
self["templateitemname"] = val
# value
# -----
@property
def value(self):
"""
string - dtickformat for described zoom level, the same as
"tickformat"
The 'value' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["value"]
@value.setter
def value(self, val):
self["value"] = val
# Self properties description
# ---------------------------
@property
def _prop_descriptions(self):
return """\
dtickrange
range [*min*, *max*], where "min", "max" - dtick values
which describe some zoom level, it is possible to omit
"min" or "max" value by passing "null"
enabled
Determines whether or not this stop is used. If
`false`, this stop is ignored even within its
`dtickrange`.
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
value
string - dtickformat for described zoom level, the same
as "tickformat"
"""
def __init__(
self,
arg=None,
dtickrange=None,
enabled=None,
name=None,
templateitemname=None,
value=None,
**kwargs
):
"""
Construct a new Tickformatstop object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.indicator.gaug
e.axis.Tickformatstop`
dtickrange
range [*min*, *max*], where "min", "max" - dtick values
which describe some zoom level, it is possible to omit
"min" or "max" value by passing "null"
enabled
Determines whether or not this stop is used. If
`false`, this stop is ignored even within its
`dtickrange`.
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
value
string - dtickformat for described zoom level, the same
as "tickformat"
Returns
-------
Tickformatstop
"""
super(Tickformatstop, self).__init__("tickformatstops")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.indicator.gauge.axis.Tickformatstop
constructor must be a dict or
an instance of :class:`plotly.graph_objs.indicator.gauge.axis.Tickformatstop`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("dtickrange", None)
_v = dtickrange if dtickrange is not None else _v
if _v is not None:
self["dtickrange"] = _v
_v = arg.pop("enabled", None)
_v = enabled if enabled is not None else _v
if _v is not None:
self["enabled"] = _v
_v = arg.pop("name", None)
_v = name if name is not None else _v
if _v is not None:
self["name"] = _v
_v = arg.pop("templateitemname", None)
_v = templateitemname if templateitemname is not None else _v
if _v is not None:
self["templateitemname"] = _v
_v = arg.pop("value", None)
_v = value if value is not None else _v
if _v is not None:
self["value"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
| {
"content_hash": "35f2d68f9a639bf2f0f37e6cb583f00d",
"timestamp": "",
"source": "github",
"line_count": 283,
"max_line_length": 82,
"avg_line_length": 33.745583038869256,
"alnum_prop": 0.5631413612565445,
"repo_name": "plotly/python-api",
"id": "c1229fce583d3e09171760092e83644dab96ac5a",
"size": "9550",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/python/plotly/plotly/graph_objs/indicator/gauge/axis/_tickformatstop.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "6870"
},
{
"name": "Makefile",
"bytes": "1708"
},
{
"name": "Python",
"bytes": "823245"
},
{
"name": "Shell",
"bytes": "3238"
}
],
"symlink_target": ""
} |
<ion-item [ngClass]="{'wallet-disabled': !wallet?.isComplete() || wallet?.needsBackup || notSupported}">
<coin-icon [ngClass]="{'easeload': useFadeEffect}" [coin]="wallet.coin" [network]="wallet.network" item-left></coin-icon>
<ion-label>
<div class="main-label">{{ wallet?.name }}</div>
<ion-note *ngIf="notSupported">
<span translate>Not Supported</span>
</ion-note>
<div *ngIf="wallet?.credentials?.n > 1 || (!wallet?.credentials?.n && wallet?.n > 1) || !wallet?.isComplete() || (wallet?.isComplete() && wallet?.needsBackup)" class="secondary-label">
<span *ngIf="wallet?.credentials?.n > 1">({{ wallet?.credentials?.m }}/{{ wallet?.credentials?.n }})</span>
<span *ngIf="!wallet?.credentials?.n && wallet?.n > 1">({{ wallet?.m }}/{{ wallet?.n }})</span>
<span *ngIf="!wallet?.isComplete()"> - <span class="wallet-warning">{{ 'Incomplete' | translate }}</span></span>
<span *ngIf="wallet?.isComplete() && wallet?.needsBackup" class="wallet-warning backup-msg"> {{'Needs Backup' | translate}}</span>
</div>
</ion-label>
<ion-note item-end *ngIf="!notSupported">
<div>
<div *ngIf="!wallet?.balanceHidden">
<div class="main-note">{{ getBalance(wallet, wallet?.coin.toUpperCase()) }}</div>
<div class="secondary-note" *ngIf="wallet?.cachedStatus && !currencyProvider.isCustomERCToken(wallet?.coin) && wallet?.network !== 'testnet'">
{{ getAlternativeBalance(wallet, wallet?.coin.toUpperCase()) }}
{{ wallet?.cachedStatus.alternativeIsoCode }}
</div>
<div class="secondary-note" *ngIf="wallet?.network == 'testnet' && getBalance(wallet, wallet?.coin.toUpperCase())">
{{ 'Test Only - No Value' | translate }}
</div>
</div>
</div>
<div *ngIf="wallet?.balanceHidden">
[<span translate>Hidden</span>]
</div>
</ion-note>
</ion-item>
| {
"content_hash": "928913db86c54cd445754139c10c203e",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 188,
"avg_line_length": 59.0625,
"alnum_prop": 0.6132275132275132,
"repo_name": "cmgustavo/copay",
"id": "a61e0243c453b2ccba200c97bebf0488bd7c7026",
"size": "1890",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/components/wallet-item-content/wallet-item-content.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "516670"
},
{
"name": "Inno Setup",
"bytes": "3214"
},
{
"name": "JavaScript",
"bytes": "39687"
},
{
"name": "SCSS",
"bytes": "275731"
},
{
"name": "Shell",
"bytes": "2822"
},
{
"name": "TypeScript",
"bytes": "2257605"
}
],
"symlink_target": ""
} |
describe('Cache#keys()', function () {
it('should return the array of keys of all items in the cache.', function () {
var itemKeys = ['item1', 'item2', 'item3'];
var cache = TestCacheFactory('DSCache.keys.cache');
cache.put(itemKeys[0], itemKeys[0]);
assert.deepEqual(cache.keys(), [itemKeys[0]]);
cache.put(itemKeys[0], itemKeys[2]);
assert.deepEqual(cache.keys(), [itemKeys[0]]);
assert.deepEqual(cache.get(itemKeys[0]), itemKeys[2]);
cache.put(itemKeys[1], itemKeys[1]);
assert.deepEqual(cache.keys(), [itemKeys[0], itemKeys[1]]);
cache.put(itemKeys[2], itemKeys[2]);
assert.deepEqual(cache.keys(), [itemKeys[0], itemKeys[1], itemKeys[2]]);
var keys = cache.keys();
assert.equal(keys[0], itemKeys[0]);
assert.equal(keys[1], itemKeys[1]);
assert.equal(keys[2], itemKeys[2]);
cache.remove(itemKeys[0]);
cache.remove(itemKeys[1]);
cache.remove(itemKeys[2]);
keys = cache.keys();
assert.equal(keys.length, 0);
assert.deepEqual(keys, []);
});
it('should return the array of keys of all items in the cache when using localStorage.', function () {
var itemKeys = ['item1', 'item2', 'item3'];
var cache = TestCacheFactory('DSCache.keys.cache', {
storageMode: 'localStorage'
});
cache.put(itemKeys[0], itemKeys[0]);
assert.deepEqual(cache.keys(), [itemKeys[0]]);
cache.put(itemKeys[0], itemKeys[2]);
assert.deepEqual(cache.keys(), [itemKeys[0]]);
assert.deepEqual(cache.get(itemKeys[0]), itemKeys[2]);
cache.put(itemKeys[1], itemKeys[1]);
assert.deepEqual(cache.keys(), [itemKeys[0], itemKeys[1]]);
cache.put(itemKeys[2], itemKeys[2]);
assert.deepEqual(cache.keys(), [itemKeys[0], itemKeys[1], itemKeys[2]]);
var keys = cache.keys();
assert.equal(keys[0], itemKeys[0]);
assert.equal(keys[1], itemKeys[1]);
assert.equal(keys[2], itemKeys[2]);
cache.remove(itemKeys[0]);
cache.remove(itemKeys[1]);
cache.remove(itemKeys[2]);
keys = cache.keys();
assert.equal(keys.length, 0);
assert.deepEqual(keys, []);
});
});
| {
"content_hash": "3cac96652851962cae89dc2cbce2694d",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 104,
"avg_line_length": 30.142857142857142,
"alnum_prop": 0.6308056872037915,
"repo_name": "nishant8BITS/angular-cache",
"id": "13dbf1c9be8205340fd24fdbeba8b463d2dcfe37",
"size": "2110",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "test/unit/Cache/index.keys.test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1166"
},
{
"name": "JavaScript",
"bytes": "80880"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct template peaks_over_threshold_prob</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../../accumulators/reference.html#header.boost.accumulators.statistics.peaks_over_threshold_hpp" title="Header <boost/accumulators/statistics/peaks_over_threshold.hpp>">
<link rel="prev" href="peaks_over_threshold.html" title="Struct template peaks_over_threshold">
<link rel="next" href="abstract_peaks_idp26868464.html" title="Struct abstract_peaks_over_threshold">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
<td align="center"><a href="../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="peaks_over_threshold.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../accumulators/reference.html#header.boost.accumulators.statistics.peaks_over_threshold_hpp"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="abstract_peaks_idp26868464.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.accumulators.tag.peaks_over_threshold_prob"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct template peaks_over_threshold_prob</span></h2>
<p>boost::accumulators::tag::peaks_over_threshold_prob</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../../accumulators/reference.html#header.boost.accumulators.statistics.peaks_over_threshold_hpp" title="Header <boost/accumulators/statistics/peaks_over_threshold.hpp>">boost/accumulators/statistics/peaks_over_threshold.hpp</a>>
</span><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> LeftRight<span class="special">></span>
<span class="keyword">struct</span> <a class="link" href="peaks_over_threshold_prob.html" title="Struct template peaks_over_threshold_prob">peaks_over_threshold_prob</a> <span class="special">:</span>
<span class="keyword">public</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">accumulators</span><span class="special">::</span><span class="identifier">depends_on</span><span class="special"><</span> <span class="identifier">count</span><span class="special">,</span> <span class="identifier">tail</span><span class="special"><</span> <span class="identifier">LeftRight</span> <span class="special">></span> <span class="special">></span>
<span class="special">{</span>
<span class="special">}</span><span class="special">;</span></pre></div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2005, 2006 Eric Niebler<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="peaks_over_threshold.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../accumulators/reference.html#header.boost.accumulators.statistics.peaks_over_threshold_hpp"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="abstract_peaks_idp26868464.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"content_hash": "0cdf2a8420974a4ca57a69fccaa96087",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 529,
"avg_line_length": 91.79245283018868,
"alnum_prop": 0.6783144912641316,
"repo_name": "goldcoin/gldcoin",
"id": "ef0514fab0164850aad7f94895b44ee32380990a",
"size": "4865",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "BuildDeps/deps/boost/doc/html/boost/accumulators/tag/peaks_over_threshold_prob.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "21289"
},
{
"name": "Assembly",
"bytes": "1152300"
},
{
"name": "Awk",
"bytes": "54072"
},
{
"name": "Batchfile",
"bytes": "95617"
},
{
"name": "C",
"bytes": "30167843"
},
{
"name": "C#",
"bytes": "1801043"
},
{
"name": "C++",
"bytes": "143719415"
},
{
"name": "CMake",
"bytes": "7934"
},
{
"name": "CSS",
"bytes": "369274"
},
{
"name": "Cuda",
"bytes": "26749"
},
{
"name": "DIGITAL Command Language",
"bytes": "320412"
},
{
"name": "Emacs Lisp",
"bytes": "1639"
},
{
"name": "FORTRAN",
"bytes": "1387"
},
{
"name": "Groff",
"bytes": "29119"
},
{
"name": "HTML",
"bytes": "187929099"
},
{
"name": "IDL",
"bytes": "14"
},
{
"name": "Java",
"bytes": "4131730"
},
{
"name": "JavaScript",
"bytes": "210803"
},
{
"name": "Lex",
"bytes": "1255"
},
{
"name": "Makefile",
"bytes": "1926648"
},
{
"name": "Max",
"bytes": "36857"
},
{
"name": "NSIS",
"bytes": "5910"
},
{
"name": "Objective-C",
"bytes": "88946"
},
{
"name": "Objective-C++",
"bytes": "11420"
},
{
"name": "OpenEdge ABL",
"bytes": "66157"
},
{
"name": "PHP",
"bytes": "60328"
},
{
"name": "Perl",
"bytes": "3895713"
},
{
"name": "Perl6",
"bytes": "29655"
},
{
"name": "Prolog",
"bytes": "42455"
},
{
"name": "Protocol Buffer",
"bytes": "2764"
},
{
"name": "Python",
"bytes": "1785357"
},
{
"name": "QML",
"bytes": "593"
},
{
"name": "QMake",
"bytes": "55372"
},
{
"name": "R",
"bytes": "4009"
},
{
"name": "Rebol",
"bytes": "354"
},
{
"name": "Scheme",
"bytes": "4249"
},
{
"name": "Shell",
"bytes": "1384609"
},
{
"name": "Tcl",
"bytes": "2603631"
},
{
"name": "TeX",
"bytes": "13404"
},
{
"name": "XS",
"bytes": "198495"
},
{
"name": "XSLT",
"bytes": "761090"
},
{
"name": "Yacc",
"bytes": "18910"
},
{
"name": "eC",
"bytes": "5157"
}
],
"symlink_target": ""
} |
var curry = require('fnkit/curry');
module.exports = function(watch){
watch('todoToggled', _updateTodo({
completed: function(c){return !c;},
}));
watch('todoEdited', _updateTodo({
status:'editing'
}));
watch('todoDestroyed', onTodoDestroyed);
watch('todoSaved', _updateTodo(function(data){
return {
title: data.value,
status: 'saved'
};
}));
watch('todoCanceled', _updateTodo({
status: 'saved'
}));
watch('todoCreated', onTodoCreated);
watch('filterChanged', onFilterChanged);
watch('completedCleared', _updateTodos({
completed: false
}));
watch('allToggled', _updateTodos(function(completed){
return {
completed: completed
};
}));
};
//updates
function onTodoDestroyed(store, refs, data){
var ref = refs.todos.get(data.id),
indexes = store.get('index');
refs.todos.remove(ref);
store.unset(['todos', ref]);
store.splice('index', [indexes.indexOf(ref), 1]);
}
function onTodoCreated(store, refs, data){
var newTodo = {
title: data.val,
status: 'created'
};
var newRef = refs.todos.create(),
newId = newRef;
refs.todos.update(newRef, newId);
newTodo.id = newId;
store.set(['todos', newRef], newTodo);
store.unshift('index', newRef);
}
function onFilterChanged(store, _, filter){
store.set('filter', filter);
}
//helpers
var _updateTodo = curry(3, function _updateTodo(update, store, refs, data){
var ref = refs.todos.get(data.id),
cursor = store.select('todos');
if(typeof update === 'function'){
update = update(data);
}
Object.keys(update).forEach(function(k){
var val = update[k];
if(typeof val === 'function'){
val = val(cursor.get([ref,k]));
}
cursor.set([ref, k], val);
});
});
var _updateTodos = curry(3, function _updateTodos(update, store, _, data){
var index = store.get('index'),
cursor = store.select('todos');
if(typeof update === 'function'){
update = update(data);
}
index.forEach(function(ref){
cursor.merge(ref, update);
});
}); | {
"content_hash": "02a69d7a3479bb8591c7a63b49b3a004",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 75,
"avg_line_length": 24.59036144578313,
"alnum_prop": 0.6276335129838314,
"repo_name": "ybybzj/m-react-todomvc-perf",
"id": "c4bc9b26c18b7f6ed9f9495d72e589b885270acc",
"size": "2041",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "todomvc/m-react/app/update.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "39699"
},
{
"name": "Clojure",
"bytes": "12407"
},
{
"name": "HTML",
"bytes": "350260"
},
{
"name": "JavaScript",
"bytes": "667789"
}
],
"symlink_target": ""
} |
require "securerandom"
require "active_support/dependencies/autoload"
require "active_support/version"
require "active_support/logger"
require "active_support/lazy_load_hooks"
require "active_support/core_ext/date_and_time/compatibility"
module ActiveSupport
extend ActiveSupport::Autoload
autoload :Concern
autoload :CodeGenerator
autoload :ActionableError
autoload :ConfigurationFile
autoload :CurrentAttributes
autoload :Dependencies
autoload :DescendantsTracker
autoload :ExecutionContext
autoload :ExecutionWrapper
autoload :Executor
autoload :ErrorReporter
autoload :FileUpdateChecker
autoload :EventedFileUpdateChecker
autoload :ForkTracker
autoload :LogSubscriber
autoload :IsolatedExecutionState
autoload :Notifications
autoload :Reloader
autoload :PerThreadRegistry
autoload :SecureCompareRotator
eager_autoload do
autoload :BacktraceCleaner
autoload :ProxyObject
autoload :Benchmarkable
autoload :Cache
autoload :Callbacks
autoload :Configurable
autoload :Deprecation
autoload :Digest
autoload :Gzip
autoload :Inflector
autoload :JSON
autoload :JsonWithMarshalFallback
autoload :KeyGenerator
autoload :MessageEncryptor
autoload :MessageVerifier
autoload :Multibyte
autoload :NumberHelper
autoload :OptionMerger
autoload :OrderedHash
autoload :OrderedOptions
autoload :StringInquirer
autoload :EnvironmentInquirer
autoload :TaggedLogging
autoload :XmlMini
autoload :ArrayInquirer
end
autoload :Rescuable
autoload :SafeBuffer, "active_support/core_ext/string/output_safety"
autoload :TestCase
def self.eager_load!
super
NumberHelper.eager_load!
end
cattr_accessor :test_order # :nodoc:
cattr_accessor :test_parallelization_threshold, default: 50 # :nodoc:
singleton_class.attr_accessor :error_reporter # :nodoc:
def self.cache_format_version
Cache.format_version
end
def self.cache_format_version=(value)
Cache.format_version = value
end
def self.to_time_preserves_timezone
DateAndTime::Compatibility.preserve_timezone
end
def self.to_time_preserves_timezone=(value)
DateAndTime::Compatibility.preserve_timezone = value
end
def self.utc_to_local_returns_utc_offset_times
DateAndTime::Compatibility.utc_to_local_returns_utc_offset_times
end
def self.utc_to_local_returns_utc_offset_times=(value)
DateAndTime::Compatibility.utc_to_local_returns_utc_offset_times = value
end
end
autoload :I18n, "active_support/i18n"
| {
"content_hash": "03879096ee128526ed0fa075e95b7ea2",
"timestamp": "",
"source": "github",
"line_count": 100,
"max_line_length": 76,
"avg_line_length": 25.56,
"alnum_prop": 0.7664319248826291,
"repo_name": "kddeisz/rails",
"id": "de0a46d68901df0267440c01e071b8a6debee56d",
"size": "3706",
"binary": false,
"copies": "1",
"ref": "refs/heads/annotations",
"path": "activesupport/lib/active_support.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "47086"
},
{
"name": "CoffeeScript",
"bytes": "24535"
},
{
"name": "HTML",
"bytes": "495148"
},
{
"name": "JavaScript",
"bytes": "185199"
},
{
"name": "Ruby",
"bytes": "13364532"
},
{
"name": "Shell",
"bytes": "4531"
},
{
"name": "Yacc",
"bytes": "983"
}
],
"symlink_target": ""
} |
require File.expand_path('../../../spec_helper', __FILE__)
describe "Mutex#unlock" do
it "raises ThreadError unless Mutex is locked" do
mutex = Mutex.new
lambda { mutex.unlock }.should raise_error(ThreadError)
end
it "raises ThreadError unless thread owns Mutex" do
mutex = Mutex.new
wait = Mutex.new
wait.lock
th = Thread.new do
mutex.lock
wait.lock
end
# avoid race on mutex.lock
Thread.pass while th.status and th.status != "sleep"
lambda { mutex.unlock }.should raise_error(ThreadError)
wait.unlock
th.join
end
it "raises ThreadError if previously locking thread is gone" do
mutex = Mutex.new
th = Thread.new do
mutex.lock
end
th.join
lambda { mutex.unlock }.should raise_error(ThreadError)
end
end
| {
"content_hash": "6d96f48029e7550f7d9ee4caea7ac324",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 65,
"avg_line_length": 21.864864864864863,
"alnum_prop": 0.657601977750309,
"repo_name": "benlovell/rubyspec",
"id": "9e4116f7b9db0b9ded9e789cc18a77750c6aec30",
"size": "809",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "core/mutex/unlock_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "184707"
},
{
"name": "Ruby",
"bytes": "5181000"
}
],
"symlink_target": ""
} |
import Ember from 'ember';
import layout from '../templates/components/materialize-collapsible';
export default Ember.Component.extend({
layout: layout,
tagName: 'li',
classNameBindings: 'class'
});
| {
"content_hash": "7100d9417521bd0e1e51cbc684212938",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 69,
"avg_line_length": 25.75,
"alnum_prop": 0.7427184466019418,
"repo_name": "rtablada/ember-cli-materialize",
"id": "1d7d16e32206292fd3be8aac984b76587bfd7811",
"size": "206",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "addon/components/materialize-collapsible.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1656"
},
{
"name": "HTML",
"bytes": "2084"
},
{
"name": "Handlebars",
"bytes": "43514"
},
{
"name": "JavaScript",
"bytes": "47129"
}
],
"symlink_target": ""
} |
package com.github.aleksandermielczarek.observablecache;
import android.support.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
import rx.Observable;
import rx.Single;
/**
* Created by Aleksander Mielczarek on 30.10.2016.
*/
public final class MapObservableCache extends ObservableCache {
private static volatile ObservableCache defaultInstance;
private final Map<String, Observable<?>> observables;
private final Map<String, Single<?>> singles;
private MapObservableCache() {
observables = new HashMap<>();
singles = new HashMap<>();
}
private MapObservableCache(int size) {
observables = new HashMap<>(size);
singles = new HashMap<>(size);
}
public static ObservableCache getDefault() {
if (defaultInstance == null) {
synchronized (ObservableCache.class) {
if (defaultInstance == null) {
defaultInstance = newInstance();
}
}
}
return defaultInstance;
}
public static ObservableCache newInstance() {
return new MapObservableCache();
}
public static ObservableCache newInstance(int size) {
return new MapObservableCache(size);
}
@Override
protected <T> void cache(String key, Observable<T> observable) {
observables.put(key, observable);
}
@Override
protected <T> void cache(String key, Single<T> single) {
singles.put(key, single);
}
@Override
public boolean clear() {
boolean empty = isEmpty();
observables.clear();
singles.clear();
return !empty;
}
@Override
public boolean remove(String key) {
Observable<?> removedObservable = observables.remove(key);
Single<?> removedSingle = singles.remove(key);
return removedObservable != null || removedSingle != null;
}
@Override
public int size() {
return observables.size() + singles.size();
}
@Override
public boolean exists(String key) {
return observables.containsKey(key) || singles.containsKey(key);
}
@Override
public boolean isEmpty() {
return observables.isEmpty() && singles.isEmpty();
}
@Override
@Nullable
@SuppressWarnings("unchecked")
protected <T> Observable<T> getObservableFromCache(String key) {
return (Observable<T>) observables.get(key);
}
@Nullable
@Override
@SuppressWarnings("unchecked")
protected <T> Single<T> getSingleFromCache(String key) {
return (Single<T>) singles.get(key);
}
}
| {
"content_hash": "bcdd48b962405045dec7f2986a90b3f0",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 72,
"avg_line_length": 25.346153846153847,
"alnum_prop": 0.6312594840667678,
"repo_name": "AleksanderMielczarek/ObservableCache",
"id": "971e2df2237f60ec2eeca42e3228af960bf070d2",
"size": "2636",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "observable-cache-1/src/main/java/com/github/aleksandermielczarek/observablecache/MapObservableCache.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "151407"
}
],
"symlink_target": ""
} |
package builtin_md;
public class builtin_concurrent_Future_onFinished_Method extends builtin.reflect.Method implements io.datawire.quark.runtime.QObject {
public builtin_concurrent_Future_onFinished_Method() {
super("builtin.void", "onFinished", new java.util.ArrayList(java.util.Arrays.asList(new Object[]{"builtin.concurrent.FutureListener"})));
}
public Object invoke(Object object, java.util.ArrayList<Object> args) {
builtin.concurrent.Future obj = (builtin.concurrent.Future) (object);
(obj).onFinished((builtin.concurrent.FutureListener) ((args).get(0)));
return null;
}
public String _getClass() {
return (String) (null);
}
public Object _getField(String name) {
return null;
}
public void _setField(String name, Object value) {}
}
| {
"content_hash": "b859db3f14718df0f48db3e8722afd73",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 145,
"avg_line_length": 43.421052631578945,
"alnum_prop": 0.6933333333333334,
"repo_name": "bozzzzo/quark",
"id": "e6f572e14eda246c33c523b3c7f1e3bae8e3b0c9",
"size": "825",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "quarkc/test/emit/expected/java/builtin/src/main/java/builtin_md/builtin_concurrent_Future_onFinished_Method.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "496221"
},
{
"name": "JavaScript",
"bytes": "466971"
},
{
"name": "Python",
"bytes": "590150"
},
{
"name": "Shell",
"bytes": "1328"
}
],
"symlink_target": ""
} |
package jp.ac.hal.kobayashi.simplejava;
public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
| {
"content_hash": "ef5483cdbcbb043c32385e30e75f35ec",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 41,
"avg_line_length": 20.857142857142858,
"alnum_prop": 0.7123287671232876,
"repo_name": "java-samples/java-hello",
"id": "699040558158f0aa60a5350f7d5456532ba47637",
"size": "146",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/jp/ac/hal/kobayashi/simplejava/Main.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "146"
}
],
"symlink_target": ""
} |
import { Component, OnInit } from '@angular/core';
import { Hero, HeroService } from './heroes';
@Component({
moduleId: module.id,
selector: 'sg-app',
templateUrl: 'app.component.html',
providers: [HeroService]
})
export class AppComponent implements OnInit {
heroes: Hero[];
constructor(private heroService: HeroService) { }
ngOnInit() {
this.heroService.getHeroes().subscribe(heroes => this.heroes = heroes);
}
}
| {
"content_hash": "a9432d0b06b59dfe3ee94c950473fe78",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 75,
"avg_line_length": 23.105263157894736,
"alnum_prop": 0.6924829157175398,
"repo_name": "GuzmanPI/angular-es",
"id": "5b10b49c37b61f995cb7fe91c3a51e580f995ce0",
"size": "439",
"binary": false,
"copies": "13",
"ref": "refs/heads/master",
"path": "public/docs/_examples/style-guide/ts/07-01/app/app.component.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "135236"
},
{
"name": "Dart",
"bytes": "133899"
},
{
"name": "HTML",
"bytes": "2123981"
},
{
"name": "JavaScript",
"bytes": "155560"
},
{
"name": "Shell",
"bytes": "12589"
},
{
"name": "TypeScript",
"bytes": "690244"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false">
<shape>
<solid android:color="@color/orange1"/>
<corners android:radius="8dp"/>
</shape>
</item>
<item android:state_pressed="true">
<shape>
<solid android:color="@color/orange2"/>
<corners android:radius="8dp"/>
</shape>
</item>
</selector> | {
"content_hash": "403a6d183a44266db03a89830f83c805",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 69,
"avg_line_length": 30.25,
"alnum_prop": 0.5640495867768595,
"repo_name": "LSL-Git/ImageLabelerApp",
"id": "b4fc7c7ab20c6370457ff1fee3c696214190ef02",
"size": "484",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/drawable/but_bg2.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "747600"
}
],
"symlink_target": ""
} |
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="jcommon-init [clean, install, site]" type="MavenRunConfiguration" factoryName="Maven">
<MavenSettings>
<option name="myGeneralSettings" />
<option name="myRunnerSettings" />
<option name="myRunnerParameters">
<MavenRunnerParameters>
<option name="profiles">
<set />
</option>
<option name="goals">
<list>
<option value="clean" />
<option value="install" />
<option value="site" />
</list>
</option>
<option name="profilesMap">
<map />
</option>
<option name="workingDirPath" value="$PROJECT_DIR$" />
</MavenRunnerParameters>
</option>
</MavenSettings>
<RunnerSettings RunnerId="Run" />
<ConfigurationWrapper RunnerId="Run" />
<method />
</configuration>
</component> | {
"content_hash": "42b1e30e65905a70e3504dee95bd8222",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 125,
"avg_line_length": 33.689655172413794,
"alnum_prop": 0.5660184237461617,
"repo_name": "jcommon/init",
"id": "c85c028631451ab0e3a5700332211177f990e84b",
"size": "977",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/runConfigurations/jcommon_init__clean__install__site_.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "168158"
},
{
"name": "JavaScript",
"bytes": "138"
},
{
"name": "Shell",
"bytes": "297"
}
],
"symlink_target": ""
} |
import os
import pytest
TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
@pytest.fixture
def fixtures_dir():
return os.path.join(TESTS_DIR, 'fixtures')
| {
"content_hash": "bbaccb2b706d0ab817ff2472333b1b3d",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 54,
"avg_line_length": 18.333333333333332,
"alnum_prop": 0.7090909090909091,
"repo_name": "red-hat-storage/rhcephcompose",
"id": "b217a51a0479bfb18f18871cebe6f245fca14274",
"size": "165",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rhcephcompose/tests/conftest.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "53761"
},
{
"name": "Shell",
"bytes": "691"
}
],
"symlink_target": ""
} |
@class CContact, EnterpriseBrandContactHelper, ForwardMessageLogicController, MMScrollView, MMTableView, NSArray, NSMutableArray, NSMutableDictionary, NSString;
@interface EnterpriseBrandContactListViewController : MMUIViewController <ForwardMessageLogicDelegate, EnterpriseBrandContactHelperDelegate, UITableViewDataSource, UITableViewDelegate, contactInfoDelegate, IEnterpriseBrandContactMgrExt, IEnterpriseGroupMgrExt>
{
ForwardMessageLogicController *m_forwardLogic;
NSMutableArray *_sectionKeyArray;
NSMutableDictionary *_allContactsDic;
CContact *_mainBrandContact;
NSArray *_arySubBrandContact;
MMTableView *_tableView;
MMScrollView *_emptyView;
unsigned int _fromScene;
unsigned int _statContactCount;
unsigned int _enterTime;
EnterpriseBrandContactHelper *_helper;
}
- (void).cxx_destruct;
- (void)makeChatBrandCell:(id)arg1 head:(id)arg2 title:(id)arg3;
- (void)openMainBrandInfo:(id)arg1;
- (void)openEnterpriseChat;
- (void)openDisabledBrandList:(id)arg1;
- (id)getCurrentViewController;
- (void)shareToFriend:(id)arg1;
- (void)showRightTopMenuBtn:(id)arg1;
- (void)onCreateEnterpriseGroup:(id)arg1 errorCode:(int)arg2 extDic:(id)arg3;
- (void)onEnterpriseBrandContactDeleted:(id)arg1;
- (void)onEnterpriseBrandContactChanged:(id)arg1;
- (id)getViewController;
- (void)tableView:(id)arg1 commitEditingStyle:(long long)arg2 forRowAtIndexPath:(id)arg3;
- (void)tableView:(id)arg1 didSelectRowAtIndexPath:(id)arg2;
- (_Bool)tableView:(id)arg1 canEditRowAtIndexPath:(id)arg2;
- (id)tableView:(id)arg1 titleForDeleteConfirmationButtonForRowAtIndexPath:(id)arg2;
- (long long)tableView:(id)arg1 editingStyleForRowAtIndexPath:(id)arg2;
- (void)tableView:(id)arg1 willDisplayCell:(id)arg2 forRowAtIndexPath:(id)arg3;
- (id)tableView:(id)arg1 cellForRowAtIndexPath:(id)arg2;
- (id)tableView:(id)arg1 viewForHeaderInSection:(long long)arg2;
- (id)tableView:(id)arg1 titleForHeaderInSection:(long long)arg2;
- (id)sectionIndexTitlesForTableView:(id)arg1;
- (double)tableView:(id)arg1 heightForHeaderInSection:(long long)arg2;
- (double)tableView:(id)arg1 heightForRowAtIndexPath:(id)arg2;
- (long long)tableView:(id)arg1 sectionForSectionIndexTitle:(id)arg2 atIndex:(long long)arg3;
- (long long)tableView:(id)arg1 numberOfRowsInSection:(long long)arg2;
- (long long)numberOfSectionsInTableView:(id)arg1;
- (void)reportQuit;
- (void)reportEnter;
- (void)viewWillBePoped:(_Bool)arg1;
- (void)viewDidLayoutSubviews;
- (void)viewDidLoad;
- (void)updateEmptyView;
- (void)initEmptyView;
- (void)initTableView;
- (void)initView;
- (void)initData;
- (void)dealloc;
- (id)initWithMainContact:(id)arg1 fromScene:(unsigned int)arg2;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
| {
"content_hash": "828ede4b8e574c4ddfbb34da378c4313",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 260,
"avg_line_length": 44.44615384615385,
"alnum_prop": 0.7923156801661475,
"repo_name": "walkdianzi/DashengHook",
"id": "4dc72137b62515ecc68090fc5a874d7762b86205",
"size": "3325",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WeChat-Headers/EnterpriseBrandContactListViewController.h",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "986"
},
{
"name": "Objective-C",
"bytes": "10153542"
},
{
"name": "Objective-C++",
"bytes": "18332"
},
{
"name": "Shell",
"bytes": "1459"
}
],
"symlink_target": ""
} |
//go:build e2e
// +build e2e
package conformance
import (
"context"
"log"
"os"
"strings"
"testing"
"knative.dev/pkg/system"
"knative.dev/eventing/test"
testlib "knative.dev/eventing/test/lib"
"knative.dev/eventing/test/lib/setupclientoptions"
"knative.dev/pkg/test/zipkin"
)
const (
recordEventsAPIPodName = "api-server-source-logger-pod"
recordEventsPingPodName = "ping-source-logger-pod"
)
var channelTestRunner testlib.ComponentsTestRunner
var sourcesTestRunner testlib.ComponentsTestRunner
var brokerTestRunner testlib.ComponentsTestRunner
var brokerClass string
func TestMain(m *testing.M) {
os.Exit(func() int {
test.InitializeEventingFlags()
testlib.ReuseNamespace = test.EventingFlags.ReuseNamespace
channelTestRunner = testlib.ComponentsTestRunner{
ComponentFeatureMap: testlib.ChannelFeatureMap,
ComponentsToTest: test.EventingFlags.Channels,
}
sourcesTestRunner = testlib.ComponentsTestRunner{
ComponentFeatureMap: testlib.SourceFeatureMap,
ComponentsToTest: test.EventingFlags.Sources,
}
brokerTestRunner = testlib.ComponentsTestRunner{
ComponentFeatureMap: testlib.BrokerFeatureMap,
ComponentsToTest: test.EventingFlags.Brokers,
ComponentName: test.EventingFlags.BrokerName,
ComponentNamespace: test.EventingFlags.BrokerNamespace,
}
brokerClass = test.EventingFlags.BrokerClass
addSourcesInitializers()
// Any tests may SetupZipkinTracing, it will only actually be done once. This should be the ONLY
// place that cleans it up. If an individual test calls this instead, then it will break other
// tests that need the tracing in place.
defer zipkin.CleanupZipkinTracingSetup(log.Printf)
exit := m.Run()
// Collect logs only when test failed.
if exit != 0 {
testlib.ExportLogs(testlib.SystemLogsDir, system.Namespace())
}
return exit
}())
}
func addSourcesInitializers() {
ctx := context.Background()
apiSrcName := strings.ToLower(testlib.ApiServerSourceTypeMeta.Kind)
pingSrcName := strings.ToLower(testlib.PingSourceTypeMeta.Kind)
sourcesTestRunner.AddComponentSetupClientOption(
testlib.ApiServerSourceTypeMeta,
setupclientoptions.ApiServerSourceV1ClientSetupOption(
ctx, apiSrcName, "Reference",
recordEventsAPIPodName),
)
sourcesTestRunner.AddComponentSetupClientOption(
testlib.PingSourceTypeMeta,
setupclientoptions.PingSourceV1B2ClientSetupOption(
ctx, pingSrcName, recordEventsPingPodName),
)
}
| {
"content_hash": "fee3843d84d8ab5539dab4f1019eb04e",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 98,
"avg_line_length": 28.823529411764707,
"alnum_prop": 0.7836734693877551,
"repo_name": "knative/eventing",
"id": "26ece5f4bc7a9a454b4b8b00a177a3b270d56d90",
"size": "3014",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "test/conformance/main_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "3696443"
},
{
"name": "Shell",
"bytes": "45068"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 322131 $ -->
<refentry xml:id="function.mysqlnd-qc-clear-cache" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
<refnamediv>
<refname>mysqlnd_qc_clear_cache</refname>
<refpurpose>Flush all cache contents</refpurpose>
</refnamediv>
<refsect1 role="description">
&reftitle.description;
<methodsynopsis>
<type>bool</type>
<methodname>mysqlnd_qc_clear_cache</methodname>
<void />
</methodsynopsis>
<para>
Flush all cache contents.
</para>
<para>
Flushing the cache is a storage handler responsibility.
All built-in storage handler but the
<literal>memcache</literal> storage
handler support flushing the cache. The
<literal>memcache</literal>
storage handler cannot flush its cache contents.
</para>
<para>
User-defined storage handler may or may not support the operation.
</para>
</refsect1>
<refsect1 role="parameters">
&reftitle.parameters;
&no.function.parameters;
</refsect1>
<refsect1 role="returnvalues">
&reftitle.returnvalues;
<para>
&return.success;
</para>
<para>
A return value of
&false;
indicates that flushing all cache contents has
failed or the operation is not supported by
the active storage handler. Applications must
not expect that calling the function will always
flush the cache.
</para>
</refsect1>
</refentry>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
| {
"content_hash": "1cd35fef99a0b6fed5bd0d4689c1a1cd",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 132,
"avg_line_length": 24.454545454545453,
"alnum_prop": 0.7211895910780669,
"repo_name": "mziyut/.vim",
"id": "c3b9d54311a499fa4a698366834f2e75cf583dab",
"size": "1883",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "dict/.neocomplete-php/phpdoc/en/reference/mysqlnd_qc/functions/mysqlnd-qc-clear-cache.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2223"
},
{
"name": "Ruby",
"bytes": "939"
},
{
"name": "Shell",
"bytes": "582"
},
{
"name": "Vim script",
"bytes": "22415"
}
],
"symlink_target": ""
} |
interface ISessionExpirationService {
getSessionExpiredStream(): Rx.Observable<{}>;
} | {
"content_hash": "dc7b34c47e6101bdb55e9051fdaa9701",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 49,
"avg_line_length": 30.333333333333332,
"alnum_prop": 0.7582417582417582,
"repo_name": "LeeCampbell/ReactiveTrader",
"id": "be65327bd6b1d0466bbc1e14cd69358aa9195e9d",
"size": "93",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "src/Adaptive.ReactiveTrader.Web/Client/Session/ISessionExpirationService.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "14189"
},
{
"name": "Batchfile",
"bytes": "1136"
},
{
"name": "C#",
"bytes": "498247"
},
{
"name": "CSS",
"bytes": "2681"
},
{
"name": "HTML",
"bytes": "53452"
},
{
"name": "JavaScript",
"bytes": "64267"
},
{
"name": "TypeScript",
"bytes": "70391"
}
],
"symlink_target": ""
} |
<?php
namespace Sylius\Bundle\VariationBundle\Form\Type;
use Sylius\Bundle\ResourceBundle\Form\EventSubscriber\AddCodeFormSubscriber;
use Sylius\Bundle\ResourceBundle\Form\Type\AbstractResourceType;
use Sylius\Bundle\VariationBundle\Form\EventListener\BuildVariantFormSubscriber;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
class VariantType extends AbstractResourceType
{
/**
* @var string
*/
protected $variableName;
/**
* @param string $dataClass
* @param array $validationGroups
* @param string $variableName
*/
public function __construct($dataClass, array $validationGroups, $variableName)
{
parent::__construct($dataClass, $validationGroups);
$this->variableName = $variableName;
}
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text', [
'required' => false,
'label' => 'sylius.form.variant.name',
])
->addEventSubscriber(new AddCodeFormSubscriber())
;
$builder->addEventSubscriber(new BuildVariantFormSubscriber($this->variableName, $builder->getFormFactory()));
}
/**
* {@inheritdoc}
*/
public function getName()
{
return sprintf('sylius_%s_variant', $this->variableName);
}
}
| {
"content_hash": "1bbbc4534ac87eca7b17f6ea3593aa74",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 118,
"avg_line_length": 26.051724137931036,
"alnum_prop": 0.6525479814692257,
"repo_name": "TeamNovatek/Sylius",
"id": "6ae3a678ef94f654e801f662cb41995a8789062b",
"size": "1724",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "src/Sylius/Bundle/VariationBundle/Form/Type/VariantType.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "519"
},
{
"name": "CSS",
"bytes": "78975"
},
{
"name": "Cucumber",
"bytes": "352667"
},
{
"name": "HTML",
"bytes": "644510"
},
{
"name": "JavaScript",
"bytes": "158221"
},
{
"name": "PHP",
"bytes": "6875033"
},
{
"name": "Puppet",
"bytes": "3165"
},
{
"name": "Ruby",
"bytes": "1210"
},
{
"name": "Shell",
"bytes": "27856"
}
],
"symlink_target": ""
} |
include(hunter_add_version)
include(hunter_cacheable)
include(hunter_download)
include(hunter_pick_scheme)
hunter_add_version(
PACKAGE_NAME
SQLite3
VERSION
"autoconf-3080803"
URL
"https://www.sqlite.org/2015/sqlite-autoconf-3080803.tar.gz"
SHA1
2fe3f6226a2a08a2e814b97cd53e36bb3c597112
)
hunter_pick_scheme(DEFAULT url_sha1_sqlite3_autotools)
hunter_cacheable(SQLite3)
hunter_download(PACKAGE_NAME SQLite3)
| {
"content_hash": "ac6862437aecd4a3455298a5698a54cd",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 64,
"avg_line_length": 23.210526315789473,
"alnum_prop": 0.7687074829931972,
"repo_name": "daminetreg/hunter",
"id": "bc5c43b10d7a845f98084b13bb8684fa5951bdb0",
"size": "565",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "cmake/projects/SQLite3/hunter.cmake",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C++",
"bytes": "50732"
},
{
"name": "CMake",
"bytes": "664399"
},
{
"name": "Python",
"bytes": "27406"
},
{
"name": "Shell",
"bytes": "15620"
}
],
"symlink_target": ""
} |
package org.apache.camel.builder.endpoint.dsl;
import javax.annotation.Generated;
import org.apache.camel.builder.EndpointConsumerBuilder;
import org.apache.camel.builder.EndpointProducerBuilder;
import org.apache.camel.builder.endpoint.AbstractEndpointBuilder;
/**
* Access OpenStack Swift object/blob store.
*
* Generated by camel build tools - do NOT edit this file!
*/
@Generated("org.apache.camel.maven.packaging.EndpointDslMojo")
public interface SwiftEndpointBuilderFactory {
/**
* Builder for endpoint for the OpenStack Swift component.
*/
public interface SwiftEndpointBuilder extends EndpointProducerBuilder {
/**
* OpenStack API version.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: V3
* Group: producer
*
* @param apiVersion the value to set
* @return the dsl builder
*/
default SwiftEndpointBuilder apiVersion(String apiVersion) {
doSetProperty("apiVersion", apiVersion);
return this;
}
/**
* OpenStack configuration.
*
* The option is a:
* <code>org.openstack4j.core.transport.Config</code> type.
*
* Group: producer
*
* @param config the value to set
* @return the dsl builder
*/
default SwiftEndpointBuilder config(Object config) {
doSetProperty("config", config);
return this;
}
/**
* OpenStack configuration.
*
* The option will be converted to a
* <code>org.openstack4j.core.transport.Config</code> type.
*
* Group: producer
*
* @param config the value to set
* @return the dsl builder
*/
default SwiftEndpointBuilder config(String config) {
doSetProperty("config", config);
return this;
}
/**
* Authentication domain.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: default
* Group: producer
*
* @param domain the value to set
* @return the dsl builder
*/
default SwiftEndpointBuilder domain(String domain) {
doSetProperty("domain", domain);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default SwiftEndpointBuilder lazyStartProducer(boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default SwiftEndpointBuilder lazyStartProducer(String lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* The operation to do.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param operation the value to set
* @return the dsl builder
*/
default SwiftEndpointBuilder operation(String operation) {
doSetProperty("operation", operation);
return this;
}
/**
* OpenStack password.
*
* The option is a: <code>java.lang.String</code> type.
*
* Required: true
* Group: producer
*
* @param password the value to set
* @return the dsl builder
*/
default SwiftEndpointBuilder password(String password) {
doSetProperty("password", password);
return this;
}
/**
* The project ID.
*
* The option is a: <code>java.lang.String</code> type.
*
* Required: true
* Group: producer
*
* @param project the value to set
* @return the dsl builder
*/
default SwiftEndpointBuilder project(String project) {
doSetProperty("project", project);
return this;
}
/**
* OpenStack Swift subsystem.
*
* The option is a: <code>java.lang.String</code> type.
*
* Required: true
* Group: producer
*
* @param subsystem the value to set
* @return the dsl builder
*/
default SwiftEndpointBuilder subsystem(String subsystem) {
doSetProperty("subsystem", subsystem);
return this;
}
/**
* OpenStack username.
*
* The option is a: <code>java.lang.String</code> type.
*
* Required: true
* Group: producer
*
* @param username the value to set
* @return the dsl builder
*/
default SwiftEndpointBuilder username(String username) {
doSetProperty("username", username);
return this;
}
}
public interface SwiftBuilders {
/**
* OpenStack Swift (camel-openstack)
* Access OpenStack Swift object/blob store.
*
* Category: cloud,paas
* Since: 2.19
* Maven coordinates: org.apache.camel:camel-openstack
*
* Syntax: <code>openstack-swift:host</code>
*
* Path parameter: host (required)
* OpenStack host url
*
* @param path host
* @return the dsl builder
*/
default SwiftEndpointBuilder openstackSwift(String path) {
return SwiftEndpointBuilderFactory.endpointBuilder("openstack-swift", path);
}
/**
* OpenStack Swift (camel-openstack)
* Access OpenStack Swift object/blob store.
*
* Category: cloud,paas
* Since: 2.19
* Maven coordinates: org.apache.camel:camel-openstack
*
* Syntax: <code>openstack-swift:host</code>
*
* Path parameter: host (required)
* OpenStack host url
*
* @param componentName to use a custom component name for the endpoint
* instead of the default name
* @param path host
* @return the dsl builder
*/
default SwiftEndpointBuilder openstackSwift(
String componentName,
String path) {
return SwiftEndpointBuilderFactory.endpointBuilder(componentName, path);
}
}
static SwiftEndpointBuilder endpointBuilder(
String componentName,
String path) {
class SwiftEndpointBuilderImpl extends AbstractEndpointBuilder implements SwiftEndpointBuilder {
public SwiftEndpointBuilderImpl(String path) {
super(componentName, path);
}
}
return new SwiftEndpointBuilderImpl(path);
}
} | {
"content_hash": "141ecd711d713b7847364fc30328c516",
"timestamp": "",
"source": "github",
"line_count": 259,
"max_line_length": 104,
"avg_line_length": 34.15444015444015,
"alnum_prop": 0.5683924937825006,
"repo_name": "pax95/camel",
"id": "2a3c36a21f5af69e174a089ea1d4a0eeead89559",
"size": "9648",
"binary": false,
"copies": "5",
"ref": "refs/heads/CAMEL-17322",
"path": "core/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SwiftEndpointBuilderFactory.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Apex",
"bytes": "6519"
},
{
"name": "Batchfile",
"bytes": "1518"
},
{
"name": "CSS",
"bytes": "30373"
},
{
"name": "Elm",
"bytes": "10852"
},
{
"name": "FreeMarker",
"bytes": "11410"
},
{
"name": "Groovy",
"bytes": "54390"
},
{
"name": "HTML",
"bytes": "190919"
},
{
"name": "Java",
"bytes": "68575773"
},
{
"name": "JavaScript",
"bytes": "90399"
},
{
"name": "Makefile",
"bytes": "513"
},
{
"name": "PLSQL",
"bytes": "1419"
},
{
"name": "Python",
"bytes": "36"
},
{
"name": "Ruby",
"bytes": "4802"
},
{
"name": "Scala",
"bytes": "323702"
},
{
"name": "Shell",
"bytes": "17107"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "Thrift",
"bytes": "6979"
},
{
"name": "XQuery",
"bytes": "546"
},
{
"name": "XSLT",
"bytes": "284638"
}
],
"symlink_target": ""
} |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->libdir . '/medialib.php');
/**
* Test script for media embedding.
*/
class core_medialib_testcase extends advanced_testcase {
/** @var array Files covered by test */
public static $includecoverage = array('lib/medialib.php', 'lib/outputrenderers.php');
/**
* Pre-test setup. Preserves $CFG.
*/
public function setUp() {
global $CFG;
parent::setUp();
// Reset $CFG and $SERVER.
$this->resetAfterTest();
// Consistent initial setup: all players disabled.
$CFG->core_media_enable_html5video = false;
$CFG->core_media_enable_html5audio = false;
$CFG->core_media_enable_mp3 = false;
$CFG->core_media_enable_flv = false;
$CFG->core_media_enable_wmp = false;
$CFG->core_media_enable_qt = false;
$CFG->core_media_enable_rm = false;
$CFG->core_media_enable_youtube = false;
$CFG->core_media_enable_vimeo = false;
$CFG->core_media_enable_swf = false;
$_SERVER = array('HTTP_USER_AGENT' => '');
$this->pretend_to_be_safari();
}
/**
* Sets user agent to Safari.
*/
private function pretend_to_be_safari() {
// Pretend to be using Safari browser (must support mp4 for tests to work).
core_useragent::instance(true, 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; de-at) ' .
'AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1');
}
/**
* Sets user agent to Firefox.
*/
private function pretend_to_be_firefox() {
// Pretend to be using Firefox browser (must support ogg for tests to work).
core_useragent::instance(true, 'Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0');
}
/**
* Test for the core_media_player is_enabled.
*/
public function test_is_enabled() {
global $CFG;
// Test enabled: unset, 0, 1.
$test = new core_media_player_test;
$this->assertFalse($test->is_enabled());
$CFG->core_media_enable_test = 0;
$this->assertFalse($test->is_enabled());
$CFG->core_media_enable_test = 1;
$this->assertTrue($test->is_enabled());
}
/**
* Test for core_media::get_filename.
*/
public function test_get_filename() {
$this->assertSame('frog.mp4', core_media::get_filename(new moodle_url(
'/pluginfile.php/312/mod_page/content/7/frog.mp4')));
// This should work even though slasharguments is true, because we want
// it to support 'legacy' links if somebody toggles the option later.
$this->assertSame('frog.mp4', core_media::get_filename(new moodle_url(
'/pluginfile.php?file=/312/mod_page/content/7/frog.mp4')));
}
/**
* Test for core_media::get_extension.
*/
public function test_get_extension() {
$this->assertSame('mp4', core_media::get_extension(new moodle_url(
'/pluginfile.php/312/mod_page/content/7/frog.mp4')));
$this->assertSame('', core_media::get_extension(new moodle_url(
'/pluginfile.php/312/mod_page/content/7/frog')));
$this->assertSame('mp4', core_media::get_extension(new moodle_url(
'/pluginfile.php?file=/312/mod_page/content/7/frog.mp4')));
$this->assertSame('', core_media::get_extension(new moodle_url(
'/pluginfile.php?file=/312/mod_page/content/7/frog')));
}
/**
* Test for the core_media_player list_supported_urls.
*/
public function test_list_supported_urls() {
global $CFG;
$test = new core_media_player_test;
// Some example URLs.
$supported1 = new moodle_url('http://example.org/1.test');
$supported2 = new moodle_url('http://example.org/2.TST');
$unsupported = new moodle_url('http://example.org/2.jpg');
// No URLs => none.
$result = $test->list_supported_urls(array());
$this->assertEquals(array(), $result);
// One supported URL => same.
$result = $test->list_supported_urls(array($supported1));
$this->assertEquals(array($supported1), $result);
// Two supported URLS => same.
$result = $test->list_supported_urls(array($supported1, $supported2));
$this->assertEquals(array($supported1, $supported2), $result);
// One unsupported => none.
$result = $test->list_supported_urls(array($unsupported));
$this->assertEquals(array(), $result);
// Two supported and one unsupported => same.
$result = $test->list_supported_urls(array($supported2, $unsupported, $supported1));
$this->assertEquals(array($supported2, $supported1), $result);
}
/**
* Test for core_media_renderer get_players
*/
public function test_get_players() {
global $CFG, $PAGE;
// All players are initially disabled (except link, which you can't).
$renderer = new core_media_renderer_test($PAGE, '');
$this->assertSame('link', $renderer->get_players_test());
// A couple enabled, check the order.
$CFG->core_media_enable_html5audio = true;
$CFG->core_media_enable_mp3 = true;
$renderer = new core_media_renderer_test($PAGE, '');
$this->assertSame('mp3, html5audio, link', $renderer->get_players_test());
}
/**
* Test for core_media_renderer can_embed_url
*/
public function test_can_embed_url() {
global $CFG, $PAGE;
// All players are initially disabled, so mp4 cannot be rendered.
$url = new moodle_url('http://example.org/test.mp4');
$renderer = new core_media_renderer_test($PAGE, '');
$this->assertFalse($renderer->can_embed_url($url));
// Enable QT player.
$CFG->core_media_enable_qt = true;
$renderer = new core_media_renderer_test($PAGE, '');
$this->assertTrue($renderer->can_embed_url($url));
// QT + html5.
$CFG->core_media_enable_html5video = true;
$renderer = new core_media_renderer_test($PAGE, '');
$this->assertTrue($renderer->can_embed_url($url));
// Only html5.
$CFG->core_media_enable_qt = false;
$renderer = new core_media_renderer_test($PAGE, '');
$this->assertTrue($renderer->can_embed_url($url));
// Only WMP.
$CFG->core_media_enable_html5video = false;
$CFG->core_media_enable_wmp = true;
$renderer = new core_media_renderer_test($PAGE, '');
$this->assertFalse($renderer->can_embed_url($url));
}
/**
* Test for core_media_renderer embed_url.
* Checks multiple format/fallback support.
*/
public function test_embed_url_fallbacks() {
global $CFG, $PAGE;
$url = new moodle_url('http://example.org/test.mp4');
// All plugins disabled, NOLINK option.
$renderer = new core_media_renderer_test($PAGE, '');
$t = $renderer->embed_url($url, 0, 0, '',
array(core_media::OPTION_NO_LINK => true));
// Completely empty.
$this->assertSame('', $t);
// All plugins disabled but not NOLINK.
$renderer = new core_media_renderer_test($PAGE, '');
$t = $renderer->embed_url($url);
$this->assert_contents(false, false, true, $t);
// HTML5 plugin enabled.
$CFG->core_media_enable_html5video = true;
$renderer = new core_media_renderer_test($PAGE, '');
$t = $renderer->embed_url($url);
$this->assert_contents(false, true, true, $t);
// QT plugin enabled as well.
$CFG->core_media_enable_qt = true;
$renderer = new core_media_renderer_test($PAGE, '');
$t = $renderer->embed_url($url);
$this->assert_contents(true, true, true, $t);
// Nolink turned off, plugins still enabled.
$t = $renderer->embed_url($url, 0, 0, '',
array(core_media::OPTION_NO_LINK => true));
$this->assert_contents(true, true, false, $t);
}
/**
* Checks the contents of the resulting HTML code to ensure it used the
* correct embed method(s).
*
* @param bool $hasqt True if it should have QT embed code
* @param bool $hashtml5 True if it should have HTML5 embed code
* @param bool $haslink True if it should have a fallback link
* @param string $text HTML content
*/
private function assert_contents($hasqt, $hashtml5, $haslink, $text) {
// I tried to avoid making it specific to the exact details of the html
// code, picking out only single key strings that would let it check
// whether final code contains the right things.
$qt = 'qtplugin.cab';
$html5 = '</video>';
$link = 'mediafallbacklink';
if ($hasqt) {
$this->assertContains($qt, $text);
} else {
$this->assertNotContains($qt, $text);
}
if ($hashtml5) {
$this->assertContains($html5, $text);
} else {
$this->assertNotContains($html5, $text);
}
if ($haslink) {
$this->assertContains($link, $text);
} else {
$this->assertNotContains($link, $text);
}
}
/**
* Test for core_media_renderer embed_url.
* Check SWF works including the special option required to enable it
*/
public function test_embed_url_swf() {
global $CFG, $PAGE;
$CFG->core_media_enable_swf = true;
$renderer = new core_media_renderer_test($PAGE, '');
// Without any options...
$url = new moodle_url('http://example.org/test.swf');
$t = $renderer->embed_url($url);
$this->assertNotContains('</object>', $t);
// ...and with the 'no it's safe, I checked it' option.
$url = new moodle_url('http://example.org/test.swf');
$t = $renderer->embed_url($url, '', 0, 0, array(core_media::OPTION_TRUSTED => true));
$this->assertContains('</object>', $t);
}
/**
* Test for core_media_renderer embed_url.
* Exercises all the basic formats not covered elsewhere.
*/
public function test_embed_url_other_formats() {
global $CFG, $PAGE;
// Enable all players and get renderer.
$CFG->core_media_enable_html5audio = true;
$CFG->core_media_enable_mp3 = true;
$CFG->core_media_enable_flv = true;
$CFG->core_media_enable_wmp = true;
$CFG->core_media_enable_rm = true;
$CFG->core_media_enable_youtube = true;
$CFG->core_media_enable_vimeo = true;
$renderer = new core_media_renderer_test($PAGE, '');
// Check each format one at a time. This is a basic check to be sure
// the HTML is included for files of the right type, not a test that
// the HTML itself is correct.
// Format: mp3.
$url = new moodle_url('http://example.org/test.mp3');
$t = $renderer->embed_url($url);
$this->assertContains('core_media_mp3_', $t);
// Format: flv.
$url = new moodle_url('http://example.org/test.flv');
$t = $renderer->embed_url($url);
$this->assertContains('core_media_flv_', $t);
// Format: wmp.
$url = new moodle_url('http://example.org/test.avi');
$t = $renderer->embed_url($url);
$this->assertContains('6BF52A52-394A-11d3-B153-00C04F79FAA6', $t);
// Format: rm.
$url = new moodle_url('http://example.org/test.rm');
$t = $renderer->embed_url($url);
$this->assertContains('CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA', $t);
// Format: youtube.
$url = new moodle_url('http://www.youtube.com/watch?v=vyrwMmsufJc');
$t = $renderer->embed_url($url);
$this->assertContains('</iframe>', $t);
$url = new moodle_url('http://www.youtube.com/v/vyrwMmsufJc');
$t = $renderer->embed_url($url);
$this->assertContains('</iframe>', $t);
// Format: youtube video within playlist.
$url = new moodle_url('https://www.youtube.com/watch?v=dv2f_xfmbD8&index=4&list=PLxcO_MFWQBDcyn9xpbmx601YSDlDcTcr0');
$t = $renderer->embed_url($url);
$this->assertContains('</iframe>', $t);
$this->assertContains('list=PLxcO_MFWQBDcyn9xpbmx601YSDlDcTcr0', $t);
// Format: youtube video with start time.
$url = new moodle_url('https://www.youtube.com/watch?v=JNJMF1l3udM&t=1h11s');
$t = $renderer->embed_url($url);
$this->assertContains('</iframe>', $t);
$this->assertContains('start=3611', $t);
// Format: youtube video within playlist with start time.
$url = new moodle_url('https://www.youtube.com/watch?v=dv2f_xfmbD8&index=4&list=PLxcO_MFWQBDcyn9xpbmx601YSDlDcTcr0&t=1m5s');
$t = $renderer->embed_url($url);
$this->assertContains('</iframe>', $t);
$this->assertContains('list=PLxcO_MFWQBDcyn9xpbmx601YSDlDcTcr0', $t);
$this->assertContains('start=65', $t);
// Format: youtube video with invalid parameter values (injection attempts).
$url = new moodle_url('https://www.youtube.com/watch?v=dv2f_xfmbD8&index=4&list=PLxcO_">');
$t = $renderer->embed_url($url);
$this->assertContains('</iframe>', $t);
$this->assertNotContains('list=PLxcO_', $t); // We shouldn't get a list param as input was invalid.
$url = new moodle_url('https://www.youtube.com/watch?v=JNJMF1l3udM&t=">');
$t = $renderer->embed_url($url);
$this->assertContains('</iframe>', $t);
$this->assertNotContains('start=', $t); // We shouldn't get a start param as input was invalid.
// Format: youtube playlist.
$url = new moodle_url('http://www.youtube.com/view_play_list?p=PL6E18E2927047B662');
$t = $renderer->embed_url($url);
$this->assertContains('</iframe>', $t);
$url = new moodle_url('http://www.youtube.com/playlist?list=PL6E18E2927047B662');
$t = $renderer->embed_url($url);
$this->assertContains('</iframe>', $t);
$url = new moodle_url('http://www.youtube.com/p/PL6E18E2927047B662');
$t = $renderer->embed_url($url);
$this->assertContains('</iframe>', $t);
// Format: vimeo.
$url = new moodle_url('http://vimeo.com/1176321');
$t = $renderer->embed_url($url);
$this->assertContains('</iframe>', $t);
// Format: html5audio.
$this->pretend_to_be_firefox();
$url = new moodle_url('http://example.org/test.ogg');
$t = $renderer->embed_url($url);
$this->assertContains('</audio>', $t);
}
/**
* Same as test_embed_url MP3 test, but for slash arguments.
*/
public function test_slash_arguments() {
global $CFG, $PAGE;
// Again we do not turn slasharguments actually on, because it has to
// work regardless of the setting of that variable in case of handling
// links created using previous setting.
// Enable MP3 and get renderer.
$CFG->core_media_enable_mp3 = true;
$renderer = new core_media_renderer_test($PAGE, '');
// Format: mp3.
$url = new moodle_url('http://example.org/pluginfile.php?file=x/y/z/test.mp3');
$t = $renderer->embed_url($url);
$this->assertContains('core_media_mp3_', $t);
}
/**
* Test for core_media_renderer embed_url.
* Checks the EMBED_OR_BLANK option.
*/
public function test_embed_or_blank() {
global $CFG, $PAGE;
$CFG->core_media_enable_html5audio = true;
$this->pretend_to_be_firefox();
$renderer = new core_media_renderer_test($PAGE, '');
$options = array(core_media::OPTION_FALLBACK_TO_BLANK => true);
// Embed that does match something should still include the link too.
$url = new moodle_url('http://example.org/test.ogg');
$t = $renderer->embed_url($url, '', 0, 0, $options);
$this->assertContains('</audio>', $t);
$this->assertContains('mediafallbacklink', $t);
// Embed that doesn't match something should be totally blank.
$url = new moodle_url('http://example.org/test.mp4');
$t = $renderer->embed_url($url, '', 0, 0, $options);
$this->assertSame('', $t);
}
/**
* Test for core_media_renderer embed_url.
* Checks that size is passed through correctly to player objects and tests
* size support in html5video output.
*/
public function test_embed_url_size() {
global $CFG, $PAGE;
// Technically this could break in every format and they handle size
// in several different ways, but I'm too lazy to test it in every
// format, so let's just pick one to check the values get passed
// through.
$CFG->core_media_enable_html5video = true;
$renderer = new core_media_renderer_test($PAGE, '');
$url = new moodle_url('http://example.org/test.mp4');
// HTML5 default size - specifies core width and does not specify height.
$t = $renderer->embed_url($url);
$this->assertContains('width="' . CORE_MEDIA_VIDEO_WIDTH . '"', $t);
$this->assertNotContains('height', $t);
// HTML5 specified size - specifies both.
$t = $renderer->embed_url($url, '', '666', '101');
$this->assertContains('width="666"', $t);
$this->assertContains('height="101"', $t);
// HTML5 size specified in url, overrides call.
$url = new moodle_url('http://example.org/test.mp4?d=123x456');
$t = $renderer->embed_url($url, '', '666', '101');
$this->assertContains('width="123"', $t);
$this->assertContains('height="456"', $t);
}
/**
* Test for core_media_renderer embed_url.
* Checks that name is passed through correctly to player objects and tests
* name support in html5video output.
*/
public function test_embed_url_name() {
global $CFG, $PAGE;
// As for size this could break in every format but I'm only testing
// html5video.
$CFG->core_media_enable_html5video = true;
$renderer = new core_media_renderer_test($PAGE, '');
$url = new moodle_url('http://example.org/test.mp4');
// HTML5 default name - use filename.
$t = $renderer->embed_url($url);
$this->assertContains('title="test.mp4"', $t);
// HTML5 specified name - check escaping.
$t = $renderer->embed_url($url, 'frog & toad');
$this->assertContains('title="frog & toad"', $t);
}
/**
* Test for core_media_renderer split_alternatives.
*/
public function test_split_alternatives() {
// Single URL - identical moodle_url.
$mp4 = 'http://example.org/test.mp4';
$result = core_media::split_alternatives($mp4, $w, $h);
$this->assertEquals($mp4, $result[0]->out(false));
// Width and height weren't specified.
$this->assertEquals(0, $w);
$this->assertEquals(0, $h);
// Two URLs - identical moodle_urls.
$webm = 'http://example.org/test.webm';
$result = core_media::split_alternatives("$mp4#$webm", $w, $h);
$this->assertEquals($mp4, $result[0]->out(false));
$this->assertEquals($webm, $result[1]->out(false));
// Two URLs plus dimensions.
$size = 'd=400x280';
$result = core_media::split_alternatives("$mp4#$webm#$size", $w, $h);
$this->assertEquals($mp4, $result[0]->out(false));
$this->assertEquals($webm, $result[1]->out(false));
$this->assertEquals(400, $w);
$this->assertEquals(280, $h);
// Two URLs plus legacy dimensions (use last one).
$result = core_media::split_alternatives("$mp4?d=1x1#$webm?$size", $w, $h);
$this->assertEquals($mp4, $result[0]->out(false));
$this->assertEquals($webm, $result[1]->out(false));
$this->assertEquals(400, $w);
$this->assertEquals(280, $h);
}
/**
* Test for core_media_renderer embed_alternatives (with multiple urls)
*/
public function test_embed_alternatives() {
global $PAGE, $CFG;
// Most aspects of this are same as single player so let's just try
// a single typical / complicated scenario.
// MP3, WebM and FLV.
$urls = array(
new moodle_url('http://example.org/test.mp4'),
new moodle_url('http://example.org/test.webm'),
new moodle_url('http://example.org/test.flv'),
);
// Enable html5 and flv.
$CFG->core_media_enable_html5video = true;
$CFG->core_media_enable_flv = true;
$renderer = new core_media_renderer_test($PAGE, '');
// Result should contain HTML5 with two sources + FLV.
$t = $renderer->embed_alternatives($urls);
// HTML5 sources - mp4, not flv or webm (not supported in Safari).
$this->assertContains('<source src="http://example.org/test.mp4"', $t);
$this->assertNotContains('<source src="http://example.org/test.webm"', $t);
$this->assertNotContains('<source src="http://example.org/test.flv"', $t);
// FLV is before the video tag (indicating html5 is used as fallback to flv
// and not vice versa).
$this->assertTrue((bool)preg_match('~core_media_flv_.*<video~s', $t));
// Do same test with firefox and check we get the webm and not mp4.
$this->pretend_to_be_firefox();
$t = $renderer->embed_alternatives($urls);
// HTML5 sources - webm, not not flv or mp4 (not supported in Firefox).
$this->assertNotContains('<source src="http://example.org/test.mp4"', $t);
$this->assertContains('<source src="http://example.org/test.webm"', $t);
$this->assertNotContains('<source src="http://example.org/test.flv"', $t);
}
/**
* Converts moodle_url array into a single comma-separated string for
* easier testing.
*
* @param array $urls Array of moodle_urls
* @return string String containing those URLs, comma-separated
*/
public static function string_urls($urls) {
$out = array();
foreach ($urls as $url) {
$out[] = $url->out(false);
}
return implode(',', $out);
}
/**
* Converts associative array into a semicolon-separated string for easier
* testing.
*
* @param array $options Associative array
* @return string String of form 'a=b;c=d'
*/
public static function string_options($options) {
$out = '';
foreach ($options as $key => $value) {
if ($out) {
$out .= ';';
}
$out .= "$key=$value";
}
return $out;
}
}
/**
* Media player stub for testing purposes.
*/
class core_media_player_test extends core_media_player {
/** @var array Array of supported extensions */
public $ext;
/** @var int Player rank */
public $rank;
/** @var int Arbitrary number */
public $num;
/**
* @param int $num Number (used in output)
* @param int $rank Player rank
* @param array $ext Array of supported extensions
*/
public function __construct($num = 1, $rank = 13, $ext = array('tst', 'test')) {
$this->ext = $ext;
$this->rank = $rank;
$this->num = $num;
}
public function embed($urls, $name, $width, $height, $options) {
return $this->num . ':' . medialib_test::string_urls($urls) .
",$name,$width,$height,<!--FALLBACK-->," . medialib_test::string_options($options);
}
public function get_supported_extensions() {
return $this->ext;
}
public function get_rank() {
return $this->rank;
}
}
/**
* Media renderer override for testing purposes.
*/
class core_media_renderer_test extends core_media_renderer {
/**
* Access list of players as string, shortening it by getting rid of
* repeated text.
* @return string Comma-separated list of players
*/
public function get_players_test() {
$players = $this->get_players();
$out = '';
foreach ($players as $player) {
if ($out) {
$out .= ', ';
}
$out .= str_replace('core_media_player_', '', get_class($player));
}
return $out;
}
}
| {
"content_hash": "66c5579b594c18206a04be5e27aa35ec",
"timestamp": "",
"source": "github",
"line_count": 664,
"max_line_length": 132,
"avg_line_length": 37.93825301204819,
"alnum_prop": 0.5846532491762931,
"repo_name": "pyros2097/moodle-integration",
"id": "ed19db7d8313967a2d8110ca7e170ab3901a147c",
"size": "25412",
"binary": false,
"copies": "70",
"ref": "refs/heads/master",
"path": "lib/tests/medialib_test.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "1205"
},
{
"name": "CSS",
"bytes": "1251303"
},
{
"name": "Gherkin",
"bytes": "1443400"
},
{
"name": "HTML",
"bytes": "421219"
},
{
"name": "Java",
"bytes": "14870"
},
{
"name": "JavaScript",
"bytes": "12239037"
},
{
"name": "PHP",
"bytes": "66782853"
},
{
"name": "PLSQL",
"bytes": "4867"
},
{
"name": "Perl",
"bytes": "20769"
},
{
"name": "XSLT",
"bytes": "33489"
}
],
"symlink_target": ""
} |
Storage is a first class object in Project6. Most other orchestration systems
are focused on using the storage that is already provisioned. Instead, Project6
pools storage from disks of all nodes in the cluster. It is meant for bare
metal on premises deployment. To try this outside of the vagrant setup, please
contact us at project6@datawise.io.
Volumes are scheduled to a node based on storage requirement and the available
storage capacity on that node.
#Types of volumes
There are two types of volumes - persistent and temporary.
Persistent volumes are explicitly created using ```dwctl volume create```. They
are named and scheduled to a node. A pod wanting to use a persistent volume needs
to refer to the volume at the time of creation.
Temporary volumes are tied to the lifecycle of the pod and dont need to managed
by the user.
##Persistent volume creation
```
$ dwctl volume create wp-vol -v vol1,1G,ext4
GROUP VOLUME SIZE FSTYPE HOST LABELS STATUS CREATED
wp-vol vol1 1G ext4 <none> Pending Less than a second
$ dwctl volume list
GROUP VOLUME SIZE FSTYPE HOST LABELS STATUS CREATED
wp-vol vol1 1G ext4 192.168.30.11 <none> Available 24 seconds
```
Multiple volumes can be created together on a node by using the -v option multiple
times. The aggregate storage capacity of all these volumes is used to schedule the
volume group. Once the volume is scheduled and created, it transitions to Available
status. If there is no storage available, the volume remains in Pending state.
Volumes can be scheduled to different nodes using the same labels and conflicts
concept as pods. This is useful for deploying clustered apps like zookeeper &
cassandra.
##Using a persistent volume
```
dwctl pod create mysql -i docker.io/mysql:latest \
-v wp-vol/vol1:/var/lib/mysql,rw -e MYSQL_ROOT_PASSWORD=root
```
As of now, this pod can only be scheduled to a node where its persistent volume is
scheduled. If for some reason, the persistent volume is not scheduled, the pod
remains in pending state until the persistent volume is scheduled.
##Using a temporary volume
When a pod needs temporary storage, it can use a temporary volume. Storage capacity
also becomes a scheduling criterion for selecting a node for this pod.
```
dwctl pod create wordpress -i docker.io/wordpress:4.2.2 \
-v /var/www/html,rw,100M,ext4 \
-e WORDPRESS_DB_HOST=172.16.1.106,WORDPRESS_DB_USER=root,WORDPRESS_DB_PASSWORD=root
```
In the above example, a 100M volume is created with ext4 filesystem and is mounted
at /var/www/html in read-write mode inside the container.
| {
"content_hash": "852c9b4d45b3c74b4444a5efe0dc330c",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 88,
"avg_line_length": 43.16129032258065,
"alnum_prop": 0.7507473841554559,
"repo_name": "DatawiseIO/Project6",
"id": "22470f28d793576e7d4e3d423554dff85e9093db",
"size": "2686",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/volumes.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ruby",
"bytes": "4133"
},
{
"name": "Shell",
"bytes": "1701"
}
],
"symlink_target": ""
} |
using System;
namespace SharpKit.Html.svg
{
using SharpKit.JavaScript;
using SharpKit.Html.fileapi;
using SharpKit.Html.html.shadow;
using SharpKit.Html.html.track;
using SharpKit.Html.inspector;
using SharpKit.Html.loader.appcache;
using SharpKit.Html.battery;
using SharpKit.Html.filesystem;
using SharpKit.Html.gamepad;
using SharpKit.Html.geolocation;
using SharpKit.Html.indexeddb;
using SharpKit.Html.intents;
using SharpKit.Html.mediasource;
using SharpKit.Html.mediastream;
using SharpKit.Html.navigatorcontentutils;
using SharpKit.Html.networkinfo;
using SharpKit.Html.notifications;
using SharpKit.Html.proximity;
using SharpKit.Html.quota;
using SharpKit.Html.speech;
using SharpKit.Html.vibration;
using SharpKit.Html.webaudio;
using SharpKit.Html.webdatabase;
using SharpKit.Html.plugins;
using SharpKit.Html.storage;
using SharpKit.Html.svg;
using SharpKit.Html.workers;
[JsType(JsMode.Prototype, Export = false, PropertiesAsFields = true, NativeCasts = true, Name = "SVGNumber")]
public partial class SvgNumber
{
public double value {get; set; }
}
} | {
"content_hash": "125ad6dd9b21aea362720e0028191f3a",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 109,
"avg_line_length": 24.953488372093023,
"alnum_prop": 0.8117427772600186,
"repo_name": "SharpKit/SharpKit-SDK",
"id": "9d0541e7146823200f4a190d656ea2fb2d5e915e",
"size": "3046",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Defs/Html/generated/svg/SVGNumber.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "950"
},
{
"name": "C#",
"bytes": "40434040"
},
{
"name": "CSS",
"bytes": "4836"
},
{
"name": "HTML",
"bytes": "421828"
},
{
"name": "JavaScript",
"bytes": "1598163"
},
{
"name": "Makefile",
"bytes": "190"
},
{
"name": "Shell",
"bytes": "292"
},
{
"name": "TypeScript",
"bytes": "145694"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
namespace Sakura.AspNetCore.Mvc
{
/// <summary>
/// Control the generation process for a single pager item.
/// </summary>
public class PagerItemOptions
{
/// <summary>
/// Get or set a generator that used to generate the content of the pager item.
/// </summary>
public IPagerItemContentGenerator Content { get; set; }
/// <summary>
/// Get or set a generator that used to generate the link of the pager item.
/// </summary>
public IPagerItemLinkGenerator Link { get; set; }
/// <summary>
/// Get or set the behavior for special pager items (non-standard number items) when it is in active. This property is
/// not used for number items.
/// </summary>
public SpecialPagerItemInactiveBehavior? InactiveBehavior { get; set; }
/// <summary>
/// Get or set the active mode for the first and last button. This property is only used for first and last items.
/// </summary>
public FirstAndLastPagerItemActiveMode? ActiveMode { get; set; }
/// <summary>
/// Get or set additional information for the pager item.
/// </summary>
public IDictionary<string, string> AdditionalSettings { get; private set; } = new Dictionary<string, string>();
/// <summary>
/// Create a clone for the current object.
/// </summary>
/// <returns>A clone for current object.</returns>
public PagerItemOptions Clone()
{
// Base clone
var result = (PagerItemOptions) MemberwiseClone();
// Deep clone
result.AdditionalSettings = new Dictionary<string, string>(AdditionalSettings);
return result;
}
/// <summary>
/// Merge a <see cref="PagerItemOptions" /> into another base instace.
/// </summary>
/// <param name="baseOptions">The base instance to be merged.</param>
/// <param name="additionalOptions">
/// The additional instance, in which the non-null values will merge into the base
/// instance.
/// </param>
/// <returns>A new <see cref="PagerItemOptions" /> to represent as the merging result.</returns>
/// <remarks>This method will not change either <paramref name="baseOptions" /> or <paramref name="additionalOptions" />.</remarks>
[Pure]
[NotNull]
public static PagerItemOptions Merge([CanBeNull] PagerItemOptions baseOptions,
[CanBeNull] PagerItemOptions additionalOptions)
{
// If base options is not null, use its clone as base; otherwise, use a new empty item as base.
var result = baseOptions?.Clone() ?? new PagerItemOptions();
// Return base item if no additional options are
if (additionalOptions == null)
return result;
// Merge attributes
result.Content = additionalOptions.Content ?? result.Content;
result.Link = additionalOptions.Link ?? result.Link;
result.ActiveMode = additionalOptions.ActiveMode ?? result.ActiveMode;
result.InactiveBehavior = additionalOptions.InactiveBehavior ?? result.InactiveBehavior;
// Merge settings
foreach (var i in additionalOptions.AdditionalSettings)
result.AdditionalSettings[i.Key] = i.Value;
return result;
}
/// <summary>
/// Merge all <see cref="PagerItemOptions" /> and get a final result.
/// </summary>
/// <param name="options">
/// A collection of all pager item options to be merged.The items at the leader will be merged
/// earlier.
/// </param>
/// <returns>The final merged result.</returns>
[NotNull]
public static PagerItemOptions MergeAll([ItemCanBeNull] params PagerItemOptions[] options)
{
return MergeAll((IEnumerable<PagerItemOptions>) options);
}
/// <summary>
/// Merge all <see cref="PagerItemOptions" /> and get a final result.
/// </summary>
/// <param name="options">
/// A collection of all pager item options to be merged.The items at the leader will be merged
/// earlier.
/// </param>
/// <returns>The final merged result.</returns>
[NotNull]
public static PagerItemOptions MergeAll([ItemCanBeNull] IEnumerable<PagerItemOptions> options)
{
return options.Aggregate(new PagerItemOptions(), Merge);
}
}
} | {
"content_hash": "7afd4642422740348b13d0f196d5d39d",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 133,
"avg_line_length": 35.982608695652175,
"alnum_prop": 0.6884968583856935,
"repo_name": "sgjsakura/AspNetCore",
"id": "a550b41dfcf5daf4c5f9ed88edb1d5374912f861",
"size": "4140",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Sakura.AspNetCore.Extensions/Sakura.AspNetCore.Mvc.PagedList/PagerItemOptions.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "922147"
}
],
"symlink_target": ""
} |
"""
sentry.conf.server
~~~~~~~~~~~~~~~~~~
These settings act as the default (base) settings for the Sentry-provided web-server
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from django.conf.global_settings import * # NOQA
from datetime import timedelta
import hashlib
import os
import os.path
import socket
import sys
import tempfile
import urlparse
import sentry
gettext_noop = lambda s: s
socket.setdefaulttimeout(5)
DEBUG = False
TEMPLATE_DEBUG = True
MAINTENANCE = False
ADMINS = ()
INTERNAL_IPS = ('127.0.0.1',)
MANAGERS = ADMINS
APPEND_SLASH = True
PROJECT_ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir))
NODE_MODULES_ROOT = os.path.join(PROJECT_ROOT, os.pardir, os.pardir, 'node_modules')
sys.path.insert(0, os.path.normpath(os.path.join(PROJECT_ROOT, os.pardir)))
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'sentry.db',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
'AUTOCOMMIT': True,
'ATOMIC_REQUESTS': False,
}
}
if 'DATABASE_URL' in os.environ:
url = urlparse.urlparse(os.environ['DATABASE_URL'])
# Ensure default database exists.
DATABASES['default'] = DATABASES.get('default', {})
# Update with environment configuration.
DATABASES['default'].update({
'NAME': url.path[1:],
'USER': url.username,
'PASSWORD': url.password,
'HOST': url.hostname,
'PORT': url.port,
})
if url.scheme == 'postgres':
DATABASES['default']['ENGINE'] = 'sentry.db.postgres'
if url.scheme == 'mysql':
DATABASES['default']['ENGINE'] = 'django.db.backends.mysql'
EMAIL_SUBJECT_PREFIX = '[Sentry] '
# This should always be UTC.
TIME_ZONE = 'UTC'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
LANGUAGES = (
('af', gettext_noop('Afrikaans')),
('ar', gettext_noop('Arabic')),
('az', gettext_noop('Azerbaijani')),
('bg', gettext_noop('Bulgarian')),
('be', gettext_noop('Belarusian')),
('bn', gettext_noop('Bengali')),
('br', gettext_noop('Breton')),
('bs', gettext_noop('Bosnian')),
('ca', gettext_noop('Catalan')),
('cs', gettext_noop('Czech')),
('cy', gettext_noop('Welsh')),
('da', gettext_noop('Danish')),
('de', gettext_noop('German')),
('el', gettext_noop('Greek')),
('en', gettext_noop('English')),
('eo', gettext_noop('Esperanto')),
('es', gettext_noop('Spanish')),
('et', gettext_noop('Estonian')),
('eu', gettext_noop('Basque')),
('fa', gettext_noop('Persian')),
('fi', gettext_noop('Finnish')),
('fr', gettext_noop('French')),
('ga', gettext_noop('Irish')),
('gl', gettext_noop('Galician')),
('he', gettext_noop('Hebrew')),
('hi', gettext_noop('Hindi')),
('hr', gettext_noop('Croatian')),
('hu', gettext_noop('Hungarian')),
('ia', gettext_noop('Interlingua')),
('id', gettext_noop('Indonesian')),
('is', gettext_noop('Icelandic')),
('it', gettext_noop('Italian')),
('ja', gettext_noop('Japanese')),
('ka', gettext_noop('Georgian')),
('kk', gettext_noop('Kazakh')),
('km', gettext_noop('Khmer')),
('kn', gettext_noop('Kannada')),
('ko', gettext_noop('Korean')),
('lb', gettext_noop('Luxembourgish')),
('lt', gettext_noop('Lithuanian')),
('lv', gettext_noop('Latvian')),
('mk', gettext_noop('Macedonian')),
('ml', gettext_noop('Malayalam')),
('mn', gettext_noop('Mongolian')),
('my', gettext_noop('Burmese')),
('nb', gettext_noop('Norwegian Bokmal')),
('ne', gettext_noop('Nepali')),
('nl', gettext_noop('Dutch')),
('nn', gettext_noop('Norwegian Nynorsk')),
('os', gettext_noop('Ossetic')),
('pa', gettext_noop('Punjabi')),
('pl', gettext_noop('Polish')),
('pt', gettext_noop('Portuguese')),
('pt-br', gettext_noop('Brazilian Portuguese')),
('ro', gettext_noop('Romanian')),
('ru', gettext_noop('Russian')),
('sk', gettext_noop('Slovak')),
('sl', gettext_noop('Slovenian')),
('sq', gettext_noop('Albanian')),
('sr', gettext_noop('Serbian')),
('sv-se', gettext_noop('Swedish')),
('sw', gettext_noop('Swahili')),
('ta', gettext_noop('Tamil')),
('te', gettext_noop('Telugu')),
('th', gettext_noop('Thai')),
('tr', gettext_noop('Turkish')),
('tt', gettext_noop('Tatar')),
('udm', gettext_noop('Udmurt')),
('uk', gettext_noop('Ukrainian')),
('ur', gettext_noop('Urdu')),
('vi', gettext_noop('Vietnamese')),
('zh-cn', gettext_noop('Simplified Chinese')),
('zh-cn', gettext_noop('Traditional Chinese')),
)
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
USE_TZ = True
# Make this unique, and don't share it with anybody.
SECRET_KEY = hashlib.md5(socket.gethostname() + ')*)&8a36)6%74e@-ne5(-!8a(vv#tkv)(eyg&@0=zd^pl!7=y@').hexdigest()
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
MIDDLEWARE_CLASSES = (
'sentry.middleware.maintenance.ServicesUnavailableMiddleware',
'sentry.middleware.env.SentryEnvMiddleware',
'sentry.middleware.proxy.SetRemoteAddrFromForwardedFor',
'sentry.middleware.debug.NoIfModifiedSinceMiddleware',
'sentry.middleware.stats.RequestTimingMiddleware',
'sentry.middleware.stats.ResponseCodeMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'sentry.middleware.auth.AuthenticationMiddleware',
'sentry.middleware.sudo.SudoMiddleware',
'sentry.middleware.locale.SentryLocaleMiddleware',
'sentry.middleware.social_auth.SentrySocialAuthExceptionMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'sentry.debug.middleware.DebugMiddleware',
)
ROOT_URLCONF = 'sentry.conf.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(PROJECT_ROOT, 'templates'),
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.core.context_processors.csrf',
'social_auth.context_processors.social_auth_by_name_backends',
'social_auth.context_processors.social_auth_backends',
'social_auth.context_processors.social_auth_by_type_backends',
'social_auth.context_processors.social_auth_login_redirect'
)
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.messages',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.staticfiles',
'captcha',
'crispy_forms',
'debug_toolbar',
'gunicorn',
'kombu.transport.django',
'raven.contrib.django.raven_compat',
'rest_framework',
'sentry',
'sentry.nodestore',
'sentry.search',
'sentry.lang.javascript',
'sentry.plugins.sentry_interface_types',
'sentry.plugins.sentry_mail',
'sentry.plugins.sentry_urls',
'sentry.plugins.sentry_useragents',
'sentry.plugins.sentry_webhooks',
'social_auth',
'south',
'sudo',
)
STATIC_ROOT = os.path.realpath(os.path.join(PROJECT_ROOT, 'static'))
STATIC_URL = '/_static/'
STATICFILES_FINDERS = (
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
)
ASSET_VERSION = 0
# setup a default media root to somewhere useless
MEDIA_ROOT = '/tmp/sentry-media'
LOCALE_PATHS = (
os.path.join(PROJECT_ROOT, 'locale'),
)
CSRF_FAILURE_VIEW = 'sentry.web.frontend.csrf_failure.view'
CSRF_COOKIE_NAME = 'csrf'
# Auth configuration
try:
from django.core.urlresolvers import reverse_lazy
except ImportError:
LOGIN_REDIRECT_URL = '/login-redirect/'
LOGIN_URL = '/auth/login/'
else:
LOGIN_REDIRECT_URL = reverse_lazy('sentry-login-redirect')
LOGIN_URL = reverse_lazy('sentry-login')
AUTHENTICATION_BACKENDS = (
'social_auth.backends.twitter.TwitterBackend',
'social_auth.backends.facebook.FacebookBackend',
# TODO: migrate to GoogleOAuth2Backend
'social_auth.backends.google.GoogleBackend',
'social_auth.backends.contrib.github.GithubBackend',
'social_auth.backends.contrib.bitbucket.BitbucketBackend',
'social_auth.backends.contrib.trello.TrelloBackend',
'sentry.utils.auth.EmailAuthBackend',
)
SOCIAL_AUTH_USER_MODEL = AUTH_USER_MODEL = 'sentry.User'
SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies"
SESSION_COOKIE_NAME = "sentrysid"
SESSION_SERIALIZER = "django.contrib.sessions.serializers.PickleSerializer"
TWITTER_CONSUMER_KEY = ''
TWITTER_CONSUMER_SECRET = ''
FACEBOOK_APP_ID = ''
FACEBOOK_API_SECRET = ''
FACEBOOK_EXTENDED_PERMISSIONS = ['email']
GOOGLE_OAUTH2_CLIENT_ID = ''
GOOGLE_OAUTH2_CLIENT_SECRET = ''
GITHUB_APP_ID = ''
GITHUB_API_SECRET = ''
TRELLO_API_KEY = ''
TRELLO_API_SECRET = ''
BITBUCKET_CONSUMER_KEY = ''
BITBUCKET_CONSUMER_SECRET = ''
MAILGUN_API_KEY = ''
SOCIAL_AUTH_PIPELINE = (
'social_auth.backends.pipeline.user.get_username',
'social_auth.backends.pipeline.social.social_auth_user',
'social_auth.backends.pipeline.associate.associate_by_email',
'social_auth.backends.pipeline.misc.save_status_to_session',
'social_auth.backends.pipeline.social.associate_user',
'social_auth.backends.pipeline.social.load_extra_data',
'social_auth.backends.pipeline.user.update_user_details',
'social_auth.backends.pipeline.misc.save_status_to_session',
)
INITIAL_CUSTOM_USER_MIGRATION = '0108_fix_user'
# Auth engines and the settings required for them to be listed
AUTH_PROVIDERS = {
'github': ('GITHUB_APP_ID', 'GITHUB_API_SECRET'),
'trello': ('TRELLO_API_KEY', 'TRELLO_API_SECRET'),
'bitbucket': ('BITBUCKET_CONSUMER_KEY', 'BITBUCKET_CONSUMER_SECRET'),
}
import random
SOCIAL_AUTH_DEFAULT_USERNAME = lambda: random.choice(['Darth Vader', 'Obi-Wan Kenobi', 'R2-D2', 'C-3PO', 'Yoda'])
SOCIAL_AUTH_PROTECTED_USER_FIELDS = ['email']
# Queue configuration
from kombu import Exchange, Queue
BROKER_URL = "django://"
BROKER_TRANSPORT_OPTIONS = {}
CELERY_ALWAYS_EAGER = True
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
CELERY_IGNORE_RESULT = True
CELERY_SEND_EVENTS = False
CELERY_RESULT_BACKEND = None
CELERY_TASK_RESULT_EXPIRES = 1
CELERY_DISABLE_RATE_LIMITS = True
CELERY_DEFAULT_QUEUE = "default"
CELERY_DEFAULT_EXCHANGE = "default"
CELERY_DEFAULT_EXCHANGE_TYPE = "direct"
CELERY_DEFAULT_ROUTING_KEY = "default"
CELERY_CREATE_MISSING_QUEUES = True
CELERY_IMPORTS = (
'sentry.tasks.beacon',
'sentry.tasks.check_auth',
'sentry.tasks.deletion',
'sentry.tasks.email',
'sentry.tasks.index',
'sentry.tasks.merge',
'sentry.tasks.store',
'sentry.tasks.options',
'sentry.tasks.ping',
'sentry.tasks.post_process',
'sentry.tasks.process_buffer',
'sentry.tasks.sync_docs',
)
CELERY_QUEUES = [
Queue('default', routing_key='default'),
Queue('alerts', routing_key='alerts'),
Queue('auth', routing_key='auth'),
Queue('cleanup', routing_key='cleanup'),
Queue('search', routing_key='search'),
Queue('events', routing_key='events'),
Queue('update', routing_key='update'),
Queue('email', routing_key='email'),
Queue('options', routing_key='options'),
]
CELERY_ROUTES = ('sentry.queue.routers.SplitQueueRouter',)
def create_partitioned_queues(name):
exchange = Exchange(name, type='direct')
for num in range(1):
CELERY_QUEUES.append(Queue(
'{0}-{1}'.format(name, num),
exchange=exchange,
))
create_partitioned_queues('counters')
create_partitioned_queues('triggers')
CELERYBEAT_SCHEDULE_FILENAME = os.path.join(tempfile.gettempdir(), 'sentry-celerybeat')
CELERYBEAT_SCHEDULE = {
'check-auth': {
'task': 'sentry.tasks.check_auth',
'schedule': timedelta(minutes=1),
'options': {
'expires': 60,
'queue': 'auth',
}
},
'send-beacon': {
'task': 'sentry.tasks.send_beacon',
'schedule': timedelta(hours=1),
'options': {
'expires': 3600,
},
},
'send-ping': {
'task': 'sentry.tasks.send_ping',
'schedule': timedelta(minutes=1),
'options': {
'expires': 60,
},
},
'flush-buffers': {
'task': 'sentry.tasks.process_buffer.process_pending',
'schedule': timedelta(seconds=10),
'options': {
'expires': 10,
'queue': 'counters-0',
}
},
'sync-docs': {
'task': 'sentry.tasks.sync_docs',
'schedule': timedelta(seconds=3600),
'options': {
'expires': 3600,
'queue': 'update',
}
},
'sync-options': {
'task': 'sentry.tasks.options.sync_options',
'schedule': timedelta(seconds=10),
'options': {
'expires': 10,
'queue': 'options',
}
},
}
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'handlers': {
'console': {
'level': 'WARNING',
'class': 'logging.StreamHandler',
'formatter': 'simple',
},
'sentry': {
'level': 'ERROR',
'filters': ['sentry:internal'],
'class': 'raven.contrib.django.handlers.SentryHandler',
},
'audit': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'simple',
},
'console:api': {
'level': 'WARNING',
'class': 'logging.StreamHandler',
'formatter': 'client_info',
},
},
'filters': {
'sentry:internal': {
'()': 'sentry.utils.raven.SentryInternalFilter',
},
},
'formatters': {
'simple': {
'format': '[%(levelname)s] %(message)s',
},
'client_info': {
'format': '[%(levelname)s] [%(project)s] [%(agent)s] %(message)s',
},
},
'root': {
'handlers': ['console', 'sentry'],
},
'loggers': {
'sentry': {
'level': 'ERROR',
},
'sentry.api': {
'handlers': ['console:api', 'sentry'],
'propagate': False,
},
'sentry.deletions': {
'handlers': ['audit'],
},
'sentry.errors': {
'handlers': ['console'],
'propagate': False,
},
'sentry.rules': {
'handlers': ['console'],
'propagate': False,
},
'static_compiler': {
'level': 'INFO',
},
'django.request': {
'level': 'ERROR',
'handlers': ['console'],
'propagate': False,
},
'toronado.cssutils': {
'level': 'ERROR',
'propagate': False,
},
}
}
# django-rest-framework
REST_FRAMEWORK = {
'TEST_REQUEST_DEFAULT_FORMAT': 'json',
'DEFAULT_PERMISSION_CLASSES': (
'sentry.api.permissions.NoPermission',
)
}
CRISPY_TEMPLATE_PACK = 'bootstrap3'
# django-recaptcha
RECAPTCHA_PUBLIC_KEY = None
RECAPTCHA_PRIVATE_KEY = None
NOCAPTCHA = True
CAPTCHA_WIDGET_TEMPLATE = "sentry/partial/form_captcha.html"
# Debugger
DEBUG_TOOLBAR_PANELS = (
'debug_toolbar.panels.timer.TimerPanel',
'sentry.debug.panels.route.RoutePanel',
'debug_toolbar.panels.templates.TemplatesPanel',
'debug_toolbar.panels.sql.SQLPanel',
# TODO(dcramer): https://github.com/getsentry/sentry/issues/1722
# 'sentry.debug.panels.redis.RedisPanel',
)
DEBUG_TOOLBAR_PATCH_SETTINGS = False
# Sentry and Raven configuration
SENTRY_CLIENT = 'sentry.utils.raven.SentryInternalClient'
SENTRY_FEATURES = {
'auth:register': True,
'organizations:create': True,
'organizations:sso': True,
'projects:quotas': True,
'projects:user-reports': True,
'projects:plugins': True,
}
# Default time zone for localization in the UI.
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
SENTRY_DEFAULT_TIME_ZONE = 'UTC'
# Enable the Sentry Debugger (Beta)
SENTRY_DEBUGGER = False
SENTRY_IGNORE_EXCEPTIONS = (
'OperationalError',
)
# Absolute URL to the sentry root directory. Should not include a trailing slash.
SENTRY_URL_PREFIX = ''
# Should we send the beacon to the upstream server?
SENTRY_BEACON = True
# The administrative contact for this installation
SENTRY_ADMIN_EMAIL = ''
# Allow access to Sentry without authentication.
SENTRY_PUBLIC = False
# Instruct Sentry that this install intends to be run by a single organization
# and thus various UI optimizations should be enabled.
SENTRY_SINGLE_ORGANIZATION = False
# Login url (defaults to LOGIN_URL)
SENTRY_LOGIN_URL = None
# Default project ID (for internal errors)
SENTRY_PROJECT = 1
# Project ID for recording frontend (javascript) exceptions
SENTRY_FRONTEND_PROJECT = None
# Only store a portion of all messages per unique group.
SENTRY_SAMPLE_DATA = True
# The following values control the sampling rates
SENTRY_SAMPLE_RATES = (
# up until N events, store 1 in M
(50, 1),
(1000, 2),
(10000, 10),
(100000, 50),
(1000000, 300),
(10000000, 2000),
)
SENTRY_MAX_SAMPLE_RATE = 10000
SENTRY_SAMPLE_TIMES = (
(3600, 1),
(360, 10),
(60, 60),
)
SENTRY_MAX_SAMPLE_TIME = 10000
# Web Service
SENTRY_WEB_HOST = 'localhost'
SENTRY_WEB_PORT = 9000
SENTRY_WEB_OPTIONS = {}
# SMTP Service
SENTRY_ENABLE_EMAIL_REPLIES = False
SENTRY_SMTP_HOSTNAME = 'localhost'
SENTRY_SMTP_HOST = 'localhost'
SENTRY_SMTP_PORT = 1025
SENTRY_INTERFACES = {
'exception': 'sentry.interfaces.exception.Exception',
'logentry': 'sentry.interfaces.message.Message',
'request': 'sentry.interfaces.http.Http',
'stacktrace': 'sentry.interfaces.stacktrace.Stacktrace',
'template': 'sentry.interfaces.template.Template',
'query': 'sentry.interfaces.query.Query',
'user': 'sentry.interfaces.user.User',
'csp': 'sentry.interfaces.csp.Csp',
'sentry.interfaces.Exception': 'sentry.interfaces.exception.Exception',
'sentry.interfaces.Message': 'sentry.interfaces.message.Message',
'sentry.interfaces.Stacktrace': 'sentry.interfaces.stacktrace.Stacktrace',
'sentry.interfaces.Template': 'sentry.interfaces.template.Template',
'sentry.interfaces.Query': 'sentry.interfaces.query.Query',
'sentry.interfaces.Http': 'sentry.interfaces.http.Http',
'sentry.interfaces.User': 'sentry.interfaces.user.User',
'sentry.interfaces.Csp': 'sentry.interfaces.csp.Csp',
}
# Should users without superuser permissions be allowed to
# make projects public
SENTRY_ALLOW_PUBLIC_PROJECTS = True
# Can users be invited to organizations?
SENTRY_ENABLE_INVITES = True
# Default to not sending the Access-Control-Allow-Origin header on api/store
SENTRY_ALLOW_ORIGIN = None
# Enable scraping of javascript context for source code
SENTRY_SCRAPE_JAVASCRIPT_CONTEXT = True
# Redis connection information (see Nydus documentation)
SENTRY_REDIS_OPTIONS = {}
# Buffer backend
SENTRY_BUFFER = 'sentry.buffer.Buffer'
SENTRY_BUFFER_OPTIONS = {}
# Cache backend
# XXX: We explicitly require the cache to be configured as its not optional
# and causes serious confusion with the default django cache
SENTRY_CACHE = None
SENTRY_CACHE_OPTIONS = {}
# The internal Django cache is still used in many places
# TODO(dcramer): convert uses over to Sentry's backend
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
# The cache version affects both Django's internal cache (at runtime) as well
# as Sentry's cache. This automatically overrides VERSION on the default
# CACHES backend.
CACHE_VERSION = 1
# Quota backend
SENTRY_QUOTAS = 'sentry.quotas.Quota'
SENTRY_QUOTA_OPTIONS = {}
# Rate limiting backend
SENTRY_RATELIMITER = 'sentry.ratelimits.base.RateLimiter'
SENTRY_RATELIMITER_OPTIONS = {}
# The default value for project-level quotas
SENTRY_DEFAULT_MAX_EVENTS_PER_MINUTE = '90%'
# The maximum number of events per minute the system should accept.
SENTRY_SYSTEM_MAX_EVENTS_PER_MINUTE = 0
# Node storage backend
SENTRY_NODESTORE = 'sentry.nodestore.django.DjangoNodeStorage'
SENTRY_NODESTORE_OPTIONS = {}
# Search backend
SENTRY_SEARCH = 'sentry.search.django.DjangoSearchBackend'
SENTRY_SEARCH_OPTIONS = {}
# SENTRY_SEARCH_OPTIONS = {
# 'urls': ['http://localhost:9200/'],
# 'timeout': 5,
# }
# Time-series storage backend
SENTRY_TSDB = 'sentry.tsdb.dummy.DummyTSDB'
SENTRY_TSDB_OPTIONS = {}
# rollups must be ordered from highest granularity to lowest
SENTRY_TSDB_ROLLUPS = (
# (time in seconds, samples to keep)
(10, 360), # 60 minutes at 10 seconds
(3600, 24 * 7), # 7 days at 1 hour
(3600 * 24, 60), # 60 days at 1 day
)
# File storage
SENTRY_FILESTORE = 'django.core.files.storage.FileSystemStorage'
SENTRY_FILESTORE_OPTIONS = {'location': '/tmp/sentry-files'}
# Internal metrics
SENTRY_METRICS_BACKEND = 'sentry.metrics.dummy.DummyMetricsBackend'
SENTRY_METRICS_OPTIONS = {}
SENTRY_METRICS_SAMPLE_RATE = 1.0
SENTRY_METRICS_PREFIX = 'sentry.'
# URL to embed in js documentation
SENTRY_RAVEN_JS_URL = 'cdn.ravenjs.com/1.1.20/jquery,native/raven.min.js'
# URI Prefixes for generating DSN URLs
# (Defaults to URL_PREFIX by default)
SENTRY_ENDPOINT = None
SENTRY_PUBLIC_ENDPOINT = None
# Prevent variables (e.g. context locals, http data, etc) from exceeding this
# size in characters
SENTRY_MAX_VARIABLE_SIZE = 512
# Prevent variables within extra context from exceeding this size in
# characters
SENTRY_MAX_EXTRA_VARIABLE_SIZE = 4096
# For changing the amount of data seen in Http Response Body part.
SENTRY_MAX_HTTP_BODY_SIZE = 4096 * 4 # 16kb
# For various attributes we don't limit the entire attribute on size, but the
# individual item. In those cases we also want to limit the maximum number of
# keys
SENTRY_MAX_DICTIONARY_ITEMS = 50
SENTRY_MAX_MESSAGE_LENGTH = 1024 * 8
SENTRY_MAX_STACKTRACE_FRAMES = 25
SENTRY_MAX_EXCEPTIONS = 25
# Gravatar service base url
SENTRY_GRAVATAR_BASE_URL = 'https://secure.gravatar.com'
# Timeout (in seconds) for fetching remote source files (e.g. JS)
SENTRY_SOURCE_FETCH_TIMEOUT = 5
# http://en.wikipedia.org/wiki/Reserved_IP_addresses
SENTRY_DISALLOWED_IPS = (
'0.0.0.0/8',
'10.0.0.0/8',
'100.64.0.0/10',
'127.0.0.0/8',
'169.254.0.0/16',
'172.16.0.0/12',
'192.0.0.0/29',
'192.0.2.0/24',
'192.88.99.0/24',
'192.168.0.0/16',
'198.18.0.0/15',
'198.51.100.0/24',
'224.0.0.0/4',
'240.0.0.0/4',
'255.255.255.255/32',
)
# Fields which managed users cannot change via Sentry UI. Username and password
# cannot be changed by managed users. Optionally include 'email' and
# 'first_name' in SENTRY_MANAGED_USER_FIELDS.
SENTRY_MANAGED_USER_FIELDS = ('email',)
# See sentry/options/__init__.py for more information
SENTRY_OPTIONS = {}
# You should not change this setting after your database has been created
# unless you have altered all schemas first
SENTRY_USE_BIG_INTS = False
# Delay (in ms) to induce on API responses
SENTRY_API_RESPONSE_DELAY = 0
# Watchers for various application purposes (such as compiling static media)
SENTRY_WATCHERS = (
[os.path.join(NODE_MODULES_ROOT, '.bin', 'webpack'), '-d', '--watch',
"--config={}".format(os.path.join(PROJECT_ROOT, os.pardir, os.pardir, "webpack.config.js"))],
)
def get_raven_config():
return {
'release': sentry.__build__,
'register_signals': True,
'include_paths': [
'sentry',
],
}
RAVEN_CONFIG = get_raven_config()
| {
"content_hash": "7abf6141d1d1618de90b1770df689a48",
"timestamp": "",
"source": "github",
"line_count": 838,
"max_line_length": 113,
"avg_line_length": 29.011933174224342,
"alnum_prop": 0.6535867061533399,
"repo_name": "BayanGroup/sentry",
"id": "38ac7714a33cdc3573f545c04aa08f71552c789c",
"size": "24312",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/sentry/conf/server.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "156607"
},
{
"name": "HTML",
"bytes": "188852"
},
{
"name": "JavaScript",
"bytes": "443758"
},
{
"name": "Makefile",
"bytes": "4647"
},
{
"name": "Python",
"bytes": "7069971"
}
],
"symlink_target": ""
} |
package de.simu.decomap.config.gui.loads;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.simu.decomap.config.gui.values.ConfigSettings;
import de.simu.decomap.config.gui.values.PropertyFileSettings;
/**
* Loading all kinds of properties-files for different modes
*
* @author Leonid Schwenke, DECOIT GmbH
*
*/
public class LoadModePropertyFiles {
public Properties prop;
public FileInputStream in;
private ArrayList<String> values = new ArrayList<String>();
private final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* Constructor
*
* @param propertiesPath
* path to the properties which should be loaded
*/
public LoadModePropertyFiles(final String propertiesPath) {
try {
logger.info("Start loading file from: "+propertiesPath);
prop = new Properties();
in = new FileInputStream(propertiesPath);
prop.load(in);
ConfigSettings.LOADEDPATH = propertiesPath;
in.close();
} catch (IOException e) {
logger.error("Error while loading file!", e);
// returning false on load
}
}
/**
*
* Loading the properties and setting the values
*
* @param mode
* mode settings to load
* @param propertieFile
* propertieFile settings to load
* @param dataArray
* Reference data
* @return
* Successful?
*/
public boolean load(final String mode, final String propertieFile,
final ArrayList<String[]> dataArray) {
try {
String[] data;
for (int i = 0; i < dataArray.size(); i++) {
data = dataArray.get(i)[2].split("=", 2);
values.add(dataArray.get(i)[0]+";"+dataArray.get(i)[1]+";"+data[0] + "=" + prop.getProperty(data[0], data[1]).replace("\\", "\\\\"));
}
PropertyFileSettings.PROPERTIESINFOS.get(mode).put(propertieFile, values);
} catch (Exception e) {
logger.error("Error while loading file "+propertieFile+"!", e);
return false;
}
logger.info("Loading successful!");
return true;
}
}
| {
"content_hash": "689770cf9d96f7c50d22d58f0e593cfa",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 137,
"avg_line_length": 26.53846153846154,
"alnum_prop": 0.6893719806763285,
"repo_name": "decoit/decomap-config-gui",
"id": "1229c9cf39450f83a76ec1a6fde11e7a8cba7280",
"size": "2666",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/de/simu/decomap/config/gui/loads/LoadModePropertyFiles.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "183460"
}
],
"symlink_target": ""
} |
<?php
namespace Cms\Http;
use Numencode\Models\Task;
class TaskController extends BaseController
{
/**
* Display a listing of the tasks.
*
* @return \Illuminate\View\View
*/
public function index()
{
$tasks = Task::latest()->get();
return view('theme::tasks.list', compact('tasks'));
}
/**
* Display a random task.
*
* @return \Illuminate\View\View
*/
public function random()
{
$task = Task::inRandomOrder()->first();
return view('theme::tasks.show', compact('task'));
}
/**
* Display a specific task.
*
* @param object $params Data parameters
*
* @return \Illuminate\View\View
*/
public function show($params)
{
return view('theme::tasks.show', [
'data' => $params,
'task' => Task::find($params->task_id),
]);
}
}
| {
"content_hash": "f38d18e0bd6335c7f851c1a3e5aab734",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 59,
"avg_line_length": 19.425531914893618,
"alnum_prop": 0.5290251916757941,
"repo_name": "BlazOrazem/numencode",
"id": "ce499042326d574992d89ece04be6a0e7a1a47ea",
"size": "913",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/Cms/Http/TaskController.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "19041"
},
{
"name": "HTML",
"bytes": "404175"
},
{
"name": "PHP",
"bytes": "414927"
},
{
"name": "Vue",
"bytes": "552"
}
],
"symlink_target": ""
} |
var app= angular.module('MonApp', ['ngRoute']);
app.config(function($routeProvider){
$routeProvider
.when('/', {templateUrl: 'partials/filieres.html', controller: 'FilieresCtrl'})
//.when('/comments/:id', {templateUrl: 'partials/comments.html', controller: 'CommentsCtrl'})
.when('/filiere/:id', {templateUrl: 'partials/exercices.html', controller: 'ExercicesCtrl'})
.when('/exercices/:id/contenu/:id_exo', {templateUrl: 'partials/contenu.html', controller: 'ExercicesContentCtrl'})
.otherwise({redirectTo: '/'});
}); | {
"content_hash": "7f5fcab912aa562a9f33007252a16a1e",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 127,
"avg_line_length": 66,
"alnum_prop": 0.6279461279461279,
"repo_name": "brookkk/brainss",
"id": "02c4e60ebbd1ea804ea34c229ac334db981bdb87",
"size": "594",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "front/js/app.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2362"
},
{
"name": "HTML",
"bytes": "68834"
},
{
"name": "JavaScript",
"bytes": "46701"
},
{
"name": "PHP",
"bytes": "239524"
},
{
"name": "Shell",
"bytes": "15321"
}
],
"symlink_target": ""
} |
"""Utility to retrieve function args."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import os
import time
from tensorflow.python.platform import gfile
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util import compat
from tensorflow.python.util import tf_decorator
from tensorflow.python.util import tf_inspect
def _is_bounded_method(fn):
_, fn = tf_decorator.unwrap(fn)
return tf_inspect.ismethod(fn) and (fn.__self__ is not None)
def _is_callable_object(obj):
return hasattr(obj, '__call__') and tf_inspect.ismethod(obj.__call__)
def fn_args(fn):
"""Get argument names for function-like object.
Args:
fn: Function, or function-like object (e.g., result of `functools.partial`).
Returns:
`tuple` of string argument names.
Raises:
ValueError: if partial function has positionally bound arguments
"""
if isinstance(fn, functools.partial):
args = fn_args(fn.func)
args = [a for a in args[len(fn.args):] if a not in (fn.keywords or [])]
else:
if _is_callable_object(fn):
fn = fn.__call__
args = tf_inspect.getfullargspec(fn).args
if _is_bounded_method(fn):
args.remove('self')
return tuple(args)
# When we create a timestamped directory, there is a small chance that the
# directory already exists because another process is also creating these
# directories. In this case we just wait one second to get a new timestamp and
# try again. If this fails several times in a row, then something is seriously
# wrong.
MAX_DIRECTORY_CREATION_ATTEMPTS = 10
def get_timestamped_dir(dir_base):
"""Builds a path to a new subdirectory within the base directory.
The subdirectory will be named using the current time.
This guarantees monotonically increasing directory numbers even across
multiple runs of the pipeline.
The timestamp used is the number of seconds since epoch UTC.
Args:
dir_base: A string containing a directory to create the subdirectory under.
Returns:
The full path of the new subdirectory (which is not actually created yet).
Raises:
RuntimeError: if repeated attempts fail to obtain a unique timestamped
directory name.
"""
attempts = 0
while attempts < MAX_DIRECTORY_CREATION_ATTEMPTS:
timestamp = int(time.time())
result_dir = os.path.join(
compat.as_bytes(dir_base), compat.as_bytes(str(timestamp)))
if not gfile.Exists(result_dir):
# Collisions are still possible (though extremely unlikely): this
# directory is not actually created yet, but it will be almost
# instantly on return from this function.
return result_dir
time.sleep(1)
attempts += 1
logging.warn('Directory {} already exists; retrying (attempt {}/{})'.format(
result_dir, attempts, MAX_DIRECTORY_CREATION_ATTEMPTS))
raise RuntimeError('Failed to obtain a unique export directory name after '
'{} attempts.'.format(MAX_DIRECTORY_CREATION_ATTEMPTS))
| {
"content_hash": "463fd66b846bc1f17c3debd2479aca24",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 80,
"avg_line_length": 32.88172043010753,
"alnum_prop": 0.7164813603662524,
"repo_name": "allenlavoie/tensorflow",
"id": "bb4bdd3fdfb2e19dbc1c581d7771f2e1ac4442ba",
"size": "3748",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "tensorflow/python/estimator/util.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "9274"
},
{
"name": "C",
"bytes": "340645"
},
{
"name": "C++",
"bytes": "40746519"
},
{
"name": "CMake",
"bytes": "198073"
},
{
"name": "Go",
"bytes": "1047216"
},
{
"name": "HTML",
"bytes": "4680032"
},
{
"name": "Java",
"bytes": "735737"
},
{
"name": "Jupyter Notebook",
"bytes": "2117270"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "Makefile",
"bytes": "48231"
},
{
"name": "Objective-C",
"bytes": "12456"
},
{
"name": "Objective-C++",
"bytes": "94385"
},
{
"name": "PHP",
"bytes": "2140"
},
{
"name": "Perl",
"bytes": "6179"
},
{
"name": "Perl 6",
"bytes": "1357"
},
{
"name": "PureBasic",
"bytes": "25356"
},
{
"name": "Python",
"bytes": "34933340"
},
{
"name": "Ruby",
"bytes": "533"
},
{
"name": "Shell",
"bytes": "426884"
},
{
"name": "Smarty",
"bytes": "6870"
}
],
"symlink_target": ""
} |
Additional header content
Specifies the orientation of labels on the axis.
**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#
[SerializableAttribute]
public enum KnownLabelOrientation
```
**VB**<br />
``` VB
<SerializableAttribute>
Public Enumeration KnownLabelOrientation
```
## Members
<table><tr><th></th><th>Member name</th><th>Value</th><th>Description</th></tr><tr><td /><td target="F:iTin.Export.Model.KnownLabelOrientation.Automatic">**Automatic**</td><td>0</td><td>The orientation is automatic.</td></tr><tr><td /><td target="F:iTin.Export.Model.KnownLabelOrientation.Downward">**Downward**</td><td>1</td><td>The orientation is downward.</td></tr><tr><td /><td target="F:iTin.Export.Model.KnownLabelOrientation.Horizontal">**Horizontal**</td><td>2</td><td>The orientation is horizontal.</td></tr><tr><td /><td target="F:iTin.Export.Model.KnownLabelOrientation.Upward">**Upward**</td><td>3</td><td>The orientation is upward.</td></tr><tr><td /><td target="F:iTin.Export.Model.KnownLabelOrientation.Vertical">**Vertical**</td><td>4</td><td>The orientation is vertical.</td></tr></table>
## Remarks
\[Missing <remarks> documentation for "T:iTin.Export.Model.KnownLabelOrientation"\]
## See Also
#### Reference
<a href="N_iTin_Export_Model">iTin.Export.Model Namespace</a><br /> | {
"content_hash": "734f2cc1472e6012a68ce140cbb2ba57",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 811,
"avg_line_length": 45.1875,
"alnum_prop": 0.7053941908713693,
"repo_name": "iAJTin/iExportEngine",
"id": "910bf7ddca1fceddee6248ccce9203dd7783a9e0",
"size": "1482",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/documentation/iTin.Export.Documentation/Documentation/T_iTin_Export_Model_KnownLabelOrientation.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2298"
},
{
"name": "C#",
"bytes": "2815693"
},
{
"name": "Smalltalk",
"bytes": "7632"
},
{
"name": "XSLT",
"bytes": "14099"
}
],
"symlink_target": ""
} |
An introduction to RooFit
| {
"content_hash": "1b6c25055e8861f09bab0318a846368f",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 25,
"avg_line_length": 26,
"alnum_prop": 0.8461538461538461,
"repo_name": "betatim/roofit-tutorial",
"id": "b03de849b76fa21a2421a8d5c1d0d7fd69286e7c",
"size": "44",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
name TEXT NOT NULL,
hair_color TEXT,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
| {
"content_hash": "ebfce961881932dd6f4460a3287bc8ca",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 85,
"avg_line_length": 35.857142857142854,
"alnum_prop": 0.7808764940239044,
"repo_name": "sgrif/diesel",
"id": "4194890fe37ae93deffc4171f129a4944909f9fe",
"size": "251",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "examples/mysql/all_about_inserts/migrations/2017-12-16-173626_create_users/up.sql",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PLpgSQL",
"bytes": "567"
},
{
"name": "Rust",
"bytes": "489162"
},
{
"name": "Shell",
"bytes": "733"
}
],
"symlink_target": ""
} |
<?php
namespace Hamcrest\Text;
class StringEndsWithTest extends \Hamcrest\AbstractMatcherTest
{
const EXCERPT = 'EXCERPT';
private $_stringEndsWith;
public function setUp()
{
$this->_stringEndsWith = \Hamcrest\Text\StringEndsWith::endsWith(self::EXCERPT);
}
protected function createMatcher()
{
return $this->_stringEndsWith;
}
public function testEvaluatesToTrueIfArgumentContainsSpecifiedSubstring()
{
$this->assertFalse(
$this->_stringEndsWith->matches(self::EXCERPT . 'END'),
'should be false if excerpt at beginning'
);
$this->assertTrue(
$this->_stringEndsWith->matches('START' . self::EXCERPT),
'should be true if excerpt at end'
);
$this->assertFalse(
$this->_stringEndsWith->matches('START' . self::EXCERPT . 'END'),
'should be false if excerpt in middle'
);
$this->assertTrue(
$this->_stringEndsWith->matches(self::EXCERPT . self::EXCERPT),
'should be true if excerpt is at end and repeated'
);
$this->assertFalse(
$this->_stringEndsWith->matches('Something else'),
'should be false if excerpt is not in string'
);
$this->assertFalse(
$this->_stringEndsWith->matches(substr(self::EXCERPT, 0, strlen(self::EXCERPT) - 2)),
'should be false if part of excerpt is at end of string'
);
}
public function testEvaluatesToTrueIfArgumentIsEqualToSubstring()
{
$this->assertTrue(
$this->_stringEndsWith->matches(self::EXCERPT),
'should be true if excerpt is entire string'
);
}
public function testHasAReadableDescription()
{
$this->assertDescription('a string ending with "EXCERPT"', $this->_stringEndsWith);
}
}
| {
"content_hash": "65390c8a114b3b17c1a57c92c8ef826f",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 97,
"avg_line_length": 31.56451612903226,
"alnum_prop": 0.5825242718446602,
"repo_name": "focuslife/v0.1",
"id": "49a61557cbb80f4a24c4e2de9807988a64a3d4f2",
"size": "1957",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/hamcrest/hamcrest-php/tests/Hamcrest/Text/StringEndsWithTest.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "428"
},
{
"name": "CSS",
"bytes": "72"
},
{
"name": "JavaScript",
"bytes": "519"
},
{
"name": "PHP",
"bytes": "273407"
}
],
"symlink_target": ""
} |
<h2>Modifying existing JavaScript for RequireJS <small><?php echo $date; ?></small></h2>
<p>I recently organized all of my JavaScript code into RequireJS
modules and have some notes on why it's worth it to make the necessary changes
in order to get it set up correctly. While you do have to wrap every file in a <code>define()</code>
function, a solid directory structure probably won't need to be modified (mine didn't), and dependency management
is much easier. For me, the change actually slightly reduced the number of lines of code and cleaned up the
global scope a bit.
<?php
echo "<a href='$details'>More</a>";
?>
</p>
| {
"content_hash": "5fadbae39b30cb83f446cae1d3b8e529",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 113,
"avg_line_length": 57.09090909090909,
"alnum_prop": 0.7515923566878981,
"repo_name": "aisthesis/codemelon-2014",
"id": "414dfdb44e9f97066bc65d3cee7ec765808a49f9",
"size": "628",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "content/blurbs/_2014051701.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "14297"
},
{
"name": "HTML",
"bytes": "366054"
},
{
"name": "JavaScript",
"bytes": "164133"
},
{
"name": "PHP",
"bytes": "89081"
}
],
"symlink_target": ""
} |
/usr/bin/psql "${DATABASE_URL/postgis/postgres}" -c 'CREATE EXTENSION IF NOT EXISTS postgis;'
/usr/bin/psql "${DATABASE_URL/postgis/postgres}" -c 'CREATE EXTENSION IF NOT EXISTS postgis_topology;'
| {
"content_hash": "6b4d6a98d887eb3a634d780311d21a09",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 102,
"avg_line_length": 98.5,
"alnum_prop": 0.751269035532995,
"repo_name": "ministryofjustice/laa-legal-adviser-api",
"id": "42f6bf08c893c7ede0b050189fa8ab0e6eecdf32",
"size": "218",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docker/setup_postgres.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "1100"
},
{
"name": "HTML",
"bytes": "6367"
},
{
"name": "Python",
"bytes": "85938"
},
{
"name": "Shell",
"bytes": "4624"
}
],
"symlink_target": ""
} |
//----------------------------------------------------------------------------
/** @file SpMinLibPlayer.h
Minimum liberty player - blocks with fewest liberties are most urgent.
*/
//----------------------------------------------------------------------------
#ifndef SP_MINLIBPLAYER_H
#define SP_MINLIBPLAYER_H
#include "SpSimplePlayer.h"
#include "SpMoveGenerator.h"
//----------------------------------------------------------------------------
/** Tries to maximize minimum liberty of own minus opponent blocks.
*/
class SpMinLibMoveGenerator
: public Sp1PlyMoveGenerator
{
public:
explicit SpMinLibMoveGenerator(GoBoard& board)
: Sp1PlyMoveGenerator(board)
{ }
virtual int Evaluate();
int LibertyMinimum(SgBlackWhite toplay);
};
//----------------------------------------------------------------------------
/** Simple player using SpMinLibMoveGenerator */
class SpMinLibPlayer
: public SpSimplePlayer
{
public:
SpMinLibPlayer(GoBoard& board)
: SpSimplePlayer(board, new SpMinLibMoveGenerator(board))
{ }
std::string Name() const
{
return "MinLib";
}
bool UseFilter() const
{
return true;
}
};
#endif
| {
"content_hash": "daddbc2a569bc3e2876e4ac6417436ca",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 78,
"avg_line_length": 22.51851851851852,
"alnum_prop": 0.5032894736842105,
"repo_name": "MisterTea/HyperNEAT",
"id": "d08980cddb0c6acfccfcc33b5d0603dff15ef751",
"size": "1216",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "fuego-0.4/simpleplayers/SpMinLibPlayer.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Ada",
"bytes": "91920"
},
{
"name": "Assembly",
"bytes": "324212"
},
{
"name": "Batchfile",
"bytes": "32748"
},
{
"name": "Bison",
"bytes": "10393"
},
{
"name": "C",
"bytes": "4172510"
},
{
"name": "C#",
"bytes": "97576"
},
{
"name": "C++",
"bytes": "163699928"
},
{
"name": "CLIPS",
"bytes": "7056"
},
{
"name": "CMake",
"bytes": "92433"
},
{
"name": "CSS",
"bytes": "248695"
},
{
"name": "Cuda",
"bytes": "26521"
},
{
"name": "DIGITAL Command Language",
"bytes": "13695"
},
{
"name": "Fortran",
"bytes": "1387"
},
{
"name": "Gnuplot",
"bytes": "2361"
},
{
"name": "Groff",
"bytes": "15745"
},
{
"name": "HTML",
"bytes": "145331688"
},
{
"name": "IDL",
"bytes": "15"
},
{
"name": "JFlex",
"bytes": "1290"
},
{
"name": "JavaScript",
"bytes": "134468"
},
{
"name": "Makefile",
"bytes": "1053202"
},
{
"name": "Max",
"bytes": "37424"
},
{
"name": "Module Management System",
"bytes": "1593"
},
{
"name": "Objective-C",
"bytes": "33988"
},
{
"name": "Objective-C++",
"bytes": "214"
},
{
"name": "PHP",
"bytes": "60249"
},
{
"name": "Pascal",
"bytes": "41721"
},
{
"name": "Perl",
"bytes": "30505"
},
{
"name": "Perl6",
"bytes": "2130"
},
{
"name": "PostScript",
"bytes": "81121"
},
{
"name": "Python",
"bytes": "1943687"
},
{
"name": "QML",
"bytes": "613"
},
{
"name": "QMake",
"bytes": "7148"
},
{
"name": "Rebol",
"bytes": "372"
},
{
"name": "SAS",
"bytes": "1776"
},
{
"name": "Scilab",
"bytes": "107733"
},
{
"name": "Shell",
"bytes": "394881"
},
{
"name": "Tcl",
"bytes": "29403"
},
{
"name": "TeX",
"bytes": "1196144"
},
{
"name": "XSLT",
"bytes": "770994"
}
],
"symlink_target": ""
} |
"""Classes and functions used to construct graphs."""
# pylint: disable=g-bad-name
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import copy
import os
import re
import sys
import threading
import numpy as np
import six
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorflow.core.framework import attr_value_pb2
from tensorflow.core.framework import function_pb2
from tensorflow.core.framework import graph_pb2
from tensorflow.core.framework import node_def_pb2
from tensorflow.core.framework import op_def_pb2
from tensorflow.core.framework import versions_pb2
from tensorflow.core.protobuf import config_pb2
from tensorflow.python import pywrap_tensorflow as c_api
from tensorflow.python.eager import context
from tensorflow.python.eager import core
from tensorflow.python.eager import tape
from tensorflow.python.framework import c_api_util
from tensorflow.python.framework import cpp_shape_inference_pb2
from tensorflow.python.framework import device as pydev
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import error_interpolation
from tensorflow.python.framework import errors
from tensorflow.python.framework import op_def_registry
from tensorflow.python.framework import registry
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import traceable_stack
from tensorflow.python.framework import versions
from tensorflow.python.ops import control_flow_util
from tensorflow.python.platform import app
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util import compat
from tensorflow.python.util import decorator_utils
from tensorflow.python.util import function_utils
from tensorflow.python.util import lock_util
from tensorflow.python.util import tf_contextlib
from tensorflow.python.util import tf_stack
from tensorflow.python.util.deprecation import deprecated_args
from tensorflow.python.util.tf_export import tf_export
# Temporary global switches determining if we should enable the work-in-progress
# calls to the C API. These will be removed once all functionality is supported.
_USE_C_API = True
_USE_C_SHAPES = os.getenv("TF_C_API_GRAPH_CONSTRUCTION_SHAPES", "1") != "0"
def tensor_id(tensor):
"""Returns a unique identifier for this Tensor."""
return tensor._id # pylint: disable=protected-access
class _UserDeviceSpec(object):
"""Store user-specified device and provide computation of merged device."""
def __init__(self, device_name_or_function):
self._device_name_or_function = device_name_or_function
self.display_name = str(self._device_name_or_function)
if callable(self._device_name_or_function):
dev_func = self._device_name_or_function
func_name = function_utils.get_func_name(dev_func)
func_code = function_utils.get_func_code(dev_func)
if func_code:
fname = func_code.co_filename
lineno = func_code.co_firstlineno
else:
fname = "unknown"
lineno = -1
self.display_name = "%s<%s, %d>" % (func_name, fname, lineno)
self.function = self._device_name_or_function
if not (self._device_name_or_function is None or
callable(self._device_name_or_function)):
self.function = pydev.merge_device(self._device_name_or_function)
class _NullContextmanager(object):
def __enter__(self):
pass
def __exit__(self, type_arg, value_arg, traceback_arg):
return False # False values do not suppress exceptions
def _override_helper(clazz_object, operator, func):
"""Overrides (string) operator on Tensors to call func.
Args:
clazz_object: the class to override for; either Tensor or SparseTensor.
operator: the string name of the operator to override.
func: the function that replaces the overridden operator.
Raises:
ValueError: If operator has already been overwritten,
or if operator is not allowed to be overwritten.
"""
existing = getattr(clazz_object, operator, None)
if existing is not None:
# Check to see if this is a default method-wrapper or slot wrapper which
# will be true for the comparison operators.
if not isinstance(existing, type(object.__lt__)):
raise ValueError("operator %s cannot be overwritten again on class %s." %
(operator, clazz_object))
if operator not in Tensor.OVERLOADABLE_OPERATORS:
raise ValueError("Overriding %s is disallowed" % operator)
setattr(clazz_object, operator, func)
def _as_graph_element(obj):
"""Convert `obj` to a graph element if possible, otherwise return `None`.
Args:
obj: Object to convert.
Returns:
The result of `obj._as_graph_element()` if that method is available;
otherwise `None`.
"""
conv_fn = getattr(obj, "_as_graph_element", None)
if conv_fn and callable(conv_fn):
return conv_fn()
return None
_TENSOR_LIKE_TYPES = tuple()
def is_dense_tensor_like(t):
"""EXPERIMENTAL: Returns true if `t` implements the tensor interface.
See `register_dense_tensor_like_type()` for the current definition of a
"tensor-like type".
Args:
t: An object.
Returns:
True iff `t` is an instance of one of the registered "tensor-like" types.
"""
return isinstance(t, _TENSOR_LIKE_TYPES)
def register_dense_tensor_like_type(tensor_type):
"""EXPERIMENTAL: Registers `tensor_type` as implementing the tensor interface.
A "tensor-like type" can represent a single dense tensor, and implements
the `name` and `dtype` properties.
Args:
tensor_type: A type implementing the tensor interface.
Raises:
TypeError: If `tensor_type` does not implement the tensor interface.
"""
try:
if not isinstance(tensor_type.name, property):
raise TypeError("Type %s does not define a `name` property" %
tensor_type.__name__)
except AttributeError:
raise TypeError("Type %s does not define a `name` property" %
tensor_type.__name__)
try:
if not isinstance(tensor_type.dtype, property):
raise TypeError("Type %s does not define a `dtype` property" %
tensor_type.__name__)
except AttributeError:
raise TypeError("Type %s does not define a `dtype` property" %
tensor_type.__name__)
# We expect this list to be small, so choose quadratic complexity
# for registration, so that we have a tuple that can be used for
# more efficient `isinstance` checks later.
global _TENSOR_LIKE_TYPES
_TENSOR_LIKE_TYPES = tuple(list(_TENSOR_LIKE_TYPES) + [tensor_type])
def uid():
"""A unique (within this program execution) integer."""
return c_api.TFE_Py_UID()
def numpy_text(tensor, is_repr=False):
"""Human readable representation of a tensor's numpy value."""
if tensor.dtype.is_numpy_compatible:
text = repr(tensor.numpy()) if is_repr else str(tensor.numpy())
else:
text = "<unprintable>"
if "\n" in text:
text = "\n" + text
return text
# NOTE(ebrevdo): Do not subclass this. If you do, I will break you on purpose.
class _TensorLike(object):
"""Internal cls for grouping Tensor, SparseTensor, ..., for is_instance."""
pass
@tf_export("Tensor")
class Tensor(_TensorLike):
"""Represents one of the outputs of an `Operation`.
A `Tensor` is a symbolic handle to one of the outputs of an
`Operation`. It does not hold the values of that operation's output,
but instead provides a means of computing those values in a
TensorFlow `tf.Session`.
This class has two primary purposes:
1. A `Tensor` can be passed as an input to another `Operation`.
This builds a dataflow connection between operations, which
enables TensorFlow to execute an entire `Graph` that represents a
large, multi-step computation.
2. After the graph has been launched in a session, the value of the
`Tensor` can be computed by passing it to
`tf.Session.run`.
`t.eval()` is a shortcut for calling
`tf.get_default_session().run(t)`.
In the following example, `c`, `d`, and `e` are symbolic `Tensor`
objects, whereas `result` is a numpy array that stores a concrete
value:
```python
# Build a dataflow graph.
c = tf.constant([[1.0, 2.0], [3.0, 4.0]])
d = tf.constant([[1.0, 1.0], [0.0, 1.0]])
e = tf.matmul(c, d)
# Construct a `Session` to execute the graph.
sess = tf.Session()
# Execute the graph and store the value that `e` represents in `result`.
result = sess.run(e)
```
"""
# List of Python operators that we allow to override.
OVERLOADABLE_OPERATORS = {
# Binary.
"__add__",
"__radd__",
"__sub__",
"__rsub__",
"__mul__",
"__rmul__",
"__div__",
"__rdiv__",
"__truediv__",
"__rtruediv__",
"__floordiv__",
"__rfloordiv__",
"__mod__",
"__rmod__",
"__lt__",
"__le__",
"__gt__",
"__ge__",
"__and__",
"__rand__",
"__or__",
"__ror__",
"__xor__",
"__rxor__",
"__getitem__",
"__pow__",
"__rpow__",
# Unary.
"__invert__",
"__neg__",
"__abs__",
"__matmul__",
"__rmatmul__"
}
def __init__(self, op, value_index, dtype):
"""Creates a new `Tensor`.
Args:
op: An `Operation`. `Operation` that computes this tensor.
value_index: An `int`. Index of the operation's endpoint that produces
this tensor.
dtype: A `DType`. Type of elements stored in this tensor.
Raises:
TypeError: If the op is not an `Operation`.
"""
if not isinstance(op, Operation):
raise TypeError("op needs to be an Operation: %s" % op)
self._op = op
self._value_index = value_index
self._dtype = dtypes.as_dtype(dtype)
# This will be set by self.shape().
self._shape_val = None
# List of operations that use this Tensor as input. We maintain this list
# to easily navigate a computation graph.
self._consumers = []
if not _USE_C_SHAPES:
# Attributes used for C++ shape inference. Not inspected, only forwarded.
# If set, will be a HandleData object from cpp_shape_inference.proto.
self._handle_data = None
self._id = uid()
@property
def op(self):
"""The `Operation` that produces this tensor as an output."""
return self._op
@property
def dtype(self):
"""The `DType` of elements in this tensor."""
return self._dtype
@property
def graph(self):
"""The `Graph` that contains this tensor."""
return self._op.graph
@property
def name(self):
"""The string name of this tensor."""
if not self._op.name:
raise ValueError("Operation was not named: %s" % self._op)
return "%s:%d" % (self._op.name, self._value_index)
@property
def device(self):
"""The name of the device on which this tensor will be produced, or None."""
return self._op.device
@property
def shape(self):
"""Returns the `TensorShape` that represents the shape of this tensor.
The shape is computed using shape inference functions that are
registered in the Op for each `Operation`. See
`tf.TensorShape`
for more details of what a shape represents.
The inferred shape of a tensor is used to provide shape
information without having to launch the graph in a session. This
can be used for debugging, and providing early error messages. For
example:
```python
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
print(c.shape)
==> TensorShape([Dimension(2), Dimension(3)])
d = tf.constant([[1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 1.0]])
print(d.shape)
==> TensorShape([Dimension(4), Dimension(2)])
# Raises a ValueError, because `c` and `d` do not have compatible
# inner dimensions.
e = tf.matmul(c, d)
f = tf.matmul(c, d, transpose_a=True, transpose_b=True)
print(f.shape)
==> TensorShape([Dimension(3), Dimension(4)])
```
In some cases, the inferred shape may have unknown dimensions. If
the caller has additional information about the values of these
dimensions, `Tensor.set_shape()` can be used to augment the
inferred shape.
Returns:
A `TensorShape` representing the shape of this tensor.
"""
if self._shape_val is None:
if _USE_C_SHAPES:
self._shape_val = self._c_api_shape()
else:
# Call set_shape_and_handle_data_for_outputs in topological order on all
# ops that are needed to compute self.op's shape. We do this instead of
# having set_shape_and_handle_data_for_outputs recursively call
# Operation.shape on self.op.inputs to overflowing the call stack.
need_shapes = self._get_input_ops_without_shapes(self.op)
need_shapes.sort(key=lambda op: op._id)
for op in need_shapes:
set_shape_and_handle_data_for_outputs(op)
return self._shape_val
def _get_input_ops_without_shapes(self, target_op):
"""Returns ops needing shape inference to compute target_op's shape."""
result = []
stack = [self._op]
visited = set()
while stack:
op = stack.pop()
if op in visited: continue
result.append(op)
stack.extend(t.op for t in op.inputs if t._shape_val is None)
visited.add(op)
return result
def _c_api_shape(self):
"""Returns the TensorShape of this tensor according to the C API."""
c_graph = self._op._graph._c_graph # pylint: disable=protected-access
shape_vector, unknown_shape = c_api.TF_GraphGetTensorShapeHelper(
c_graph, self._as_tf_output())
if unknown_shape:
return tensor_shape.unknown_shape()
else:
shape_vector = [None if d == -1 else d for d in shape_vector]
return tensor_shape.TensorShape(shape_vector)
@property
def _shape(self):
logging.warning("Tensor._shape is private, use Tensor.shape "
"instead. Tensor._shape will eventually be removed.")
return self.shape
@_shape.setter
def _shape(self, value):
raise ValueError(
"Tensor._shape cannot be assigned, use Tensor.set_shape instead.")
def __iter__(self):
if not context.executing_eagerly():
raise TypeError(
"Tensor objects are only iterable when eager execution is "
"enabled. To iterate over this tensor use tf.map_fn.")
shape = self._shape_tuple()
if shape is None:
raise TypeError("Cannot iterate over a tensor with unknown shape.")
if not shape:
raise TypeError("Cannot iterate over a scalar tensor.")
if shape[0] is None:
raise TypeError(
"Cannot iterate over a tensor with unknown first dimension.")
for i in xrange(shape[0]):
yield self[i]
def _shape_as_list(self):
if self.shape.ndims is not None:
return [dim.value for dim in self.shape.dims]
else:
return None
def _shape_tuple(self):
shape = self._shape_as_list()
if shape is None:
return None
return tuple(shape)
def _rank(self):
"""Integer rank of this Tensor, if known, else None.
Returns:
Integer rank or None
"""
return self.shape.ndims
def get_shape(self):
"""Alias of Tensor.shape."""
return self.shape
def set_shape(self, shape):
"""Updates the shape of this tensor.
This method can be called multiple times, and will merge the given
`shape` with the current shape of this tensor. It can be used to
provide additional information about the shape of this tensor that
cannot be inferred from the graph alone. For example, this can be used
to provide additional information about the shapes of images:
```python
_, image_data = tf.TFRecordReader(...).read(...)
image = tf.image.decode_png(image_data, channels=3)
# The height and width dimensions of `image` are data dependent, and
# cannot be computed without executing the op.
print(image.shape)
==> TensorShape([Dimension(None), Dimension(None), Dimension(3)])
# We know that each image in this dataset is 28 x 28 pixels.
image.set_shape([28, 28, 3])
print(image.shape)
==> TensorShape([Dimension(28), Dimension(28), Dimension(3)])
```
Args:
shape: A `TensorShape` representing the shape of this tensor, a
`TensorShapeProto`, a list, a tuple, or None.
Raises:
ValueError: If `shape` is not compatible with the current shape of
this tensor.
"""
if _USE_C_SHAPES: # pylint: disable=protected-access
# Reset cached shape.
self._shape_val = None
else:
self._shape_val = self.shape.merge_with(shape)
# Update C shape even if _USE_C_SHAPES = False, since we still want
# set_shape to be reflected in the C API graph for when we run it.
if not isinstance(shape, tensor_shape.TensorShape):
shape = tensor_shape.TensorShape(shape)
dim_list = []
if shape.dims is None:
unknown_shape = True
else:
unknown_shape = False
for dim in shape.dims:
if dim.value is None:
dim_list.append(-1)
else:
dim_list.append(dim.value)
try:
c_api.TF_GraphSetTensorShape_wrapper(
self._op._graph._c_graph, # pylint: disable=protected-access
self._as_tf_output(),
dim_list,
unknown_shape)
except errors.InvalidArgumentError as e:
# Convert to ValueError for backwards compatibility.
raise ValueError(str(e))
@property
def value_index(self):
"""The index of this tensor in the outputs of its `Operation`."""
return self._value_index
def consumers(self):
"""Returns a list of `Operation`s that consume this tensor.
Returns:
A list of `Operation`s.
"""
consumer_names = c_api.TF_OperationOutputConsumers_wrapper(
self._as_tf_output())
# pylint: disable=protected-access
return [
self.graph._get_operation_by_name_unsafe(name)
for name in consumer_names
]
# pylint: enable=protected-access
def _as_node_def_input(self):
"""Return a value to use for the NodeDef "input" attribute.
The returned string can be used in a NodeDef "input" attribute
to indicate that the NodeDef uses this Tensor as input.
Raises:
ValueError: if this Tensor's Operation does not have a name.
Returns:
a string.
"""
if not self._op.name:
raise ValueError("Operation was not named: %s" % self._op)
if self._value_index == 0:
return self._op.name
else:
return "%s:%d" % (self._op.name, self._value_index)
def _as_tf_output(self):
# pylint: disable=protected-access
return c_api_util.tf_output(self.op._c_op, self.value_index)
# pylint: enable=protected-access
def __str__(self):
return "Tensor(\"%s\"%s%s%s)" % (
self.name, (", shape=%s" % self.get_shape())
if self.get_shape().ndims is not None else "",
(", dtype=%s" % self._dtype.name)
if self._dtype else "", (", device=%s" % self.device)
if self.device else "")
def __repr__(self):
return "<tf.Tensor '%s' shape=%s dtype=%s>" % (self.name, self.get_shape(),
self._dtype.name)
def __hash__(self):
# Necessary to support Python's collection membership operators
return id(self)
def __eq__(self, other):
# Necessary to support Python's collection membership operators
return id(self) == id(other)
def __copy__(self):
# Make sure _shape_val is computed before we copy.
# TODO(b/77597810): get rid of Tensor copies.
if self._shape_val is None:
set_shape_and_handle_data_for_outputs(self.op)
cls = self.__class__
result = cls.__new__(cls)
result.__dict__.update(self.__dict__)
return result
# NOTE(mrry): This enables the Tensor's overloaded "right" binary
# operators to run when the left operand is an ndarray, because it
# accords the Tensor class higher priority than an ndarray, or a
# numpy matrix.
# TODO(mrry): Convert this to using numpy's __numpy_ufunc__
# mechanism, which allows more control over how Tensors interact
# with ndarrays.
__array_priority__ = 100
@staticmethod
def _override_operator(operator, func):
_override_helper(Tensor, operator, func)
def __bool__(self):
"""Dummy method to prevent a tensor from being used as a Python `bool`.
This overload raises a `TypeError` when the user inadvertently
treats a `Tensor` as a boolean (e.g. in an `if` statement). For
example:
```python
if tf.constant(True): # Will raise.
# ...
if tf.constant(5) < tf.constant(7): # Will raise.
# ...
```
This disallows ambiguities between testing the Python value vs testing the
dynamic condition of the `Tensor`.
Raises:
`TypeError`.
"""
raise TypeError("Using a `tf.Tensor` as a Python `bool` is not allowed. "
"Use `if t is not None:` instead of `if t:` to test if a "
"tensor is defined, and use TensorFlow ops such as "
"tf.cond to execute subgraphs conditioned on the value of "
"a tensor.")
def __nonzero__(self):
"""Dummy method to prevent a tensor from being used as a Python `bool`.
This is the Python 2.x counterpart to `__bool__()` above.
Raises:
`TypeError`.
"""
raise TypeError("Using a `tf.Tensor` as a Python `bool` is not allowed. "
"Use `if t is not None:` instead of `if t:` to test if a "
"tensor is defined, and use TensorFlow ops such as "
"tf.cond to execute subgraphs conditioned on the value of "
"a tensor.")
def eval(self, feed_dict=None, session=None):
"""Evaluates this tensor in a `Session`.
Calling this method will execute all preceding operations that
produce the inputs needed for the operation that produces this
tensor.
*N.B.* Before invoking `Tensor.eval()`, its graph must have been
launched in a session, and either a default session must be
available, or `session` must be specified explicitly.
Args:
feed_dict: A dictionary that maps `Tensor` objects to feed values.
See `tf.Session.run` for a
description of the valid feed values.
session: (Optional.) The `Session` to be used to evaluate this tensor. If
none, the default session will be used.
Returns:
A numpy array corresponding to the value of this tensor.
"""
return _eval_using_default_session(self, feed_dict, self.graph, session)
# TODO(agarwal): consider getting rid of this.
class _EagerTensorBase(Tensor):
"""Base class for EagerTensor."""
@property
def dtype(self):
# Note: using the intern table directly here as this is
# performance-sensitive in some models.
return dtypes._INTERN_TABLE[self._datatype_enum()] # pylint: disable=protected-access
def numpy(self):
"""Returns a numpy array or a scalar with the same contents as the Tensor.
TODO(ashankar,agarwal): Perhaps this should NOT reference the underlying
buffer but instead always explicitly copy? Note that currently it may or may
not copy based on whether the numpy data is properly aligned or not.
Returns:
A numpy array or a scalar. Numpy array may share memory with the
Tensor object. Any changes to one may be reflected in the other. A scalar
value is returned when self has rank 0.
Raises:
ValueError: if the type of this Tensor is not representable in numpy.
"""
if self.dtype == dtypes.resource:
raise ValueError("Resource handles are not convertible to numpy.")
return self._cpu_nograd()._numpy() # pylint: disable=protected-access
# __int__, __float__ and __index__ may copy the tensor to CPU and
# only work for scalars; values are cast as per numpy.
def __int__(self):
return int(self.numpy())
def __float__(self):
return float(self.numpy())
def __index__(self):
return int(self.numpy())
def __array__(self, dtype=None):
return np.array(self.numpy(), dtype=dtype)
def __format__(self, format_spec):
return self.numpy().__format__(format_spec)
def _numpy(self):
raise NotImplementedError()
def __copy__(self):
# Eager Tensors are immutable so it's safe to return themselves as a copy.
return self
def __deepcopy__(self, memo):
# Eager Tensors are immutable so it's safe to return themselves as a copy.
del memo
return self
def _datatype_enum(self):
raise NotImplementedError()
def _shape_tuple(self):
"""The shape of this Tensor, as a tuple.
This is more performant than tuple(shape().as_list()) as it avoids
two list and one object creation. Marked private for now as from an API
perspective, it would be better to have a single performant way of
getting a shape rather than exposing shape() and shape_tuple()
(and heaven forbid, shape_list() etc. as well!). Punting on that for now,
but ideally one would work things out and remove the need for this method.
Returns:
tuple with the shape.
"""
raise NotImplementedError()
def _rank(self):
"""Integer rank of this Tensor.
Unlike regular Tensors, the rank is always known for EagerTensors.
This is more performant than len(self._shape_tuple())
Returns:
Integer rank
"""
raise NotImplementedError()
def _copy_to_device(self, context, device): # pylint: disable=redefined-outer-name
raise NotImplementedError()
def __str__(self):
return "tf.Tensor(%s, shape=%s, dtype=%s)" % (numpy_text(self),
self.shape,
self.dtype.name)
def __repr__(self):
return "<tf.Tensor: id=%s, shape=%s, dtype=%s, numpy=%s>" % (
self._id, self.shape, self.dtype.name, numpy_text(self, is_repr=True))
@staticmethod
def _override_operator(name, func):
setattr(_EagerTensorBase, name, func)
def _copy_nograd(self, ctx=None, device_name=None):
"""Copies tensor to dest device, but doesn't record the operation."""
# pylint: disable=protected-access
# Creates a new tensor on the dest device.
if ctx is None:
ctx = context.context()
if device_name is None:
device_name = ctx.device_name
# pylint: disable=protected-access
try:
new_tensor = self._copy_to_device(context=ctx._handle, device=device_name)
except core._NotOkStatusException as e:
six.raise_from(core._status_to_exception(e.code, e.message), None)
return new_tensor
def _copy(self, ctx=None, device_name=None):
"""Copies tensor to dest device."""
new_tensor = self._copy_nograd(ctx, device_name)
# Record the copy on tape and define backprop copy as well.
if context.executing_eagerly():
self_device = self.device
def grad_fun(dresult):
return [dresult._copy(device_name=self_device)]
tape.record_operation("_copy", [new_tensor], [self], grad_fun)
return new_tensor
# pylint: enable=protected-access
@property
def shape(self):
if self._tensor_shape is None: # pylint: disable=access-member-before-definition
# `_tensor_shape` is declared and defined in the definition of
# `EagerTensor`, in C.
self._tensor_shape = tensor_shape.TensorShape(self._shape_tuple())
return self._tensor_shape
def get_shape(self):
"""Alias of Tensor.shape."""
return self.shape
def _shape_as_list(self):
"""The shape of the tensor as a list."""
return list(self._shape_tuple())
@property
def ndim(self):
"""Returns the number of Tensor dimensions."""
return self.shape.ndims
def _cpu_nograd(self):
"""A copy of this Tensor with contents backed by host memory.
The copy cannot be differentiated through.
Returns:
A CPU-memory backed Tensor object with the same contents as this Tensor.
"""
return self._copy_nograd(context.context(), "CPU:0")
def cpu(self):
"""A copy of this Tensor with contents backed by host memory."""
return self._copy(context.context(), "CPU:0")
def gpu(self, gpu_index=0):
"""A copy of this Tensor with contents backed by memory on the GPU.
Arguments:
gpu_index: Identifies which GPU to place the contents on the returned
Tensor in.
Returns:
A GPU-memory backed Tensor object initialized with the same contents
as this Tensor.
"""
return self._copy(context.context(), "GPU:" + str(gpu_index))
def __bool__(self):
if self._shape_tuple() != (): # pylint: disable=g-explicit-bool-comparison
raise ValueError(
"Non-scalar tensor %s cannot be converted to boolean." % repr(self))
if self.dtype != dtypes.bool:
raise ValueError(
"Non-boolean tensor %s cannot be converted to boolean." % repr(self))
return bool(self.cpu().numpy())
def __nonzero__(self):
return self.__bool__()
def set_shape(self, shape):
if not self.shape.is_compatible_with(shape):
raise ValueError(
"Tensor's shape %s is not compatible with supplied shape %s" %
(self.shape, shape))
# Methods not supported / implemented for Eager Tensors.
@property
def op(self):
raise AttributeError(
"Tensor.op is meaningless when eager execution is enabled.")
@property
def graph(self):
raise AttributeError(
"Tensor.graph is meaningless when eager execution is enabled.")
@property
def name(self):
raise AttributeError(
"Tensor.name is meaningless when eager execution is enabled.")
@property
def value_index(self):
raise AttributeError(
"Tensor.value_index is meaningless when eager execution is enabled.")
def consumers(self):
raise NotImplementedError(
"Tensor.consumers is meaningless when eager execution is enabled.")
def _add_consumer(self, consumer):
raise NotImplementedError(
"_add_consumer not supported when eager execution is enabled.")
def _as_node_def_input(self):
raise NotImplementedError(
"_as_node_def_input not supported when eager execution is enabled.")
def _as_tf_output(self):
raise NotImplementedError(
"_as_tf_output not supported when eager execution is enabled.")
def eval(self, feed_dict=None, session=None):
raise NotImplementedError(
"eval is not supported when eager execution is enabled, "
"is .numpy() what you're looking for?"
)
# This call creates an EagerTensor class, as a subclass of _EagerTensorBase, and
# registers it with the current module.
EagerTensor = c_api.TFE_Py_InitEagerTensor(_EagerTensorBase)
def _TensorTensorConversionFunction(t, dtype=None, name=None, as_ref=False):
_ = name, as_ref
if dtype and not dtype.is_compatible_with(t.dtype):
raise ValueError(
"Tensor conversion requested dtype %s for Tensor with dtype %s: %r" %
(dtype.name, t.dtype.name, str(t)))
return t
_tensor_conversion_func_registry = {
0: [(Tensor, _TensorTensorConversionFunction)]
}
_tensor_conversion_func_cache = {}
_tensor_conversion_func_lock = threading.Lock()
register_dense_tensor_like_type(Tensor)
@tf_export("convert_to_tensor")
def convert_to_tensor(value, dtype=None, name=None, preferred_dtype=None):
"""Converts the given `value` to a `Tensor`.
This function converts Python objects of various types to `Tensor`
objects. It accepts `Tensor` objects, numpy arrays, Python lists,
and Python scalars. For example:
```python
import numpy as np
def my_func(arg):
arg = tf.convert_to_tensor(arg, dtype=tf.float32)
return tf.matmul(arg, arg) + arg
# The following calls are equivalent.
value_1 = my_func(tf.constant([[1.0, 2.0], [3.0, 4.0]]))
value_2 = my_func([[1.0, 2.0], [3.0, 4.0]])
value_3 = my_func(np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32))
```
This function can be useful when composing a new operation in Python
(such as `my_func` in the example above). All standard Python op
constructors apply this function to each of their Tensor-valued
inputs, which allows those ops to accept numpy arrays, Python lists,
and scalars in addition to `Tensor` objects.
Note: This function diverges from default Numpy behavior for `float` and
`string` types when `None` is present in a Python list or scalar. Rather
than silently converting `None` values, an error will be thrown.
Args:
value: An object whose type has a registered `Tensor` conversion function.
dtype: Optional element type for the returned tensor. If missing, the
type is inferred from the type of `value`.
name: Optional name to use if a new `Tensor` is created.
preferred_dtype: Optional element type for the returned tensor,
used when dtype is None. In some cases, a caller may not have a
dtype in mind when converting to a tensor, so preferred_dtype
can be used as a soft preference. If the conversion to
`preferred_dtype` is not possible, this argument has no effect.
Returns:
An `Output` based on `value`.
Raises:
TypeError: If no conversion function is registered for `value`.
RuntimeError: If a registered conversion function returns an invalid value.
"""
return internal_convert_to_tensor(
value=value,
dtype=dtype,
name=name,
preferred_dtype=preferred_dtype,
as_ref=False)
def _error_prefix(name):
return "" if name is None else "%s: " % name
def internal_convert_to_tensor(value,
dtype=None,
name=None,
as_ref=False,
preferred_dtype=None,
ctx=None):
"""Converts the given `value` to an `Tensor`.
This function converts Python objects of various types to `Tensor`
objects. It accepts `Tensor` objects, numpy arrays, Python lists,
and Python scalars. For example:
This function can be useful when composing a new operation in Python
All standard Python op constructors apply this function to each of their
Tensor-valued inputs, which allows those ops to accept numpy arrays, Python
lists, and scalars in addition to `Tensor` objects.
Args:
value: An object whose type has a registered `Tensor` conversion function.
dtype: Optional element type for the returned tensor. If missing, the
type is inferred from the type of `value`.
name: Optional name to use if a new `Tensor` is created.
as_ref: True if we want the mutable view of Variables, if applicable.
preferred_dtype: Optional element type for the returned tensor,
used when dtype is None. In some cases, a caller may not have a
dtype in mind when converting to a tensor, so preferred_dtype
can be used as a soft preference. If the conversion to
`preferred_dtype` is not possible, this argument has no effect.
ctx: Optional: The value of context.context().
Returns:
A `Tensor` based on `value`.
Raises:
TypeError: If no conversion function is registered for `value`.
RuntimeError: If a registered conversion function returns an invalid value.
"""
if ctx is None: ctx = context.context()
if isinstance(value, EagerTensor):
if ctx.executing_eagerly():
# Fast path for EagerTensors that don't need any conversion.
# Note that we don't check that value's dtype matches the dtype
# argument. We expect that the C runtime will do that checking
# when we execute the kernel.
return value
else:
graph = get_default_graph()
if not graph.building_function:
raise RuntimeError("Attempting to capture an EagerTensor without "
"building a function.")
return graph.capture(value, name=name)
if dtype is not None:
dtype = dtypes.as_dtype(dtype)
unwrapped_type = type(value)
conversion_func_list = _tensor_conversion_func_cache.get(unwrapped_type, None)
if conversion_func_list is None:
with _tensor_conversion_func_lock:
conversion_func_list = []
for _, funcs_at_priority in sorted(
_tensor_conversion_func_registry.items()):
for base_type, conversion_func in funcs_at_priority:
if isinstance(value, base_type):
conversion_func_list.append((base_type, conversion_func))
_tensor_conversion_func_cache[unwrapped_type] = conversion_func_list
for base_type, conversion_func in conversion_func_list:
# If dtype is None but preferred_dtype is not None, we try to
# cast to preferred_dtype first.
ret = None
if dtype is None and preferred_dtype is not None:
try:
ret = conversion_func(
value, dtype=preferred_dtype, name=name, as_ref=as_ref)
except (TypeError, ValueError, errors.UnimplementedError,
errors.InvalidArgumentError):
# Could not coerce the conversion to use the preferred dtype.
ret = None
if ret is not None and ret is not NotImplemented:
if (ret.dtype.base_dtype !=
dtypes.as_dtype(preferred_dtype).base_dtype):
raise TypeError("convert_to_tensor did not convert to "
"the preferred dtype: %s vs %s " %
(ret.dtype.base_dtype,
dtypes.as_dtype(preferred_dtype).base_dtype))
if ret is None:
ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
if ret is NotImplemented:
continue
if not isinstance(ret, Tensor):
raise RuntimeError(
"%sConversion function %r for type %s returned non-Tensor: %r" %
(_error_prefix(name), conversion_func, base_type, ret))
if dtype and not dtype.is_compatible_with(ret.dtype):
raise RuntimeError(
"%sConversion function %r for type %s returned incompatible "
"dtype: requested = %s, actual = %s" %
(_error_prefix(name), conversion_func, base_type, dtype.name,
ret.dtype.name))
return ret
raise TypeError("%sCannot convert %r with type %s to Tensor: "
"no conversion function registered." %
(_error_prefix(name), value, unwrapped_type))
def internal_convert_n_to_tensor(values,
dtype=None,
name=None,
as_ref=False,
preferred_dtype=None,
ctx=None):
"""Converts `values` to a list of `Tensor` objects.
Args:
values: A list of objects that can be consumed by `tf.convert_to_tensor()`.
dtype: (Optional.) The required `DType` of the returned `Tensor` objects.
name: (Optional.) A name prefix to used when a new `Tensor` is
created, in which case element `i` will be given the name `name
+ '_' + i`.
as_ref: True if the caller wants the results as ref tensors.
preferred_dtype: Optional element type for the returned tensors,
used when dtype is None. In some cases, a caller may not have a
dtype in mind when converting to a tensor, so preferred_dtype
can be used as a soft preference. If the conversion to
`preferred_dtype` is not possible, this argument has no effect.
ctx: The value of context.context().
Returns:
A list of `Tensor` and/or `IndexedSlices` objects.
Raises:
TypeError: If no conversion function is registered for an element in
`values`.
RuntimeError: If a registered conversion function returns an invalid
value.
"""
if not isinstance(values, collections.Sequence):
raise TypeError("values must be a list.")
ret = []
if ctx is None: ctx = context.context()
for i, value in enumerate(values):
n = None if name is None else "%s_%d" % (name, i)
ret.append(
internal_convert_to_tensor(
value,
dtype=dtype,
name=n,
as_ref=as_ref,
preferred_dtype=preferred_dtype,
ctx=ctx))
return ret
def convert_n_to_tensor(values, dtype=None, name=None, preferred_dtype=None):
"""Converts `values` to a list of `Tensor` objects.
Args:
values: A list of objects that can be consumed by `tf.convert_to_tensor()`.
dtype: (Optional.) The required `DType` of the returned `Tensor` objects.
name: (Optional.) A name prefix to used when a new `Tensor` is
created, in which case element `i` will be given the name `name
+ '_' + i`.
preferred_dtype: Optional element type for the returned tensors,
used when dtype is None. In some cases, a caller may not have a
dtype in mind when converting to a tensor, so preferred_dtype
can be used as a soft preference. If the conversion to
`preferred_dtype` is not possible, this argument has no effect.
Returns:
A list of `Tensor` and/or `IndexedSlices` objects.
Raises:
TypeError: If no conversion function is registered for an element in
`values`.
RuntimeError: If a registered conversion function returns an invalid
value.
"""
return internal_convert_n_to_tensor(
values=values,
dtype=dtype,
name=name,
preferred_dtype=preferred_dtype,
as_ref=False)
@tf_export("convert_to_tensor_or_indexed_slices")
def convert_to_tensor_or_indexed_slices(value, dtype=None, name=None):
"""Converts the given object to a `Tensor` or an `IndexedSlices`.
If `value` is an `IndexedSlices` or `SparseTensor` it is returned
unmodified. Otherwise, it is converted to a `Tensor` using
`convert_to_tensor()`.
Args:
value: An `IndexedSlices`, `SparseTensor`, or an object that can be consumed
by `convert_to_tensor()`.
dtype: (Optional.) The required `DType` of the returned `Tensor` or
`IndexedSlices`.
name: (Optional.) A name to use if a new `Tensor` is created.
Returns:
An `Tensor`, `IndexedSlices`, or `SparseTensor` based on `value`.
Raises:
ValueError: If `dtype` does not match the element type of `value`.
"""
return internal_convert_to_tensor_or_indexed_slices(
value=value, dtype=dtype, name=name, as_ref=False)
def internal_convert_to_tensor_or_indexed_slices(value,
dtype=None,
name=None,
as_ref=False):
"""Converts the given object to an `Tensor` or an `IndexedSlices`.
If `value` is an `IndexedSlices` or `SparseTensor` it is returned
unmodified. Otherwise, it is converted to a `Tensor` using
`convert_to_tensor()`.
Args:
value: An `IndexedSlices`, `SparseTensor`, or an object that can be consumed
by `convert_to_tensor()`.
dtype: (Optional.) The required `DType` of the returned `Tensor` or
`IndexedSlices`.
name: (Optional.) A name to use if a new `Tensor` is created.
as_ref: True if the caller wants the results as ref tensors.
Returns:
An `Tensor`, `IndexedSlices`, or `SparseTensor` based on `value`.
Raises:
ValueError: If `dtype` does not match the element type of `value`.
"""
if isinstance(value, EagerTensor) and not context.executing_eagerly():
return internal_convert_to_tensor(
value, dtype=dtype, name=name, as_ref=as_ref)
elif isinstance(value, _TensorLike):
if dtype and not dtypes.as_dtype(dtype).is_compatible_with(value.dtype):
raise ValueError(
"Tensor conversion requested dtype %s for Tensor with dtype %s: %r" %
(dtypes.as_dtype(dtype).name, value.dtype.name, str(value)))
return value
else:
return internal_convert_to_tensor(
value, dtype=dtype, name=name, as_ref=as_ref)
def internal_convert_n_to_tensor_or_indexed_slices(values,
dtype=None,
name=None,
as_ref=False):
"""Converts `values` to a list of `Tensor` or `IndexedSlices` objects.
Any `IndexedSlices` or `SparseTensor` objects in `values` are returned
unmodified.
Args:
values: A list of `None`, `IndexedSlices`, `SparseTensor`, or objects that
can be consumed by `convert_to_tensor()`.
dtype: (Optional.) The required `DType` of the returned `Tensor`
`IndexedSlices`.
name: (Optional.) A name prefix to used when a new `Tensor` is
created, in which case element `i` will be given the name `name
+ '_' + i`.
as_ref: True if the caller wants the results as ref tensors.
Returns:
A list of `Tensor`, `IndexedSlices`, and/or `SparseTensor` objects.
Raises:
TypeError: If no conversion function is registered for an element in
`values`.
RuntimeError: If a registered conversion function returns an invalid
value.
"""
if not isinstance(values, collections.Sequence):
raise TypeError("values must be a list.")
ret = []
for i, value in enumerate(values):
if value is None:
ret.append(value)
else:
n = None if name is None else "%s_%d" % (name, i)
ret.append(
internal_convert_to_tensor_or_indexed_slices(
value, dtype=dtype, name=n, as_ref=as_ref))
return ret
def convert_n_to_tensor_or_indexed_slices(values, dtype=None, name=None):
"""Converts `values` to a list of `Output` or `IndexedSlices` objects.
Any `IndexedSlices` or `SparseTensor` objects in `values` are returned
unmodified.
Args:
values: A list of `None`, `IndexedSlices`, `SparseTensor`, or objects that
can be consumed by `convert_to_tensor()`.
dtype: (Optional.) The required `DType` of the returned `Tensor`
`IndexedSlices`.
name: (Optional.) A name prefix to used when a new `Tensor` is
created, in which case element `i` will be given the name `name
+ '_' + i`.
Returns:
A list of `Tensor`, `IndexedSlices`, and/or `SparseTensor` objects.
Raises:
TypeError: If no conversion function is registered for an element in
`values`.
RuntimeError: If a registered conversion function returns an invalid
value.
"""
return internal_convert_n_to_tensor_or_indexed_slices(
values=values, dtype=dtype, name=name, as_ref=False)
# TODO(josh11b): Add ctx argument to conversion_func() signature.
@tf_export("register_tensor_conversion_function")
def register_tensor_conversion_function(base_type,
conversion_func,
priority=100):
"""Registers a function for converting objects of `base_type` to `Tensor`.
The conversion function must have the following signature:
```python
def conversion_func(value, dtype=None, name=None, as_ref=False):
# ...
```
It must return a `Tensor` with the given `dtype` if specified. If the
conversion function creates a new `Tensor`, it should use the given
`name` if specified. All exceptions will be propagated to the caller.
The conversion function may return `NotImplemented` for some
inputs. In this case, the conversion process will continue to try
subsequent conversion functions.
If `as_ref` is true, the function must return a `Tensor` reference,
such as a `Variable`.
NOTE: The conversion functions will execute in order of priority,
followed by order of registration. To ensure that a conversion function
`F` runs before another conversion function `G`, ensure that `F` is
registered with a smaller priority than `G`.
Args:
base_type: The base type or tuple of base types for all objects that
`conversion_func` accepts.
conversion_func: A function that converts instances of `base_type` to
`Tensor`.
priority: Optional integer that indicates the priority for applying this
conversion function. Conversion functions with smaller priority values
run earlier than conversion functions with larger priority values.
Defaults to 100.
Raises:
TypeError: If the arguments do not have the appropriate type.
"""
global _tensor_conversion_func_cache
with _tensor_conversion_func_lock:
if not (isinstance(base_type, type) or
(isinstance(base_type, tuple) and
all(isinstance(x, type) for x in base_type))):
raise TypeError("base_type must be a type or a tuple of types.")
if not callable(conversion_func):
raise TypeError("conversion_func must be callable.")
# context._context is checked so that we don't inadvertently create it.
# This is because enable_eager_execution will fail when called from the main
# function if the context._context is already created, and the
# register_tensor_conversion_function calls happen when the module is
# imported.
if context._context is not None and context.executing_eagerly(
) and isinstance(base_type, six.integer_types + (
float,
np.ndarray,
)):
# TODO(nareshmodi): consider setting a context variable which disables the
# fastpath instead.
raise TypeError(
"Cannot register conversions for numpy arrays, python number types "
"when executing eagerly.")
try:
funcs_at_priority = _tensor_conversion_func_registry[priority]
except KeyError:
funcs_at_priority = []
_tensor_conversion_func_registry[priority] = funcs_at_priority
funcs_at_priority.append((base_type, conversion_func))
_tensor_conversion_func_cache = {}
@tf_export("IndexedSlices")
class IndexedSlices(_TensorLike):
"""A sparse representation of a set of tensor slices at given indices.
This class is a simple wrapper for a pair of `Tensor` objects:
* `values`: A `Tensor` of any dtype with shape `[D0, D1, ..., Dn]`.
* `indices`: A 1-D integer `Tensor` with shape `[D0]`.
An `IndexedSlices` is typically used to represent a subset of a larger
tensor `dense` of shape `[LARGE0, D1, .. , DN]` where `LARGE0 >> D0`.
The values in `indices` are the indices in the first dimension of
the slices that have been extracted from the larger tensor.
The dense tensor `dense` represented by an `IndexedSlices` `slices` has
```python
dense[slices.indices[i], :, :, :, ...] = slices.values[i, :, :, :, ...]
```
The `IndexedSlices` class is used principally in the definition of
gradients for operations that have sparse gradients
(e.g. `tf.gather`).
Contrast this representation with
`tf.SparseTensor`,
which uses multi-dimensional indices and scalar values.
"""
def __init__(self, values, indices, dense_shape=None):
"""Creates an `IndexedSlices`."""
_get_graph_from_inputs([values, indices, dense_shape])
self._values = values
self._indices = indices
self._dense_shape = dense_shape
@property
def values(self):
"""A `Tensor` containing the values of the slices."""
return self._values
@property
def indices(self):
"""A 1-D `Tensor` containing the indices of the slices."""
return self._indices
@property
def dense_shape(self):
"""A 1-D `Tensor` containing the shape of the corresponding dense tensor."""
return self._dense_shape
@property
def name(self):
"""The name of this `IndexedSlices`."""
return self.values.name
@property
def device(self):
"""The name of the device on which `values` will be produced, or `None`."""
return self.values.device
@property
def op(self):
"""The `Operation` that produces `values` as an output."""
return self.values.op
@property
def dtype(self):
"""The `DType` of elements in this tensor."""
return self.values.dtype
@property
def graph(self):
"""The `Graph` that contains the values, indices, and shape tensors."""
return self._values.graph
def __str__(self):
return "IndexedSlices(indices=%s, values=%s%s)" % (
self._indices, self._values, (", dense_shape=%s" % self._dense_shape)
if self._dense_shape is not None else "")
def __neg__(self):
return IndexedSlices(-self.values, self.indices, self.dense_shape)
IndexedSlicesValue = collections.namedtuple(
"IndexedSlicesValue", ["values", "indices", "dense_shape"])
def _device_string(dev_spec):
if isinstance(dev_spec, pydev.DeviceSpec):
return dev_spec.to_string()
else:
return dev_spec
def _NodeDef(op_type, name, device=None, attrs=None): # pylint: disable=redefined-outer-name
"""Create a NodeDef proto.
Args:
op_type: Value for the "op" attribute of the NodeDef proto.
name: Value for the "name" attribute of the NodeDef proto.
device: string, device, or function from NodeDef to string.
Value for the "device" attribute of the NodeDef proto.
attrs: Optional dictionary where the key is the attribute name (a string)
and the value is the respective "attr" attribute of the NodeDef proto (an
AttrValue).
Returns:
A node_def_pb2.NodeDef protocol buffer.
"""
node_def = node_def_pb2.NodeDef()
node_def.op = compat.as_bytes(op_type)
node_def.name = compat.as_bytes(name)
if attrs is not None:
for k, v in six.iteritems(attrs):
node_def.attr[k].CopyFrom(v)
if device is not None:
if callable(device):
node_def.device = device(node_def)
else:
node_def.device = _device_string(device)
return node_def
# Copied from core/framework/node_def_util.cc
# TODO(mrry,josh11b): Consolidate this validation in C++ code.
_VALID_OP_NAME_REGEX = re.compile("^[A-Za-z0-9.][A-Za-z0-9_.\\-/]*$")
_VALID_SCOPE_NAME_REGEX = re.compile("^[A-Za-z0-9_.\\-/]*$")
def _create_c_op(graph, node_def, inputs, control_inputs):
"""Creates a TF_Operation.
Args:
graph: a `Graph`.
node_def: `node_def_pb2.NodeDef` for the operation to create.
inputs: A list of `Tensor`s (corresponding to scalar inputs) and lists of
`Tensor`s (corresponding to sequence inputs, e.g. "int64 * N",
"list(int64)"). The length of the list should be equal to the number of
inputs specified by this operation's op def.
control_inputs: A list of `Operation`s to set as control dependencies.
Returns:
A wrapped TF_Operation*.
"""
# pylint: disable=protected-access
op_desc = c_api.TF_NewOperation(graph._c_graph,
compat.as_str(node_def.op),
compat.as_str(node_def.name))
# Add inputs
for op_input in inputs:
if isinstance(op_input, (list, tuple)):
c_api.TF_AddInputList(op_desc, [t._as_tf_output() for t in op_input])
else:
c_api.TF_AddInput(op_desc, op_input._as_tf_output())
# Add control inputs
for control_input in control_inputs:
c_api.TF_AddControlInput(op_desc, control_input._c_op)
# pylint: enable=protected-access
# Add attrs
for name, attr_value in node_def.attr.items():
serialized = attr_value.SerializeToString()
# TODO(skyewm): this creates and deletes a new TF_Status for every attr.
# It might be worth creating a convenient way to re-use the same status.
c_api.TF_SetAttrValueProto(op_desc, compat.as_str(name), serialized)
try:
c_op = c_api.TF_FinishOperation(op_desc)
except errors.InvalidArgumentError as e:
# Convert to ValueError for backwards compatibility.
raise ValueError(str(e))
return c_op
@tf_export("Operation")
class Operation(object):
"""Represents a graph node that performs computation on tensors.
An `Operation` is a node in a TensorFlow `Graph` that takes zero or
more `Tensor` objects as input, and produces zero or more `Tensor`
objects as output. Objects of type `Operation` are created by
calling a Python op constructor (such as
`tf.matmul`)
or `tf.Graph.create_op`.
For example `c = tf.matmul(a, b)` creates an `Operation` of type
"MatMul" that takes tensors `a` and `b` as input, and produces `c`
as output.
After the graph has been launched in a session, an `Operation` can
be executed by passing it to
`tf.Session.run`.
`op.run()` is a shortcut for calling `tf.get_default_session().run(op)`.
"""
def __init__(self,
node_def,
g,
inputs=None,
output_types=None,
control_inputs=None,
input_types=None,
original_op=None,
op_def=None):
r"""Creates an `Operation`.
NOTE: This constructor validates the name of the `Operation` (passed
as `node_def.name`). Valid `Operation` names match the following
regular expression:
[A-Za-z0-9.][A-Za-z0-9_.\\-/]*
Args:
node_def: `node_def_pb2.NodeDef`. `NodeDef` for the `Operation`.
Used for attributes of `node_def_pb2.NodeDef`, typically `name`,
`op`, and `device`. The `input` attribute is irrelevant here
as it will be computed when generating the model.
g: `Graph`. The parent graph.
inputs: list of `Tensor` objects. The inputs to this `Operation`.
output_types: list of `DType` objects. List of the types of the
`Tensors` computed by this operation. The length of this list indicates
the number of output endpoints of the `Operation`.
control_inputs: list of operations or tensors from which to have a
control dependency.
input_types: List of `DType` objects representing the
types of the tensors accepted by the `Operation`. By default
uses `[x.dtype.base_dtype for x in inputs]`. Operations that expect
reference-typed inputs must specify these explicitly.
original_op: Optional. Used to associate the new `Operation` with an
existing `Operation` (for example, a replica with the op that was
replicated).
op_def: Optional. The `op_def_pb2.OpDef` proto that describes the
op type that this `Operation` represents.
Raises:
TypeError: if control inputs are not Operations or Tensors,
or if `node_def` is not a `NodeDef`,
or if `g` is not a `Graph`,
or if `inputs` are not tensors,
or if `inputs` and `input_types` are incompatible.
ValueError: if the `node_def` name is not valid.
"""
# For internal use only: `node_def` can be set to a TF_Operation to create
# an Operation for that op. This is useful for creating Operations for ops
# indirectly created by C API methods, e.g. the ops created by
# TF_ImportGraphDef. When `node_def` is a TF_Operation, all optional fields
# should be None.
if isinstance(node_def, node_def_pb2.NodeDef):
if node_def.ByteSize() >= (1 << 31) or node_def.ByteSize() < 0:
raise ValueError(
"Cannot create a tensor proto whose content is larger than 2GB.")
if not _VALID_OP_NAME_REGEX.match(node_def.name):
raise ValueError("'%s' is not a valid node name" % node_def.name)
c_op = None
elif type(node_def).__name__ == "SwigPyObject":
assert inputs is None
assert output_types is None
assert control_inputs is None
assert input_types is None
assert original_op is None
assert op_def is None
c_op = node_def
else:
raise TypeError("node_def needs to be a NodeDef: %s" % node_def)
if not isinstance(g, Graph):
raise TypeError("g needs to be a Graph: %s" % g)
self._graph = g
if inputs is None:
inputs = []
elif not isinstance(inputs, list):
raise TypeError("inputs needs to be a list of Tensors: %s" % inputs)
for a in inputs:
if not isinstance(a, Tensor):
raise TypeError("input needs to be a Tensor: %s" % a)
if input_types is None:
input_types = [i.dtype.base_dtype for i in inputs]
else:
if not all(
x.is_compatible_with(i.dtype)
for i, x in zip(inputs, input_types)):
raise TypeError("In op '%s', input types (%s) are not compatible "
"with expected types (%s)" %
(node_def.name, [i.dtype for i in inputs],
input_types))
# Build the list of control inputs.
control_input_ops = []
if control_inputs:
for c in control_inputs:
control_op = None
if isinstance(c, Operation):
control_op = c
elif isinstance(c, (Tensor, IndexedSlices)):
control_op = c.op
else:
raise TypeError("Control input must be an Operation, "
"a Tensor, or IndexedSlices: %s" % c)
control_input_ops.append(control_op)
# This will be set by self.inputs.
self._inputs_val = None
# pylint: disable=protected-access
self._id_value = self._graph._next_id()
self._original_op = original_op
self._traceback = tf_stack.extract_stack()
# List of _UserDevSpecs holding code location of device context manager
# invocations and the users original argument to them.
self._device_code_locations = None
# Dict mapping op name to file and line information for op colocation
# context managers.
self._colocation_code_locations = None
self._control_flow_context = self.graph._get_control_flow_context()
# pylint: enable=protected-access
# Initialize self._c_op.
if c_op:
self._c_op = c_op
else:
if op_def is None:
op_def = self._graph._get_op_def(node_def.op)
# TODO(skyewm): op_def_library.apply_op() flattens the incoming inputs.
# Refactor so we don't have to do this here.
grouped_inputs = self._reconstruct_sequence_inputs(
op_def, inputs, node_def.attr)
self._c_op = _create_c_op(self._graph, node_def, grouped_inputs,
control_input_ops)
# Initialize self._outputs.
num_outputs = c_api.TF_OperationNumOutputs(self._c_op)
output_types = [
c_api.TF_OperationOutputType(c_api_util.tf_output(self._c_op, i))
for i in range(num_outputs)]
self._outputs = [
Tensor(self, i, output_type)
for i, output_type in enumerate(output_types)
]
self._graph._add_op(self) # pylint: disable=protected-access
if not c_op:
self._control_flow_post_processing()
def _control_flow_post_processing(self):
"""Add this op to its control flow context.
This may add new ops and change this op's inputs. self.inputs must be
available before calling this method.
"""
for input_tensor in self.inputs:
control_flow_util.CheckInputFromValidContext(self, input_tensor.op)
if self._control_flow_context is not None:
self._control_flow_context.AddOp(self)
def _reconstruct_sequence_inputs(self, op_def, inputs, attrs):
"""Regroups a flat list of input tensors into scalar and sequence inputs.
Args:
op_def: The `op_def_pb2.OpDef` (for knowing the input types)
inputs: a list of input `Tensor`s to the op.
attrs: mapping from attr name to `attr_value_pb2.AttrValue` (these define
how long each sequence is)
Returns:
A list of `Tensor`s (corresponding to scalar inputs) and lists of
`Tensor`s (corresponding to sequence inputs).
"""
grouped_inputs = []
i = 0
for input_arg in op_def.input_arg:
if input_arg.number_attr:
input_len = attrs[input_arg.number_attr].i
is_sequence = True
elif input_arg.type_list_attr:
input_len = len(attrs[input_arg.type_list_attr].list.type)
is_sequence = True
else:
input_len = 1
is_sequence = False
if is_sequence:
grouped_inputs.append(inputs[i:i + input_len])
else:
grouped_inputs.append(inputs[i])
i += input_len
assert i == len(inputs)
return grouped_inputs
def colocation_groups(self):
"""Returns the list of colocation groups of the op."""
default_colocation_group = [
compat.as_bytes("loc:@%s" % self.name)
]
try:
class_attr = self.get_attr("_class")
except ValueError:
# This op has no explicit colocation group, so it is itself its
# own root of a colocation group.
return default_colocation_group
attr_groups = [
class_name for class_name in class_attr
if class_name.startswith(b"loc:@")
]
# If there are no colocation groups in the explicit _class field,
# return the default colocation group.
return attr_groups if attr_groups else default_colocation_group
def values(self):
"""DEPRECATED: Use outputs."""
return tuple(self.outputs)
def _get_control_flow_context(self):
"""Returns the control flow context of this op.
Returns:
A context object.
"""
return self._control_flow_context
def _set_control_flow_context(self, ctx):
"""Sets the current control flow context of this op.
Args:
ctx: a context object.
"""
self._control_flow_context = ctx
@property
def name(self):
"""The full name of this operation."""
return c_api.TF_OperationName(self._c_op)
@property
def _id(self):
"""The unique integer id of this operation."""
return self._id_value
@property
def device(self):
"""The name of the device to which this op has been assigned, if any.
Returns:
The string name of the device to which this op has been
assigned, or an empty string if it has not been assigned to a
device.
"""
return c_api.TF_OperationDevice(self._c_op)
@property
def _device_assignments(self):
"""Code locations for device context managers active at op creation.
This property will return a list of traceable_stack.TraceableObject
instances where .obj is a string representing the assigned device
(or information about the function that would be applied to this op
to compute the desired device) and the filename and lineno members
record the location of the relevant device context manager.
For example, suppose file_a contained these lines:
file_a.py:
15: with tf.device('/gpu:0'):
16: node_b = tf.constant(4, name='NODE_B')
Then a TraceableObject t_obj representing the device context manager
would have these member values:
t_obj.obj -> '/gpu:0'
t_obj.filename = 'file_a.py'
t_obj.lineno = 15
and node_b.op._device_assignments would return the list [t_obj].
Returns:
[str: traceable_stack.TraceableObject, ...] as per this method's
description, above.
"""
return self._device_code_locations or []
@property
def _colocation_dict(self):
"""Code locations for colocation context managers active at op creation.
This property will return a dictionary for which the keys are nodes with
which this Operation is colocated, and for which the values are
traceable_stack.TraceableObject instances. The TraceableObject instances
record the location of the relevant colocation context manager but have the
"obj" field set to None to prevent leaking private data.
For example, suppose file_a contained these lines:
file_a.py:
14: node_a = tf.constant(3, name='NODE_A')
15: with tf.colocate_with(node_a):
16: node_b = tf.constant(4, name='NODE_B')
Then a TraceableObject t_obj representing the colocation context manager
would have these member values:
t_obj.obj -> None
t_obj.filename = 'file_a.py'
t_obj.lineno = 15
and node_b.op._colocation_dict would return the dictionary
{ 'NODE_A': t_obj }
Returns:
{str: traceable_stack.TraceableObject} as per this method's description,
above.
"""
locations_dict = self._colocation_code_locations or {}
return locations_dict.copy()
@property
def _output_types(self):
"""List this operation's output types.
Returns:
List of the types of the Tensors computed by this operation.
Each element in the list is an integer whose value is one of
the TF_DataType enums defined in c_api.h
The length of this list indicates the number of output endpoints
of the operation.
"""
num_outputs = c_api.TF_OperationNumOutputs(self._c_op)
output_types = [
c_api.TF_OperationOutputType(self._tf_output(i))
for i in xrange(num_outputs)
]
# In all the tests we have output_types that are passed into
# Operation.__init__ are a list of ints (which is illegal according
# to the docstring), but input_types are instances of DType.
# This extra assert is to catch if we ever use DType for output_types.
if output_types:
assert isinstance(output_types[0], int)
return output_types
def _tf_output(self, output_idx):
"""Create and return a new TF_Output for output_idx'th output of this op."""
tf_output = c_api.TF_Output()
tf_output.oper = self._c_op
tf_output.index = output_idx
return tf_output
def _tf_input(self, input_idx):
"""Create and return a new TF_Input for input_idx'th input of this op."""
tf_input = c_api.TF_Input()
tf_input.oper = self._c_op
tf_input.index = input_idx
return tf_input
def _set_device(self, device): # pylint: disable=redefined-outer-name
"""Set the device of this operation.
Args:
device: string or device.. The device to set.
"""
c_api.SetRequestedDevice(
self._graph._c_graph, # pylint: disable=protected-access
self._c_op, # pylint: disable=protected-access
compat.as_str(_device_string(device)))
def _update_input(self, index, tensor):
"""Update the input to this operation at the given index.
NOTE: This is for TF internal use only. Please don't use it.
Args:
index: the index of the input to update.
tensor: the Tensor to be used as the input at the given index.
Raises:
TypeError: if tensor is not a Tensor,
or if input tensor type is not convertible to dtype.
ValueError: if the Tensor is from a different graph.
"""
if not isinstance(tensor, Tensor):
raise TypeError("tensor must be a Tensor: %s" % tensor)
_assert_same_graph(self, tensor)
# Make sure output shapes are already computed for this op in case we create
# a cycle (we cannot compute shapes for cycles). Usually shapes are computed
# lazily upon request.
if not _USE_C_SHAPES:
set_shape_and_handle_data_for_outputs(self)
# Reset cached inputs.
self._inputs_val = None
c_api.UpdateEdge(
self._graph._c_graph, # pylint: disable=protected-access
tensor._as_tf_output(), # pylint: disable=protected-access
self._tf_input(index))
def _add_control_inputs(self, ops):
"""Add a list of new control inputs to this operation.
Args:
ops: the list of Operations to add as control input.
Raises:
TypeError: if ops is not a list of Operations.
ValueError: if any op in ops is from a different graph.
"""
for op in ops:
if not isinstance(op, Operation):
raise TypeError("op must be an Operation: %s" % op)
c_api.AddControlInput(self._graph._c_graph, self._c_op, op._c_op) # pylint: disable=protected-access
def _add_control_input(self, op):
"""Add a new control input to this operation.
Args:
op: the Operation to add as control input.
Raises:
TypeError: if op is not an Operation.
ValueError: if op is from a different graph.
"""
if not isinstance(op, Operation):
raise TypeError("op must be an Operation: %s" % op)
c_api.AddControlInput(self._graph._c_graph, self._c_op, op._c_op) # pylint: disable=protected-access
def _remove_all_control_inputs(self):
"""Removes any control inputs to this operation."""
c_api.RemoveAllControlInputs(self._graph._c_graph, self._c_op) # pylint: disable=protected-access
def __str__(self):
return str(self.node_def)
def __repr__(self):
return "<tf.Operation '%s' type=%s>" % (self.name, self.type)
@property
def outputs(self):
"""The list of `Tensor` objects representing the outputs of this op."""
return self._outputs
# pylint: disable=protected-access
class _InputList(object):
"""Immutable input list wrapper."""
def __init__(self, inputs):
self._inputs = inputs
def __iter__(self):
return iter(self._inputs)
def __len__(self):
return len(self._inputs)
def __bool__(self):
return bool(self._inputs)
# Python 3 wants __bool__, Python 2.7 wants __nonzero__
__nonzero__ = __bool__
def __getitem__(self, i):
return self._inputs[i]
# pylint: enable=protected-access
@property
def inputs(self):
"""The list of `Tensor` objects representing the data inputs of this op."""
if self._inputs_val is None:
tf_outputs = c_api.GetOperationInputs(self._c_op)
# pylint: disable=protected-access
retval = [
self.graph._get_tensor_by_tf_output(tf_output)
for tf_output in tf_outputs
]
# pylint: enable=protected-access
self._inputs_val = Operation._InputList(retval)
return self._inputs_val
@property
def _inputs(self):
logging.warning("Operation._inputs is private, use Operation.inputs "
"instead. Operation._inputs will eventually be removed.")
return self.inputs
@_inputs.setter
def _inputs(self, value):
raise ValueError("Cannot assign _inputs")
@property
def _input_types(self):
num_inputs = c_api.TF_OperationNumInputs(self._c_op)
input_types = [
dtypes.as_dtype(c_api.TF_OperationInputType(self._tf_input(i)))
for i in xrange(num_inputs)
]
return input_types
@_input_types.setter
def _input_types(self, value):
raise ValueError("Cannot assign _input_types")
@property
def control_inputs(self):
"""The `Operation` objects on which this op has a control dependency.
Before this op is executed, TensorFlow will ensure that the
operations in `self.control_inputs` have finished executing. This
mechanism can be used to run ops sequentially for performance
reasons, or to ensure that the side effects of an op are observed
in the correct order.
Returns:
A list of `Operation` objects.
"""
control_c_ops = c_api.TF_OperationGetControlInputs_wrapper(self._c_op)
# pylint: disable=protected-access
return [
self.graph._get_operation_by_name_unsafe(
c_api.TF_OperationName(c_op)) for c_op in control_c_ops
]
# pylint: enable=protected-access
@property
def _control_outputs(self):
"""The `Operation` objects which have a control dependency on this op.
Before any of the ops in self._control_outputs can execute tensorflow will
ensure self has finished executing.
Returns:
A list of `Operation` objects.
"""
control_c_ops = c_api.TF_OperationGetControlOutputs_wrapper(self._c_op)
# pylint: disable=protected-access
return [
self.graph._get_operation_by_name_unsafe(
c_api.TF_OperationName(c_op)) for c_op in control_c_ops
]
# pylint: enable=protected-access
@property
def _control_inputs(self):
logging.warning("Operation._control_inputs is private, use "
"Operation.control_inputs instead. "
"Operation._control_inputs will eventually be removed.")
return self.control_inputs
@_control_inputs.setter
def _control_inputs(self, value):
logging.warning("Operation._control_inputs is private, use "
"Operation.control_inputs instead. "
"Operation._control_inputs will eventually be removed.")
# Copy value because it may be self._control_inputs_val (in particular if
# this is called from self._control_inputs += ...), and we don't want to
# clear value below.
value = copy.copy(value)
self._remove_all_control_inputs()
self._add_control_inputs(value)
@property
def type(self):
"""The type of the op (e.g. `"MatMul"`)."""
return c_api.TF_OperationOpType(self._c_op)
@property
def graph(self):
"""The `Graph` that contains this operation."""
return self._graph
@property
def node_def(self):
# pylint: disable=line-too-long
"""Returns the `NodeDef` representation of this operation.
Returns:
A
[`NodeDef`](https://www.tensorflow.org/code/tensorflow/core/framework/node_def.proto)
protocol buffer.
"""
# pylint: enable=line-too-long
with c_api_util.tf_buffer() as buf:
c_api.TF_OperationToNodeDef(self._c_op, buf)
data = c_api.TF_GetBuffer(buf)
node_def = node_def_pb2.NodeDef()
node_def.ParseFromString(compat.as_bytes(data))
return node_def
@property
def _node_def(self):
logging.warning("Operation._node_def is private, use Operation.node_def "
"instead. Operation._node_def will eventually be removed.")
return self.node_def
@property
def op_def(self):
# pylint: disable=line-too-long
"""Returns the `OpDef` proto that represents the type of this op.
Returns:
An
[`OpDef`](https://www.tensorflow.org/code/tensorflow/core/framework/op_def.proto)
protocol buffer.
"""
# pylint: enable=line-too-long
return self._graph._get_op_def(self.type)
@property
def _op_def(self):
logging.warning("Operation._op_def is private, use Operation.op_def "
"instead. Operation._op_def will eventually be removed.")
return self.op_def
@property
def traceback(self):
"""Returns the call stack from when this operation was constructed."""
return tf_stack.convert_stack(self._traceback)
@property
def traceback_with_start_lines(self):
"""Same as traceback but includes start line of function definition.
Returns:
A list of 5-tuples (filename, lineno, name, code, func_start_lineno).
"""
return tf_stack.convert_stack(self._traceback,
include_func_start_lineno=True)
def _set_attr(self, attr_name, attr_value):
"""Private method used to set an attribute in the node_def."""
buf = c_api.TF_NewBufferFromString(
compat.as_bytes(attr_value.SerializeToString()))
try:
# pylint: disable=protected-access
c_api.SetAttr(self._graph._c_graph, self._c_op, attr_name, buf)
# pylint: enable=protected-access
finally:
c_api.TF_DeleteBuffer(buf)
def get_attr(self, name):
"""Returns the value of the attr of this op with the given `name`.
Args:
name: The name of the attr to fetch.
Returns:
The value of the attr, as a Python object.
Raises:
ValueError: If this op does not have an attr with the given `name`.
"""
fields = ["s", "i", "f", "b", "type", "shape", "tensor", "func"]
try:
with c_api_util.tf_buffer() as buf:
c_api.TF_OperationGetAttrValueProto(self._c_op, name, buf)
data = c_api.TF_GetBuffer(buf)
except errors.InvalidArgumentError as e:
# Convert to ValueError for backwards compatibility.
raise ValueError(str(e))
x = attr_value_pb2.AttrValue()
x.ParseFromString(data)
# Treat an empty oneof value as an empty list.
if not x.WhichOneof("value"):
return []
if x.HasField("list"):
for f in fields:
if getattr(x.list, f):
if f == "type":
return [dtypes.as_dtype(x) for x in list(getattr(x.list, f))]
else:
return list(getattr(x.list, f))
return []
else:
for f in fields:
if x.HasField(f):
if f == "type":
return dtypes.as_dtype(getattr(x, f))
else:
return getattr(x, f)
assert False, "Unsupported field type in " + str(x)
def run(self, feed_dict=None, session=None):
"""Runs this operation in a `Session`.
Calling this method will execute all preceding operations that
produce the inputs needed for this operation.
*N.B.* Before invoking `Operation.run()`, its graph must have been
launched in a session, and either a default session must be
available, or `session` must be specified explicitly.
Args:
feed_dict: A dictionary that maps `Tensor` objects to feed values.
See `tf.Session.run`
for a description of the valid feed values.
session: (Optional.) The `Session` to be used to run to this operation. If
none, the default session will be used.
"""
_run_using_default_session(self, feed_dict, self.graph, session)
_gradient_registry = registry.Registry("gradient")
@tf_export("RegisterGradient")
class RegisterGradient(object):
"""A decorator for registering the gradient function for an op type.
This decorator is only used when defining a new op type. For an op
with `m` inputs and `n` outputs, the gradient function is a function
that takes the original `Operation` and `n` `Tensor` objects
(representing the gradients with respect to each output of the op),
and returns `m` `Tensor` objects (representing the partial gradients
with respect to each input of the op).
For example, assuming that operations of type `"Sub"` take two
inputs `x` and `y`, and return a single output `x - y`, the
following gradient function would be registered:
```python
@tf.RegisterGradient("Sub")
def _sub_grad(unused_op, grad):
return grad, tf.negative(grad)
```
The decorator argument `op_type` is the string type of an
operation. This corresponds to the `OpDef.name` field for the proto
that defines the operation.
"""
def __init__(self, op_type):
"""Creates a new decorator with `op_type` as the Operation type.
Args:
op_type: The string type of an operation. This corresponds to the
`OpDef.name` field for the proto that defines the operation.
"""
if not isinstance(op_type, six.string_types):
raise TypeError("op_type must be a string")
self._op_type = op_type
def __call__(self, f):
"""Registers the function `f` as gradient function for `op_type`."""
_gradient_registry.register(f, self._op_type)
return f
@tf_export("NoGradient", "NotDifferentiable")
def NotDifferentiable(op_type):
"""Specifies that ops of type `op_type` is not differentiable.
This function should *not* be used for operations that have a
well-defined gradient that is not yet implemented.
This function is only used when defining a new op type. It may be
used for ops such as `tf.size()` that are not differentiable. For
example:
```python
tf.NotDifferentiable("Size")
```
The gradient computed for 'op_type' will then propagate zeros.
For ops that have a well-defined gradient but are not yet implemented,
no declaration should be made, and an error *must* be thrown if
an attempt to request its gradient is made.
Args:
op_type: The string type of an operation. This corresponds to the
`OpDef.name` field for the proto that defines the operation.
Raises:
TypeError: If `op_type` is not a string.
"""
if not isinstance(op_type, six.string_types):
raise TypeError("op_type must be a string")
_gradient_registry.register(None, op_type)
# Alias for the old name, will be eventually removed.
NoGradient = NotDifferentiable
def get_gradient_function(op):
"""Returns the function that computes gradients for "op"."""
if not op.inputs:
return None
try:
op_type = op.get_attr("_gradient_op_type")
except ValueError:
op_type = op.type
return _gradient_registry.lookup(op_type)
_shape_registry = registry.Registry("shape functions")
_default_shape_function_registry = registry.Registry("default shape functions")
# These are set to common_shapes.call_cpp_shape_fn by op generated code
# (generated by python_op_gen.cc).
# It is set outside ops.py to avoid a circular dependency.
_call_cpp_shape_fn = None
_call_cpp_shape_fn_and_require_op = None
def _set_call_cpp_shape_fn(call_cpp_shape_fn):
"""Sets default shape fns from passed common_shapes.call_cpp_shape_fn."""
global _call_cpp_shape_fn, _call_cpp_shape_fn_and_require_op
if _call_cpp_shape_fn:
return # already registered
def call_without_requiring(op):
return call_cpp_shape_fn(op, require_shape_fn=False)
_call_cpp_shape_fn = call_without_requiring
def call_with_requiring(op):
return call_cpp_shape_fn(op, require_shape_fn=True)
_call_cpp_shape_fn_and_require_op = call_with_requiring
class RegisterShape(object):
"""No longer used. Was: A decorator for registering a shape function.
Shape functions must now be registered via the SetShapeFn on the
original Op specification in C++.
"""
def __init__(self, op_type):
"""Saves the `op_type` as the `Operation` type."""
if not isinstance(op_type, six.string_types):
raise TypeError("op_type must be a string")
self._op_type = op_type
def __call__(self, f):
"""Registers "f" as the shape function for "op_type"."""
if f is None:
assert _call_cpp_shape_fn
# None is a special "weak" value that provides a default shape function,
# and can be overridden by a non-None registration.
try:
_default_shape_function_registry.register(_call_cpp_shape_fn,
self._op_type)
except KeyError:
# Ignore duplicate registrations of the weak value. This can
# occur if the op library input to wrapper generation
# inadvertently links in one or more of the standard op
# libraries.
pass
else:
_shape_registry.register(f, self._op_type)
return f
# TODO(b/74620627): remove when _USE_C_SHAPES is removed
def _set_shape_and_handle_data_for_outputs_c_api(op):
"""Set shapes and resource handle data using info from the C API."""
assert not _USE_C_SHAPES
for output in op.outputs:
output._shape_val = output._c_api_shape()
# Set the resource handle data for compatibility with the Python shape
# inference code.
serialized = c_api.GetResourceHandleShapeAndType(op._graph._c_graph,
output._as_tf_output())
if serialized:
output._handle_data = (
cpp_shape_inference_pb2.CppShapeInferenceResult.HandleData
.FromString(compat.as_bytes(serialized)))
else:
output._handle_data = None
# TODO(b/74620627): remove when _USE_C_SHAPES is removed
def set_shape_and_handle_data_for_outputs(op):
"""Set the shapes and resource handle data for op's outputs.
When _USE_C_SHAPES = False, this is lazily called when a tensor's shape is
first requested. Usually this should work automatically, but some edge cases
may require manually calling this first to make sure Tensor._shape_val and
Tensor._handle_data are set (e.g. manually overriding _handle_data, copying a
Tensor).
"""
if _USE_C_SHAPES: return
if op.graph._is_function(op.type):
for output in op.outputs:
output._shape_val = tensor_shape.unknown_shape()
return
try:
shape_func = _shape_registry.lookup(op.type)
except LookupError:
try:
shape_func = _default_shape_function_registry.lookup(op.type)
except LookupError:
shape_func = _call_cpp_shape_fn_and_require_op
shapes = shape_func(op)
if shapes is None:
raise RuntimeError(
"Shape function for op %s did not return any shapes" % op)
elif isinstance(shapes, dict):
# Returned by call_cpp_shape_fn
shapes_dict = shapes
shapes = shapes_dict["shapes"]
handle_datas = shapes_dict["handle_data"]
for output, handle_data in zip(op.outputs, handle_datas):
# Don't override any existing handle data that may have been manually set.
# pylint: disable=protected-access
if output._handle_data is None:
output._handle_data = handle_data
# pylint: enable=protected-access
if len(op.outputs) != len(shapes):
raise RuntimeError(
"Shape function for op %s returned %d shapes but expected %d %s %s" %
(op, len(shapes), len(op.outputs), shape_func.__name__, str(shapes)))
for output, s in zip(op.outputs, shapes):
output._shape_val = tensor_shape.unknown_shape()
output._shape_val = output._shape_val.merge_with(s)
class OpStats(object):
"""A holder for statistics about an operator.
This class holds information about the resource requirements for an op,
including the size of its weight parameters on-disk and how many FLOPS it
requires to execute forward inference.
If you define a new operation, you can create a function that will return a
set of information about its usage of the CPU and disk space when serialized.
The function itself takes a Graph object that's been set up so you can call
methods like get_tensor_by_name to help calculate the results, and a NodeDef
argument.
"""
def __init__(self, statistic_type, value=None):
"""Sets up the initial placeholders for the statistics."""
self.statistic_type = statistic_type
self.value = value
@property
def statistic_type(self):
return self._statistic_type
@statistic_type.setter
def statistic_type(self, statistic_type):
self._statistic_type = statistic_type
@property
def value(self):
return self._value
@value.setter
def value(self, value):
self._value = value
def __iadd__(self, other):
if other.statistic_type != self.statistic_type:
raise ValueError("Can't add an OpStat of type %s to one of %s." %
(self.statistic_type, other.statistic_type))
if self.value is None:
self.value = other.value
elif other.value is not None:
self._value += other.value
return self
_stats_registry = registry.Registry("statistical functions")
class RegisterStatistics(object):
"""A decorator for registering the statistics function for an op type.
This decorator can be defined for an op type so that it gives a
report on the resources used by an instance of an operator, in the
form of an OpStats object.
Well-known types of statistics include these so far:
- flops: When running a graph, the bulk of the computation happens doing
numerical calculations like matrix multiplications. This type allows a node
to return how many floating-point operations it takes to complete. The
total number of FLOPs for a graph is a good guide to its expected latency.
You can add your own statistics just by picking a new type string, registering
functions for the ops you care about, and then calling get_stats_for_node_def.
If a statistic for an op is registered multiple times, a KeyError will be
raised.
Since the statistics is counted on a per-op basis. It is not suitable for
model parameters (capacity), which is expected to be counted only once, even
if it is shared by multiple ops. (e.g. RNN)
For example, you can define a new metric called doohickey for a Foo operation
by placing this in your code:
```python
@ops.RegisterStatistics("Foo", "doohickey")
def _calc_foo_bojangles(unused_graph, unused_node_def):
return ops.OpStats("doohickey", 20)
```
Then in client code you can retrieve the value by making this call:
```python
doohickey = ops.get_stats_for_node_def(graph, node_def, "doohickey")
```
If the NodeDef is for an op with a registered doohickey function, you'll get
back the calculated amount in doohickey.value, or None if it's not defined.
"""
def __init__(self, op_type, statistic_type):
"""Saves the `op_type` as the `Operation` type."""
if not isinstance(op_type, six.string_types):
raise TypeError("op_type must be a string.")
if "," in op_type:
raise TypeError("op_type must not contain a comma.")
self._op_type = op_type
if not isinstance(statistic_type, six.string_types):
raise TypeError("statistic_type must be a string.")
if "," in statistic_type:
raise TypeError("statistic_type must not contain a comma.")
self._statistic_type = statistic_type
def __call__(self, f):
"""Registers "f" as the statistics function for "op_type"."""
_stats_registry.register(f, self._op_type + "," + self._statistic_type)
return f
def get_stats_for_node_def(graph, node, statistic_type):
"""Looks up the node's statistics function in the registry and calls it.
This function takes a Graph object and a NodeDef from a GraphDef, and if
there's an associated statistics method, calls it and returns a result. If no
function has been registered for the particular node type, it returns an empty
statistics object.
Args:
graph: A Graph object that's been set up with the node's graph.
node: A NodeDef describing the operator.
statistic_type: A string identifying the statistic we're interested in.
Returns:
An OpStats object containing information about resource usage.
"""
try:
stats_func = _stats_registry.lookup(node.op + "," + statistic_type)
result = stats_func(graph, node)
except LookupError:
result = OpStats(statistic_type)
return result
def _name_from_scope_name(name):
"""Returns the name of an op given the name of its scope.
Args:
name: the name of the scope.
Returns:
the name of the op (equal to scope name minus any trailing slash).
"""
return name[:-1] if (name and name[-1] == "/") else name
_MUTATION_LOCK_GROUP = 0
_SESSION_RUN_LOCK_GROUP = 1
@tf_export("Graph")
class Graph(object):
"""A TensorFlow computation, represented as a dataflow graph.
A `Graph` contains a set of
`tf.Operation` objects,
which represent units of computation; and
`tf.Tensor` objects, which represent
the units of data that flow between operations.
A default `Graph` is always registered, and accessible by calling
`tf.get_default_graph`.
To add an operation to the default graph, simply call one of the functions
that defines a new `Operation`:
```python
c = tf.constant(4.0)
assert c.graph is tf.get_default_graph()
```
Another typical usage involves the
`tf.Graph.as_default`
context manager, which overrides the current default graph for the
lifetime of the context:
```python
g = tf.Graph()
with g.as_default():
# Define operations and tensors in `g`.
c = tf.constant(30.0)
assert c.graph is g
```
Important note: This class *is not* thread-safe for graph construction. All
operations should be created from a single thread, or external
synchronization must be provided. Unless otherwise specified, all methods
are not thread-safe.
A `Graph` instance supports an arbitrary number of "collections"
that are identified by name. For convenience when building a large
graph, collections can store groups of related objects: for
example, the `tf.Variable` uses a collection (named
`tf.GraphKeys.GLOBAL_VARIABLES`) for
all variables that are created during the construction of a graph. The caller
may define additional collections by specifying a new name.
"""
def __init__(self):
"""Creates a new, empty Graph."""
# Protects core state that can be returned via public accessors.
# Thread-safety is provided on a best-effort basis to support buggy
# programs, and is not guaranteed by the public `tf.Graph` API.
#
# NOTE(mrry): This does not protect the various stacks. A warning will
# be reported if these are used from multiple threads
self._lock = threading.RLock()
# The group lock synchronizes Session.run calls with methods that create
# and mutate ops (e.g. Graph.create_op()). This synchronization is
# necessary because it's illegal to modify an operation after it's been run.
# The group lock allows any number of threads to mutate ops at the same time
# but if any modification is going on, all Session.run calls have to wait.
# Similarly, if one or more Session.run calls are going on, all mutate ops
# have to wait until all Session.run calls have finished.
self._group_lock = lock_util.GroupLock(num_groups=2)
self._nodes_by_id = dict() # GUARDED_BY(self._lock)
self._next_id_counter = 0 # GUARDED_BY(self._lock)
self._nodes_by_name = dict() # GUARDED_BY(self._lock)
self._version = 0 # GUARDED_BY(self._lock)
# Maps a name used in the graph to the next id to use for that name.
self._names_in_use = {}
self._stack_state_is_thread_local = False
self._thread_local = threading.local()
# Functions that will be applied to choose a device if none is specified.
# After switch_to_thread_local(), self._thread_local._device_function_stack
# is used instead.
self._graph_device_function_stack = traceable_stack.TraceableStack()
# Default original_op applied to new ops.
self._default_original_op = None
# Current control flow context. It could be either CondContext or
# WhileContext defined in ops/control_flow_ops.py
self._control_flow_context = None
# A new node will depend of the union of all of the nodes in the stack.
# After switch_to_thread_local(),
# self._thread_local._control_dependencies_stack is used instead.
self._graph_control_dependencies_stack = []
# Arbitrary collections of objects.
self._collections = {}
# The graph-level random seed
self._seed = None
# A dictionary of attributes that should be applied to all ops.
self._attr_scope_map = {}
# A map from op type to the kernel label that should be used.
self._op_to_kernel_label_map = {}
# A map from op type to an alternative op type that should be used when
# computing gradients.
self._gradient_override_map = {}
# True if the graph is considered "finalized". In that case no
# new operations can be added.
self._finalized = False
# Functions defined in the graph
self._functions = collections.OrderedDict()
# Default GraphDef versions
self._graph_def_versions = versions_pb2.VersionDef(
producer=versions.GRAPH_DEF_VERSION,
min_consumer=versions.GRAPH_DEF_VERSION_MIN_CONSUMER)
self._building_function = False
# Stack of colocate_with ops. After switch_to_thread_local(),
# self._thread_local._colocation_stack is used instead.
self._graph_colocation_stack = traceable_stack.TraceableStack()
# Set of tensors that are dangerous to feed!
self._unfeedable_tensors = set()
# Set of operations that are dangerous to fetch!
self._unfetchable_ops = set()
# A map of tensor handle placeholder to tensor dtype.
self._handle_feeders = {}
# A map from tensor handle to its read op.
self._handle_readers = {}
# A map from tensor handle to its move op.
self._handle_movers = {}
# A map from tensor handle to its delete op.
self._handle_deleters = {}
# Allow optimizers and other objects to pseudo-uniquely key graphs (this key
# will be shared when defining function graphs, for example, so optimizers
# being called inside function definitions behave as if they were seeing the
# actual outside graph).
self._graph_key = "grap-key-%d/" % (uid(),)
# A string with the last reduction method passed to
# losses.compute_weighted_loss(), or None.
self._last_loss_reduction = None
self._container = ""
self._registered_ops = op_def_registry.get_registered_ops()
# TODO(skyewm): fold as much of the above as possible into the C
# implementation
if self._use_c_api_hack():
self._scoped_c_graph = c_api_util.ScopedTFGraph()
# The C API requires all ops to have shape functions. Disable this
# requirement (many custom ops do not have shape functions, and we don't
# want to break these existing cases).
c_api.SetRequireShapeInferenceFns(self._c_graph, False)
else:
self._scoped_c_graph = None
# TODO(apassos) remove once the C API is used by default.
def _use_c_api_hack(self):
"""Temporary hack; can be overridden to force C API usage."""
return _USE_C_API
# Note: this method is private because the API of tf.Graph() is public and
# frozen, and this functionality is still not ready for public visibility.
@tf_contextlib.contextmanager
def _variable_creator_scope(self, creator):
# This step makes a copy of the existing stack, and it also initializes
# self._thread_local._variable_creator_stack if it doesn't exist yet.
old = list(self._variable_creator_stack)
self._thread_local._variable_creator_stack.append(creator) # pylint: disable=protected-access
try:
yield
finally:
self._thread_local._variable_creator_stack = old # pylint: disable=protected-access
# Note: this method is private because the API of tf.Graph() is public and
# frozen, and this functionality is still not ready for public visibility.
@property
def _variable_creator_stack(self):
if not hasattr(self._thread_local, "_variable_creator_stack"):
self._thread_local._variable_creator_stack = [] # pylint: disable=protected-access
return list(self._thread_local._variable_creator_stack) # pylint: disable=protected-access
@_variable_creator_stack.setter
def _variable_creator_stack(self, variable_creator_stack):
self._thread_local._variable_creator_stack = variable_creator_stack # pylint: disable=protected-access
def _check_not_finalized(self):
"""Check if the graph is finalized.
Raises:
RuntimeError: If the graph finalized.
"""
if self._finalized:
raise RuntimeError("Graph is finalized and cannot be modified.")
def _add_op(self, op):
"""Adds 'op' to the graph.
Args:
op: the Operator or Tensor to add.
Raises:
TypeError: if op is not an Operation or Tensor.
ValueError: if the op.name or op._id are already used.
"""
self._check_not_finalized()
if not isinstance(op, (Tensor, Operation)):
raise TypeError("op must be a Tensor or Operation: %s" % op)
with self._lock:
# pylint: disable=protected-access
if op._id in self._nodes_by_id:
raise ValueError("cannot add an op with id %d as it already "
"exists in the graph" % op._id)
if op.name in self._nodes_by_name:
raise ValueError("cannot add op with name %s as that name "
"is already used" % op.name)
self._nodes_by_id[op._id] = op
self._nodes_by_name[op.name] = op
self._version = max(self._version, op._id)
# pylint: enable=protected-access
@property
def _c_graph(self):
if self._scoped_c_graph:
return self._scoped_c_graph.graph
return None
@property
def version(self):
"""Returns a version number that increases as ops are added to the graph.
Note that this is unrelated to the
`tf.Graph.graph_def_versions`.
Returns:
An integer version that increases as ops are added to the graph.
"""
if self._finalized:
return self._version
with self._lock:
return self._version
@property
def graph_def_versions(self):
# pylint: disable=line-too-long
"""The GraphDef version information of this graph.
For details on the meaning of each version, see
[`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto).
Returns:
A `VersionDef`.
"""
# pylint: enable=line-too-long
with c_api_util.tf_buffer() as buf:
c_api.TF_GraphVersions(self._c_graph, buf)
data = c_api.TF_GetBuffer(buf)
version_def = versions_pb2.VersionDef()
version_def.ParseFromString(compat.as_bytes(data))
return version_def
@property
def seed(self):
"""The graph-level random seed of this graph."""
return self._seed
@seed.setter
def seed(self, seed):
self._seed = seed
@property
def finalized(self):
"""True if this graph has been finalized."""
return self._finalized
def finalize(self):
"""Finalizes this graph, making it read-only.
After calling `g.finalize()`, no new operations can be added to
`g`. This method is used to ensure that no operations are added
to a graph when it is shared between multiple threads, for example
when using a `tf.train.QueueRunner`.
"""
self._finalized = True
def _unsafe_unfinalize(self):
"""Opposite of `finalize`. Internal interface.
NOTE: Unfinalizing a graph could have negative impact on performance,
especially in a multi-threaded environment. Unfinalizing a graph
when it is in use by a Session may lead to undefined behavior. Ensure
that all sessions using a graph are closed before calling this method.
"""
self._finalized = False
def _get_control_flow_context(self):
"""Returns the current control flow context.
Returns:
A context object.
"""
return self._control_flow_context
def _set_control_flow_context(self, ctx):
"""Sets the current control flow context.
Args:
ctx: a context object.
"""
self._control_flow_context = ctx
def _copy_functions_to_graph_def(self, graph_def, starting_bytesize):
"""If this graph contains functions, copy them to `graph_def`."""
bytesize = starting_bytesize
for f in self._functions.values():
bytesize += f.definition.ByteSize()
if bytesize >= (1 << 31) or bytesize < 0:
raise ValueError("GraphDef cannot be larger than 2GB.")
graph_def.library.function.extend([f.definition])
if f.grad_func_name:
grad_def = function_pb2.GradientDef()
grad_def.function_name = f.name
grad_def.gradient_func = f.grad_func_name
graph_def.library.gradient.extend([grad_def])
def _as_graph_def(self, from_version=None, add_shapes=False):
# pylint: disable=line-too-long
"""Returns a serialized `GraphDef` representation of this graph.
The serialized `GraphDef` can be imported into another `Graph`
(using `tf.import_graph_def`) or used with the
[C++ Session API](../../../../api_docs/cc/index.md).
This method is thread-safe.
Args:
from_version: Optional. If this is set, returns a `GraphDef`
containing only the nodes that were added to this graph since
its `version` property had the given value.
add_shapes: If true, adds an "_output_shapes" list attr to each
node with the inferred shapes of each of its outputs.
Returns:
A tuple containing a
[`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto)
protocol buffer, and the version of the graph to which that
`GraphDef` corresponds.
Raises:
ValueError: If the `graph_def` would be too large.
"""
# pylint: enable=line-too-long
with self._lock:
with c_api_util.tf_buffer() as buf:
c_api.TF_GraphToGraphDef(self._c_graph, buf)
data = c_api.TF_GetBuffer(buf)
graph = graph_pb2.GraphDef()
graph.ParseFromString(compat.as_bytes(data))
# Strip the experimental library field iff it's empty.
if not graph.library.function:
graph.ClearField("library")
if add_shapes:
for node in graph.node:
op = self._nodes_by_name[node.name]
if op.outputs:
node.attr["_output_shapes"].list.shape.extend(
[output.get_shape().as_proto() for output in op.outputs])
return graph, self._version
def as_graph_def(self, from_version=None, add_shapes=False):
# pylint: disable=line-too-long
"""Returns a serialized `GraphDef` representation of this graph.
The serialized `GraphDef` can be imported into another `Graph`
(using `tf.import_graph_def`) or used with the
[C++ Session API](../../api_docs/cc/index.md).
This method is thread-safe.
Args:
from_version: Optional. If this is set, returns a `GraphDef`
containing only the nodes that were added to this graph since
its `version` property had the given value.
add_shapes: If true, adds an "_output_shapes" list attr to each
node with the inferred shapes of each of its outputs.
Returns:
A
[`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto)
protocol buffer.
Raises:
ValueError: If the `graph_def` would be too large.
"""
# pylint: enable=line-too-long
result, _ = self._as_graph_def(from_version, add_shapes)
return result
def _is_function(self, name):
"""Tests whether 'name' is registered in this graph's function library.
Args:
name: string op name.
Returns:
bool indicating whether or not 'name' is registered in function library.
"""
return name in self._functions
def _get_function(self, name):
"""Returns the function definition for 'name'.
Args:
name: string function name.
Returns:
The function def proto.
"""
return self._functions.get(name, None)
def _add_function(self, function):
"""Adds a function to the graph.
After the function has been added, you can call to the function by
passing the function name in place of an op name to
`Graph.create_op()`.
Args:
function: A `_DefinedFunction` object.
Raises:
ValueError: if another function is defined with the same name.
"""
name = function.name
# Sanity checks on gradient definition.
if (function.grad_func_name is not None) and (function.python_grad_func is
not None):
raise ValueError("Gradient defined twice for function %s" % name)
# Add function to graph
# pylint: disable=protected-access
# Handle functions created without using the C API. TODO(apassos,skyewm)
# remove this when all functions are generated using the C API by default
# as this will be unnecessary.
if not function._c_func:
serialized = function.definition.SerializeToString()
c_func = c_api.TF_FunctionImportFunctionDef(serialized)
function._c_func = c_api_util.ScopedTFFunction(c_func)
gradient = (function._grad_func._c_func.func if function._grad_func
else None)
c_api.TF_GraphCopyFunction(self._c_graph, function._c_func.func, gradient)
# pylint: enable=protected-access
self._functions[name] = function
# Need a new-enough consumer to support the functions we add to the graph.
if self._graph_def_versions.min_consumer < 12:
self._graph_def_versions.min_consumer = 12
@property
def building_function(self):
"""Returns True iff this graph represents a function."""
return self._building_function
# Helper functions to create operations.
@deprecated_args(None,
"Shapes are always computed; don't use the compute_shapes "
"as it has no effect.", "compute_shapes")
def create_op(
self,
op_type,
inputs,
dtypes, # pylint: disable=redefined-outer-name
input_types=None,
name=None,
attrs=None,
op_def=None,
compute_shapes=True,
compute_device=True):
"""Creates an `Operation` in this graph.
This is a low-level interface for creating an `Operation`. Most
programs will not call this method directly, and instead use the
Python op constructors, such as `tf.constant()`, which add ops to
the default graph.
Args:
op_type: The `Operation` type to create. This corresponds to the
`OpDef.name` field for the proto that defines the operation.
inputs: A list of `Tensor` objects that will be inputs to the `Operation`.
dtypes: A list of `DType` objects that will be the types of the tensors
that the operation produces.
input_types: (Optional.) A list of `DType`s that will be the types of
the tensors that the operation consumes. By default, uses the base
`DType` of each input in `inputs`. Operations that expect
reference-typed inputs must specify `input_types` explicitly.
name: (Optional.) A string name for the operation. If not specified, a
name is generated based on `op_type`.
attrs: (Optional.) A dictionary where the key is the attribute name (a
string) and the value is the respective `attr` attribute of the
`NodeDef` proto that will represent the operation (an `AttrValue`
proto).
op_def: (Optional.) The `OpDef` proto that describes the `op_type` that
the operation will have.
compute_shapes: (Optional.) Deprecated. Has no effect (shapes are always
computed).
compute_device: (Optional.) If True, device functions will be executed
to compute the device property of the Operation.
Raises:
TypeError: if any of the inputs is not a `Tensor`.
ValueError: if colocation conflicts with existing device assignment.
Returns:
An `Operation` object.
"""
del compute_shapes
self._check_not_finalized()
for idx, a in enumerate(inputs):
if not isinstance(a, Tensor):
raise TypeError("Input #%d is not a tensor: %s" % (idx, a))
if name is None:
name = op_type
# If a names ends with a '/' it is a "name scope" and we use it as-is,
# after removing the trailing '/'.
if name and name[-1] == "/":
name = _name_from_scope_name(name)
else:
name = self.unique_name(name)
node_def = _NodeDef(op_type, name, device=None, attrs=attrs)
input_ops = set([t.op for t in inputs])
control_inputs = self._control_dependencies_for_inputs(input_ops)
# _create_op_helper mutates the new Operation. `_mutation_lock` ensures a
# Session.run call cannot occur between creating and mutating the op.
with self._mutation_lock():
ret = Operation(
node_def,
self,
inputs=inputs,
output_types=dtypes,
control_inputs=control_inputs,
input_types=input_types,
original_op=self._default_original_op,
op_def=op_def)
self._create_op_helper(ret, compute_device=compute_device)
return ret
def _create_op_from_tf_operation(self, c_op, compute_device=True):
"""Creates an `Operation` in this graph from the supplied TF_Operation.
This method is like create_op() except the new Operation is constructed
using `c_op`. The returned Operation will have `c_op` as its _c_op
field. This is used to create Operation objects around TF_Operations created
indirectly by the C API (e.g. by TF_ImportGraphDef, TF_FinishWhile).
This function does not call Operation._control_flow_post_processing or
Graph._control_dependencies_for_inputs (since the inputs may not be
available yet). The caller is responsible for calling these methods.
Args:
c_op: a wrapped TF_Operation
compute_device: (Optional.) If True, device functions will be executed
to compute the device property of the Operation.
Returns:
An `Operation` object.
"""
self._check_not_finalized()
ret = Operation(c_op, self)
# If a name_scope was created with ret.name but no nodes were created in it,
# the name will still appear in _names_in_use even though the name hasn't
# been used. This is ok, just leave _names_in_use as-is in this case.
# TODO(skyewm): make the C API guarantee no name conflicts.
name_key = ret.name.lower()
if name_key not in self._names_in_use:
self._names_in_use[name_key] = 1
self._create_op_helper(ret, compute_device=compute_device)
return ret
def _make_colocation_conflict_message(self, op, colocation_op):
"""Return detailed error message about device conflict due to colocation."""
# Example error message:
# Tried to colocate op 'a' (defined at file1.py:149) having device
# '/device:GPU:0' with op 'b' (defined at file2:96) which had an
# incompatible device '/device:CPU:0'.
#
# No node-device colocations were active during op 'a' creation.
# Device assignments active during op 'a' creation:
# with tf.device(/device:GPU:0): file1.py:148>
#
# Node-device colocations active during op 'b' creation:
# with tf.colocate_with(a): file2.py:93>
# Device assignments active during op 'b' creation:
# with tf.device(/cpu:0): file2.py:94
op_info = error_interpolation.compute_field_dict(op)
coloc_op_info = error_interpolation.compute_field_dict(colocation_op)
msg = ("Tried to colocate op '{op_name}'{op_loc} having device '{op_dev}' "
"with op '{coloc_op_name}'{coloc_op_loc} which had an incompatible "
"device '{coloc_op_dev}'.\n\n{op_summary}\n\n{coloc_op_summary}"
.format(op_name=op.name,
op_loc=op_info["defined_at"],
op_dev=op.device,
op_summary=op_info["devs_and_colocs"],
coloc_op_name=colocation_op.name,
coloc_op_loc=coloc_op_info["defined_at"],
coloc_op_dev=colocation_op.device,
coloc_op_summary=coloc_op_info["devs_and_colocs"]))
return msg
def _create_op_helper(self, op, compute_device=True):
"""Common logic for creating an op in this graph."""
# Apply any additional attributes requested. Do not overwrite any existing
# attributes.
for key, value in self._attr_scope_map.items():
try:
op.get_attr(key)
except ValueError:
if callable(value):
value = value(op.node_def)
if not isinstance(value, (type(None), attr_value_pb2.AttrValue)):
raise TypeError(
"Callable for scope map key '%s' must return either None or "
"an AttrValue protocol buffer; but it returned: %s" % (key,
value))
if value:
op._set_attr(key, value) # pylint: disable=protected-access
# Apply a kernel label if one has been specified for this op type.
try:
kernel_label = self._op_to_kernel_label_map[op.type]
op._set_attr("_kernel", # pylint: disable=protected-access
attr_value_pb2.AttrValue(s=compat.as_bytes(kernel_label)))
except KeyError:
pass
# Apply the overriding op type for gradients if one has been specified for
# this op type.
try:
mapped_op_type = self._gradient_override_map[op.type]
op._set_attr("_gradient_op_type", # pylint: disable=protected-access
attr_value_pb2.AttrValue(s=compat.as_bytes(mapped_op_type)))
except KeyError:
pass
self._record_op_seen_by_control_dependencies(op)
if compute_device:
self._apply_device_functions(op)
# Snapshot the colocation stack metadata before we might generate error
# messages using it. Note that this snapshot depends on the actual stack
# and is independent of the op's _class attribute.
# pylint: disable=protected-access
op._colocation_code_locations = self._snapshot_colocation_stack_metadata()
# pylint: enable=protected-access
if self._colocation_stack:
all_colocation_groups = []
for colocation_op in self._colocation_stack.peek_objs():
all_colocation_groups.extend(colocation_op.colocation_groups())
if colocation_op.device:
if (op.device and pydev.canonical_name(op.device) !=
pydev.canonical_name(colocation_op.device)):
msg = self._make_colocation_conflict_message(op, colocation_op)
logging.warning(msg)
else:
op._set_device(colocation_op.device) # pylint: disable=protected-access
all_colocation_groups = sorted(set(all_colocation_groups))
# pylint: disable=protected-access
op._set_attr("_class", attr_value_pb2.AttrValue(
list=attr_value_pb2.AttrValue.ListValue(s=all_colocation_groups)))
# pylint: enable=protected-access
# Sets "container" attribute if
# (1) self._container is not None
# (2) "is_stateful" is set in OpDef
# (3) "container" attribute is in OpDef
# (4) "container" attribute is None
if self._container and op.op_def.is_stateful:
try:
container_attr = op.get_attr("container")
except ValueError:
# "container" attribute is not in OpDef
pass
else:
if not container_attr:
op._set_attr("container", attr_value_pb2.AttrValue( # pylint: disable=protected-access
s=compat.as_bytes(self._container)))
def _add_new_tf_operations(self, compute_devices=True):
"""Creates `Operations` in this graph for any new TF_Operations.
This is useful for when TF_Operations are indirectly created by the C API
outside of the Operation constructor (e.g. by TF_ImportGraphDef,
TF_FinishWhile). This ensures there are corresponding Operations for all
TF_Operations in the underlying TF_Graph.
Args:
compute_devices: (Optional.) If True, device functions will be executed
to compute the device properties of each new Operation.
Returns:
A list of the new `Operation` objects.
"""
# Create all Operation objects before accessing their inputs since an op may
# be created before its inputs.
new_ops = [
self._create_op_from_tf_operation(c_op, compute_device=compute_devices)
for c_op in c_api_util.new_tf_operations(self)
]
# pylint: disable=protected-access
for op in new_ops:
# Operations created by the C API always retrieve shapes from the C API so
# we preserve the shapes of ops created in import_graph_def (from the
# "_output_shapes" attr of the imported NodeDef).
if not _USE_C_SHAPES:
_set_shape_and_handle_data_for_outputs_c_api(op)
new_control_inputs = self._control_dependencies_for_inputs(op.inputs)
op._add_control_inputs(new_control_inputs)
op._control_flow_post_processing()
# pylint: enable=protected-access
return new_ops
def as_graph_element(self, obj, allow_tensor=True, allow_operation=True):
"""Returns the object referred to by `obj`, as an `Operation` or `Tensor`.
This function validates that `obj` represents an element of this
graph, and gives an informative error message if it is not.
This function is the canonical way to get/validate an object of
one of the allowed types from an external argument reference in the
Session API.
This method may be called concurrently from multiple threads.
Args:
obj: A `Tensor`, an `Operation`, or the name of a tensor or operation.
Can also be any object with an `_as_graph_element()` method that returns
a value of one of these types.
allow_tensor: If true, `obj` may refer to a `Tensor`.
allow_operation: If true, `obj` may refer to an `Operation`.
Returns:
The `Tensor` or `Operation` in the Graph corresponding to `obj`.
Raises:
TypeError: If `obj` is not a type we support attempting to convert
to types.
ValueError: If `obj` is of an appropriate type but invalid. For
example, an invalid string.
KeyError: If `obj` is not an object in the graph.
"""
if self._finalized:
return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
with self._lock:
return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
def _as_graph_element_locked(self, obj, allow_tensor, allow_operation):
"""See `Graph.as_graph_element()` for details."""
# The vast majority of this function is figuring
# out what an API user might be doing wrong, so
# that we can give helpful error messages.
#
# Ideally, it would be nice to split it up, but we
# need context to generate nice error messages.
if allow_tensor and allow_operation:
types_str = "Tensor or Operation"
elif allow_tensor:
types_str = "Tensor"
elif allow_operation:
types_str = "Operation"
else:
raise ValueError("allow_tensor and allow_operation can't both be False.")
temp_obj = _as_graph_element(obj)
if temp_obj is not None:
obj = temp_obj
# If obj appears to be a name...
if isinstance(obj, compat.bytes_or_text_types):
name = compat.as_str(obj)
if ":" in name and allow_tensor:
# Looks like a Tensor name and can be a Tensor.
try:
op_name, out_n = name.split(":")
out_n = int(out_n)
except:
raise ValueError("The name %s looks a like a Tensor name, but is "
"not a valid one. Tensor names must be of the "
"form \"<op_name>:<output_index>\"." % repr(name))
if op_name in self._nodes_by_name:
op = self._nodes_by_name[op_name]
else:
raise KeyError("The name %s refers to a Tensor which does not "
"exist. The operation, %s, does not exist in the "
"graph." % (repr(name), repr(op_name)))
try:
return op.outputs[out_n]
except:
raise KeyError("The name %s refers to a Tensor which does not "
"exist. The operation, %s, exists but only has "
"%s outputs." % (repr(name), repr(op_name),
len(op.outputs)))
elif ":" in name and not allow_tensor:
# Looks like a Tensor name but can't be a Tensor.
raise ValueError("Name %s appears to refer to a Tensor, not a %s." %
(repr(name), types_str))
elif ":" not in name and allow_operation:
# Looks like an Operation name and can be an Operation.
if name not in self._nodes_by_name:
raise KeyError("The name %s refers to an Operation not in the "
"graph." % repr(name))
return self._nodes_by_name[name]
elif ":" not in name and not allow_operation:
# Looks like an Operation name but can't be an Operation.
if name in self._nodes_by_name:
# Yep, it's an Operation name
err_msg = ("The name %s refers to an Operation, not a %s." %
(repr(name), types_str))
else:
err_msg = ("The name %s looks like an (invalid) Operation name, "
"not a %s." % (repr(name), types_str))
err_msg += (" Tensor names must be of the form "
"\"<op_name>:<output_index>\".")
raise ValueError(err_msg)
elif isinstance(obj, Tensor) and allow_tensor:
# Actually obj is just the object it's referring to.
if obj.graph is not self:
raise ValueError("Tensor %s is not an element of this graph." % obj)
return obj
elif isinstance(obj, Operation) and allow_operation:
# Actually obj is just the object it's referring to.
if obj.graph is not self:
raise ValueError("Operation %s is not an element of this graph." % obj)
return obj
else:
# We give up!
raise TypeError("Can not convert a %s into a %s." % (type(obj).__name__,
types_str))
def get_operations(self):
"""Return the list of operations in the graph.
You can modify the operations in place, but modifications
to the list such as inserts/delete have no effect on the
list of operations known to the graph.
This method may be called concurrently from multiple threads.
Returns:
A list of Operations.
"""
if self._finalized:
return list(self._nodes_by_id.values())
with self._lock:
return list(self._nodes_by_id.values())
def get_operation_by_name(self, name):
"""Returns the `Operation` with the given `name`.
This method may be called concurrently from multiple threads.
Args:
name: The name of the `Operation` to return.
Returns:
The `Operation` with the given `name`.
Raises:
TypeError: If `name` is not a string.
KeyError: If `name` does not correspond to an operation in this graph.
"""
if not isinstance(name, six.string_types):
raise TypeError("Operation names are strings (or similar), not %s." %
type(name).__name__)
return self.as_graph_element(name, allow_tensor=False, allow_operation=True)
def _get_operation_by_name_unsafe(self, name):
"""Returns the `Operation` with the given `name`.
This is a internal unsafe version of get_operation_by_name. It skips many
checks and does not have user friedly error messages but runs considerably
faster. This method may be called concurrently from multiple threads.
Args:
name: The name of the `Operation` to return.
Returns:
The `Operation` with the given `name`.
Raises:
KeyError: If `name` does not correspond to an operation in this graph.
"""
if self._finalized:
return self._nodes_by_name[name]
with self._lock:
return self._nodes_by_name[name]
def _get_operation_by_tf_operation(self, tf_oper):
op_name = c_api.TF_OperationName(tf_oper)
return self._get_operation_by_name_unsafe(op_name)
def get_tensor_by_name(self, name):
"""Returns the `Tensor` with the given `name`.
This method may be called concurrently from multiple threads.
Args:
name: The name of the `Tensor` to return.
Returns:
The `Tensor` with the given `name`.
Raises:
TypeError: If `name` is not a string.
KeyError: If `name` does not correspond to a tensor in this graph.
"""
# Names should be strings.
if not isinstance(name, six.string_types):
raise TypeError("Tensor names are strings (or similar), not %s." %
type(name).__name__)
return self.as_graph_element(name, allow_tensor=True, allow_operation=False)
def _get_tensor_by_tf_output(self, tf_output):
"""Returns the `Tensor` representing `tf_output`.
Note that there is only one such `Tensor`, i.e. multiple calls to this
function with the same TF_Output value will always return the same `Tensor`
object.
Args:
tf_output: A wrapped `TF_Output` (the C API equivalent of `Tensor`).
Returns:
The `Tensor` that represents `tf_output`.
"""
op = self._get_operation_by_tf_operation(tf_output.oper)
return op.outputs[tf_output.index]
def _next_id(self):
"""Id for next Operation instance. Also increments the internal id."""
self._check_not_finalized()
with self._lock:
self._next_id_counter += 1
return self._next_id_counter
@property
def _last_id(self):
return self._next_id_counter
def _get_op_def(self, type): # pylint: disable=redefined-builtin
"""Returns the `OpDef` proto for `type`. `type` is a string."""
with c_api_util.tf_buffer() as buf:
# pylint: disable=protected-access
c_api.TF_GraphGetOpDef(self._c_graph, compat.as_bytes(type), buf)
# pylint: enable=protected-access
data = c_api.TF_GetBuffer(buf)
op_def = op_def_pb2.OpDef()
op_def.ParseFromString(compat.as_bytes(data))
return op_def
def as_default(self):
"""Returns a context manager that makes this `Graph` the default graph.
This method should be used if you want to create multiple graphs
in the same process. For convenience, a global default graph is
provided, and all ops will be added to this graph if you do not
create a new graph explicitly.
Use this method with the `with` keyword to specify that ops created within
the scope of a block should be added to this graph. In this case, once
the scope of the `with` is exited, the previous default graph is set again
as default. There is a stack, so it's ok to have multiple nested levels
of `as_default` calls.
The default graph is a property of the current thread. If you
create a new thread, and wish to use the default graph in that
thread, you must explicitly add a `with g.as_default():` in that
thread's function.
The following code examples are equivalent:
```python
# 1. Using Graph.as_default():
g = tf.Graph()
with g.as_default():
c = tf.constant(5.0)
assert c.graph is g
# 2. Constructing and making default:
with tf.Graph().as_default() as g:
c = tf.constant(5.0)
assert c.graph is g
```
If eager execution is enabled ops created under this context manager will be
added to the graph instead of executed eagerly.
Returns:
A context manager for using this graph as the default graph.
"""
return _default_graph_stack.get_controller(self)
@property
def collections(self):
"""Returns the names of the collections known to this graph."""
return list(self._collections)
def add_to_collection(self, name, value):
"""Stores `value` in the collection with the given `name`.
Note that collections are not sets, so it is possible to add a value to
a collection several times.
Args:
name: The key for the collection. The `GraphKeys` class
contains many standard names for collections.
value: The value to add to the collection.
""" # pylint: disable=g-doc-exception
self._check_not_finalized()
with self._lock:
if name not in self._collections:
self._collections[name] = [value]
else:
self._collections[name].append(value)
def add_to_collections(self, names, value):
"""Stores `value` in the collections given by `names`.
Note that collections are not sets, so it is possible to add a value to
a collection several times. This function makes sure that duplicates in
`names` are ignored, but it will not check for pre-existing membership of
`value` in any of the collections in `names`.
`names` can be any iterable, but if `names` is a string, it is treated as a
single collection name.
Args:
names: The keys for the collections to add to. The `GraphKeys` class
contains many standard names for collections.
value: The value to add to the collections.
"""
# Make sure names are unique, but treat strings as a single collection name
names = (names,) if isinstance(names, six.string_types) else set(names)
for name in names:
self.add_to_collection(name, value)
def get_collection_ref(self, name):
"""Returns a list of values in the collection with the given `name`.
If the collection exists, this returns the list itself, which can
be modified in place to change the collection. If the collection does
not exist, it is created as an empty list and the list is returned.
This is different from `get_collection()` which always returns a copy of
the collection list if it exists and never creates an empty collection.
Args:
name: The key for the collection. For example, the `GraphKeys` class
contains many standard names for collections.
Returns:
The list of values in the collection with the given `name`, or an empty
list if no value has been added to that collection.
""" # pylint: disable=g-doc-exception
with self._lock:
coll_list = self._collections.get(name, None)
if coll_list is None:
coll_list = []
self._collections[name] = coll_list
return coll_list
def get_collection(self, name, scope=None):
"""Returns a list of values in the collection with the given `name`.
This is different from `get_collection_ref()` which always returns the
actual collection list if it exists in that it returns a new list each time
it is called.
Args:
name: The key for the collection. For example, the `GraphKeys` class
contains many standard names for collections.
scope: (Optional.) A string. If supplied, the resulting list is filtered
to include only items whose `name` attribute matches `scope` using
`re.match`. Items without a `name` attribute are never returned if a
scope is supplied. The choice of `re.match` means that a `scope` without
special tokens filters by prefix.
Returns:
The list of values in the collection with the given `name`, or
an empty list if no value has been added to that collection. The
list contains the values in the order under which they were
collected.
""" # pylint: disable=g-doc-exception
with self._lock:
collection = self._collections.get(name, None)
if collection is None:
return []
if scope is None:
return list(collection)
else:
c = []
regex = re.compile(scope)
for item in collection:
if hasattr(item, "name") and regex.match(item.name):
c.append(item)
return c
def get_all_collection_keys(self):
"""Returns a list of collections used in this graph."""
with self._lock:
return [x for x in self._collections if isinstance(x, six.string_types)]
def clear_collection(self, name):
"""Clears all values in a collection.
Args:
name: The key for the collection. The `GraphKeys` class contains many
standard names for collections.
"""
self._check_not_finalized()
with self._lock:
if name in self._collections:
del self._collections[name]
@tf_contextlib.contextmanager
def _original_op(self, op):
"""Python 'with' handler to help annotate ops with their originator.
An op may have an 'original_op' property that indicates the op on which
it was based. For example a replica op is based on the op that was
replicated and a gradient op is based on the op that was differentiated.
All ops created in the scope of this 'with' handler will have
the given 'op' as their original op.
Args:
op: The Operation that all ops created in this scope will have as their
original op.
Yields:
Nothing.
"""
old_original_op = self._default_original_op
self._default_original_op = op
try:
yield
finally:
self._default_original_op = old_original_op
@property
def _name_stack(self):
# This may be called from a thread where name_stack doesn't yet exist.
if not hasattr(self._thread_local, "_name_stack"):
self._thread_local._name_stack = ""
return self._thread_local._name_stack
@_name_stack.setter
def _name_stack(self, name_stack):
self._thread_local._name_stack = name_stack
# pylint: disable=g-doc-return-or-yield,line-too-long
@tf_contextlib.contextmanager
def name_scope(self, name):
r"""Returns a context manager that creates hierarchical names for operations.
A graph maintains a stack of name scopes. A `with name_scope(...):`
statement pushes a new name onto the stack for the lifetime of the context.
The `name` argument will be interpreted as follows:
* A string (not ending with '/') will create a new name scope, in which
`name` is appended to the prefix of all operations created in the
context. If `name` has been used before, it will be made unique by
calling `self.unique_name(name)`.
* A scope previously captured from a `with g.name_scope(...) as
scope:` statement will be treated as an "absolute" name scope, which
makes it possible to re-enter existing scopes.
* A value of `None` or the empty string will reset the current name scope
to the top-level (empty) name scope.
For example:
```python
with tf.Graph().as_default() as g:
c = tf.constant(5.0, name="c")
assert c.op.name == "c"
c_1 = tf.constant(6.0, name="c")
assert c_1.op.name == "c_1"
# Creates a scope called "nested"
with g.name_scope("nested") as scope:
nested_c = tf.constant(10.0, name="c")
assert nested_c.op.name == "nested/c"
# Creates a nested scope called "inner".
with g.name_scope("inner"):
nested_inner_c = tf.constant(20.0, name="c")
assert nested_inner_c.op.name == "nested/inner/c"
# Create a nested scope called "inner_1".
with g.name_scope("inner"):
nested_inner_1_c = tf.constant(30.0, name="c")
assert nested_inner_1_c.op.name == "nested/inner_1/c"
# Treats `scope` as an absolute name scope, and
# switches to the "nested/" scope.
with g.name_scope(scope):
nested_d = tf.constant(40.0, name="d")
assert nested_d.op.name == "nested/d"
with g.name_scope(""):
e = tf.constant(50.0, name="e")
assert e.op.name == "e"
```
The name of the scope itself can be captured by `with
g.name_scope(...) as scope:`, which stores the name of the scope
in the variable `scope`. This value can be used to name an
operation that represents the overall result of executing the ops
in a scope. For example:
```python
inputs = tf.constant(...)
with g.name_scope('my_layer') as scope:
weights = tf.Variable(..., name="weights")
biases = tf.Variable(..., name="biases")
affine = tf.matmul(inputs, weights) + biases
output = tf.nn.relu(affine, name=scope)
```
NOTE: This constructor validates the given `name`. Valid scope
names match one of the following regular expressions:
[A-Za-z0-9.][A-Za-z0-9_.\\-/]* (for scopes at the root)
[A-Za-z0-9_.\\-/]* (for other scopes)
Args:
name: A name for the scope.
Returns:
A context manager that installs `name` as a new name scope.
Raises:
ValueError: If `name` is not a valid scope name, according to the rules
above.
"""
if name:
if isinstance(name, compat.bytes_or_text_types):
name = compat.as_str(name)
if self._name_stack:
# Scopes created in a nested scope may have initial characters
# that are illegal as the initial character of an op name
# (viz. '-', '\', '/', and '_').
if not _VALID_SCOPE_NAME_REGEX.match(name):
raise ValueError("'%s' is not a valid scope name" % name)
else:
# Scopes created in the root must match the more restrictive
# op name regex, which constrains the initial character.
if not _VALID_OP_NAME_REGEX.match(name):
raise ValueError("'%s' is not a valid scope name" % name)
old_stack = self._name_stack
if not name: # Both for name=None and name="" we re-set to empty scope.
new_stack = None
elif name[-1] == "/":
new_stack = _name_from_scope_name(name)
else:
new_stack = self.unique_name(name)
self._name_stack = new_stack
try:
yield "" if new_stack is None else new_stack + "/"
finally:
self._name_stack = old_stack
# pylint: enable=g-doc-return-or-yield,line-too-long
def unique_name(self, name, mark_as_used=True):
"""Return a unique operation name for `name`.
Note: You rarely need to call `unique_name()` directly. Most of
the time you just need to create `with g.name_scope()` blocks to
generate structured names.
`unique_name` is used to generate structured names, separated by
`"/"`, to help identify operations when debugging a graph.
Operation names are displayed in error messages reported by the
TensorFlow runtime, and in various visualization tools such as
TensorBoard.
If `mark_as_used` is set to `True`, which is the default, a new
unique name is created and marked as in use. If it's set to `False`,
the unique name is returned without actually being marked as used.
This is useful when the caller simply wants to know what the name
to be created will be.
Args:
name: The name for an operation.
mark_as_used: Whether to mark this name as being used.
Returns:
A string to be passed to `create_op()` that will be used
to name the operation being created.
"""
if self._name_stack:
name = self._name_stack + "/" + name
# For the sake of checking for names in use, we treat names as case
# insensitive (e.g. foo = Foo).
name_key = name.lower()
i = self._names_in_use.get(name_key, 0)
# Increment the number for "name_key".
if mark_as_used:
self._names_in_use[name_key] = i + 1
if i > 0:
base_name_key = name_key
# Make sure the composed name key is not already used.
while name_key in self._names_in_use:
name_key = "%s_%d" % (base_name_key, i)
i += 1
# Mark the composed name_key as used in case someone wants
# to call unique_name("name_1").
if mark_as_used:
self._names_in_use[name_key] = 1
# Return the new name with the original capitalization of the given name.
name = "%s_%d" % (name, i-1)
return name
def get_name_scope(self):
"""Returns the current name scope.
For example:
```python
with tf.name_scope('scope1'):
with tf.name_scope('scope2'):
print(tf.get_default_graph().get_name_scope())
```
would print the string `scope1/scope2`.
Returns:
A string representing the current name scope.
"""
return self._name_stack
@tf_contextlib.contextmanager
def _colocate_with_for_gradient(self, op, gradient_uid,
ignore_existing=False):
with self.colocate_with(op, ignore_existing):
if gradient_uid is not None and self._control_flow_context is not None:
self._control_flow_context.EnterGradientColocation(op, gradient_uid)
try:
yield
finally:
self._control_flow_context.ExitGradientColocation(op, gradient_uid)
else:
yield
@tf_contextlib.contextmanager
def colocate_with(self, op, ignore_existing=False):
"""Returns a context manager that specifies an op to colocate with.
Note: this function is not for public use, only for internal libraries.
For example:
```python
a = tf.Variable([1.0])
with g.colocate_with(a):
b = tf.constant(1.0)
c = tf.add(a, b)
```
`b` and `c` will always be colocated with `a`, no matter where `a`
is eventually placed.
**NOTE** Using a colocation scope resets any existing device constraints.
If `op` is `None` then `ignore_existing` must be `True` and the new
scope resets all colocation and device constraints.
Args:
op: The op to colocate all created ops with, or `None`.
ignore_existing: If true, only applies colocation of this op within
the context, rather than applying all colocation properties
on the stack. If `op` is `None`, this value must be `True`.
Raises:
ValueError: if op is None but ignore_existing is False.
Yields:
A context manager that specifies the op with which to colocate
newly created ops.
"""
if op is None and not ignore_existing:
raise ValueError("Trying to reset colocation (op is None) but "
"ignore_existing is not True")
if op is not None and not isinstance(op, Operation):
# We always want to colocate with the reference op.
op = internal_convert_to_tensor_or_indexed_slices(op, as_ref=True).op
# By default, colocate_with resets the device function stack,
# since colocate_with is typically used in specific internal
# library functions where colocation is intended to be "stronger"
# than device functions.
#
# In the future, a caller may specify that device_functions win
# over colocation, in which case we can add support.
device_fn_tmp = self._device_function_stack
self._device_function_stack = traceable_stack.TraceableStack()
if ignore_existing:
current_stack = self._colocation_stack
self._colocation_stack = traceable_stack.TraceableStack()
if op is not None:
# offset refers to the stack frame used for storing code location.
# We use 4, the sum of 1 to use our caller's stack frame and 3
# to jump over layers of context managers above us.
self._colocation_stack.push_obj(op, offset=4)
try:
yield
finally:
# Restore device function stack
self._device_function_stack = device_fn_tmp
if op is not None:
self._colocation_stack.pop_obj()
# Reset the colocation stack if requested.
if ignore_existing:
self._colocation_stack = current_stack
def _add_device_to_stack(self, device_name_or_function, offset=0):
"""Add device to stack manually, separate from a context manager."""
total_offset = 1 + offset
spec = _UserDeviceSpec(device_name_or_function)
self._device_function_stack.push_obj(spec, offset=total_offset)
return spec
@tf_contextlib.contextmanager
def device(self, device_name_or_function):
# pylint: disable=line-too-long
"""Returns a context manager that specifies the default device to use.
The `device_name_or_function` argument may either be a device name
string, a device function, or None:
* If it is a device name string, all operations constructed in
this context will be assigned to the device with that name, unless
overridden by a nested `device()` context.
* If it is a function, it will be treated as a function from
Operation objects to device name strings, and invoked each time
a new Operation is created. The Operation will be assigned to
the device with the returned name.
* If it is None, all `device()` invocations from the enclosing context
will be ignored.
For information about the valid syntax of device name strings, see
the documentation in
[`DeviceNameUtils`](https://www.tensorflow.org/code/tensorflow/core/util/device_name_utils.h).
For example:
```python
with g.device('/device:GPU:0'):
# All operations constructed in this context will be placed
# on GPU 0.
with g.device(None):
# All operations constructed in this context will have no
# assigned device.
# Defines a function from `Operation` to device string.
def matmul_on_gpu(n):
if n.type == "MatMul":
return "/device:GPU:0"
else:
return "/cpu:0"
with g.device(matmul_on_gpu):
# All operations of type "MatMul" constructed in this context
# will be placed on GPU 0; all other operations will be placed
# on CPU 0.
```
**N.B.** The device scope may be overridden by op wrappers or
other library code. For example, a variable assignment op
`v.assign()` must be colocated with the `tf.Variable` `v`, and
incompatible device scopes will be ignored.
Args:
device_name_or_function: The device name or function to use in
the context.
Yields:
A context manager that specifies the default device to use for newly
created ops.
"""
self._add_device_to_stack(device_name_or_function, offset=2)
try:
yield
finally:
self._device_function_stack.pop_obj()
def _apply_device_functions(self, op):
"""Applies the current device function stack to the given operation."""
# Apply any device functions in LIFO order, so that the most recently
# pushed function has the first chance to apply a device to the op.
# We apply here because the result can depend on the Operation's
# signature, which is computed in the Operation constructor.
# pylint: disable=protected-access
for device_spec in self._device_function_stack.peek_objs():
if device_spec.function is None:
break
op._set_device(device_spec.function(op))
op._device_code_locations = self._snapshot_device_function_stack_metadata()
# pylint: enable=protected-access
# pylint: disable=g-doc-return-or-yield
@tf_contextlib.contextmanager
def container(self, container_name):
"""Returns a context manager that specifies the resource container to use.
Stateful operations, such as variables and queues, can maintain their
states on devices so that they can be shared by multiple processes.
A resource container is a string name under which these stateful
operations are tracked. These resources can be released or cleared
with `tf.Session.reset()`.
For example:
```python
with g.container('experiment0'):
# All stateful Operations constructed in this context will be placed
# in resource container "experiment0".
v1 = tf.Variable([1.0])
v2 = tf.Variable([2.0])
with g.container("experiment1"):
# All stateful Operations constructed in this context will be
# placed in resource container "experiment1".
v3 = tf.Variable([3.0])
q1 = tf.FIFOQueue(10, tf.float32)
# All stateful Operations constructed in this context will be
# be created in the "experiment0".
v4 = tf.Variable([4.0])
q1 = tf.FIFOQueue(20, tf.float32)
with g.container(""):
# All stateful Operations constructed in this context will be
# be placed in the default resource container.
v5 = tf.Variable([5.0])
q3 = tf.FIFOQueue(30, tf.float32)
# Resets container "experiment0", after which the state of v1, v2, v4, q1
# will become undefined (such as uninitialized).
tf.Session.reset(target, ["experiment0"])
```
Args:
container_name: container name string.
Returns:
A context manager for defining resource containers for stateful ops,
yields the container name.
"""
original_container = self._container
self._container = container_name
try:
yield self._container
finally:
self._container = original_container
# pylint: enable=g-doc-return-or-yield
class _ControlDependenciesController(object):
"""Context manager for `control_dependencies()`."""
def __init__(self, graph, control_inputs):
"""Create a new `_ControlDependenciesController`.
A `_ControlDependenciesController` is the context manager for
`with tf.control_dependencies()` blocks. These normally nest,
as described in the documentation for `control_dependencies()`.
The `control_inputs` argument list control dependencies that must be
added to the current set of control dependencies. Because of
uniquification the set can be empty even if the caller passed a list of
ops. The special value `None` indicates that we want to start a new
empty set of control dependencies instead of extending the current set.
In that case we also clear the current control flow context, which is an
additional mechanism to add control dependencies.
Args:
graph: The graph that this controller is managing.
control_inputs: List of ops to use as control inputs in addition
to the current control dependencies. None to indicate that
the dependencies should be cleared.
"""
self._graph = graph
if control_inputs is None:
self._control_inputs_val = []
self._new_stack = True
else:
self._control_inputs_val = control_inputs
self._new_stack = False
self._seen_nodes = set()
self._old_stack = None
self._old_control_flow_context = None
# pylint: disable=protected-access
def __enter__(self):
if self._new_stack:
# Clear the control_dependencies graph.
self._old_stack = self._graph._control_dependencies_stack
self._graph._control_dependencies_stack = []
# Clear the control_flow_context too.
self._old_control_flow_context = self._graph._get_control_flow_context()
self._graph._set_control_flow_context(None)
self._graph._push_control_dependencies_controller(self)
def __exit__(self, unused_type, unused_value, unused_traceback):
self._graph._pop_control_dependencies_controller(self)
if self._new_stack:
self._graph._control_dependencies_stack = self._old_stack
self._graph._set_control_flow_context(self._old_control_flow_context)
# pylint: enable=protected-access
@property
def control_inputs(self):
return self._control_inputs_val
def add_op(self, op):
self._seen_nodes.add(op)
def op_in_group(self, op):
return op in self._seen_nodes
def _push_control_dependencies_controller(self, controller):
self._control_dependencies_stack.append(controller)
def _pop_control_dependencies_controller(self, controller):
assert self._control_dependencies_stack[-1] is controller
self._control_dependencies_stack.pop()
def _current_control_dependencies(self):
ret = set()
for controller in self._control_dependencies_stack:
for op in controller.control_inputs:
ret.add(op)
return ret
def _control_dependencies_for_inputs(self, input_ops):
"""For an op that takes `input_ops` as inputs, compute control inputs.
The returned control dependencies should yield an execution that
is equivalent to adding all control inputs in
self._control_dependencies_stack to a newly created op. However,
this function attempts to prune the returned control dependencies
by observing that nodes created within the same `with
control_dependencies(...):` block may have data dependencies that make
the explicit approach redundant.
Args:
input_ops: The data input ops for an op to be created.
Returns:
A list of control inputs for the op to be created.
"""
ret = []
for controller in self._control_dependencies_stack:
# If any of the input_ops already depends on the inputs from controller,
# we say that the new op is dominated (by that input), and we therefore
# do not need to add control dependencies for this controller's inputs.
dominated = False
for op in input_ops:
if controller.op_in_group(op):
dominated = True
break
if not dominated:
# Don't add a control input if we already have a data dependency on i.
# NOTE(mrry): We do not currently track transitive data dependencies,
# so we may add redundant control inputs.
ret.extend([c for c in controller.control_inputs if c not in input_ops])
return ret
def _record_op_seen_by_control_dependencies(self, op):
"""Record that the given op depends on all registered control dependencies.
Args:
op: An Operation.
"""
for controller in self._control_dependencies_stack:
controller.add_op(op)
def control_dependencies(self, control_inputs):
"""Returns a context manager that specifies control dependencies.
Use with the `with` keyword to specify that all operations constructed
within the context should have control dependencies on
`control_inputs`. For example:
```python
with g.control_dependencies([a, b, c]):
# `d` and `e` will only run after `a`, `b`, and `c` have executed.
d = ...
e = ...
```
Multiple calls to `control_dependencies()` can be nested, and in
that case a new `Operation` will have control dependencies on the union
of `control_inputs` from all active contexts.
```python
with g.control_dependencies([a, b]):
# Ops constructed here run after `a` and `b`.
with g.control_dependencies([c, d]):
# Ops constructed here run after `a`, `b`, `c`, and `d`.
```
You can pass None to clear the control dependencies:
```python
with g.control_dependencies([a, b]):
# Ops constructed here run after `a` and `b`.
with g.control_dependencies(None):
# Ops constructed here run normally, not waiting for either `a` or `b`.
with g.control_dependencies([c, d]):
# Ops constructed here run after `c` and `d`, also not waiting
# for either `a` or `b`.
```
*N.B.* The control dependencies context applies *only* to ops that
are constructed within the context. Merely using an op or tensor
in the context does not add a control dependency. The following
example illustrates this point:
```python
# WRONG
def my_func(pred, tensor):
t = tf.matmul(tensor, tensor)
with tf.control_dependencies([pred]):
# The matmul op is created outside the context, so no control
# dependency will be added.
return t
# RIGHT
def my_func(pred, tensor):
with tf.control_dependencies([pred]):
# The matmul op is created in the context, so a control dependency
# will be added.
return tf.matmul(tensor, tensor)
```
Also note that though execution of ops created under this scope will trigger
execution of the dependencies, the ops created under this scope might still
be pruned from a normal tensorflow graph. For example, in the following
snippet of code the dependencies are never executed:
```python
loss = model.loss()
with tf.control_dependencies(dependencies):
loss = loss + tf.constant(1) # note: dependencies ignored in the
# backward pass
return tf.gradients(loss, model.variables)
```
This is because evaluating the gradient graph does not require evaluating
the constant(1) op created in the forward pass.
Args:
control_inputs: A list of `Operation` or `Tensor` objects which
must be executed or computed before running the operations
defined in the context. Can also be `None` to clear the control
dependencies.
Returns:
A context manager that specifies control dependencies for all
operations constructed within the context.
Raises:
TypeError: If `control_inputs` is not a list of `Operation` or
`Tensor` objects.
"""
if control_inputs is None:
return self._ControlDependenciesController(self, None)
# First convert the inputs to ops, and deduplicate them.
# NOTE(mrry): Other than deduplication, we do not currently track direct
# or indirect dependencies between control_inputs, which may result in
# redundant control inputs.
control_ops = []
current = self._current_control_dependencies()
for c in control_inputs:
if isinstance(c, IndexedSlices):
c = c.op
c = self.as_graph_element(c)
if isinstance(c, Tensor):
c = c.op
elif not isinstance(c, Operation):
raise TypeError("Control input must be Operation or Tensor: %s" % c)
if c not in current:
control_ops.append(c)
current.add(c)
return self._ControlDependenciesController(self, control_ops)
# pylint: disable=g-doc-return-or-yield
@tf_contextlib.contextmanager
def _attr_scope(self, attr_map):
"""EXPERIMENTAL: A context manager for setting attributes on operators.
This context manager can be used to add additional
attributes to operators within the scope of the context.
For example:
with ops.Graph().as_default() as g:
f_1 = Foo() # No extra attributes
with g._attr_scope({"_a": tf.attr_value_pb2.AttrValue(b=False)}):
f_2 = Foo() # Additional attribute _a=False
with g._attr_scope({"_a": tf.attr_value_pb2.AttrValue(b=True)}):
f_3 = Foo() # Additional attribute _a=False
with g._attr_scope({"_a": None}):
f_4 = Foo() # No additional attributes.
Args:
attr_map: A dictionary mapping attr name strings to
AttrValue protocol buffers or None.
Returns:
A context manager that sets the kernel label to be used for one or more
ops created in that context.
Raises:
TypeError: If attr_map is not a dictionary mapping
strings to AttrValue protobufs.
"""
if not isinstance(attr_map, dict):
raise TypeError("attr_map must be a dictionary mapping "
"strings to AttrValue protocol buffers")
# The saved_attrs dictionary stores any currently-set labels that
# will be overridden by this context manager.
saved_attrs = {}
# Install the given attribute
for name, attr in attr_map.items():
if not (isinstance(name, six.string_types) and
(isinstance(attr, (type(None), attr_value_pb2.AttrValue)) or
callable(attr))):
raise TypeError("attr_map must be a dictionary mapping "
"strings to AttrValue protocol buffers or "
"callables that emit AttrValue protocol buffers")
try:
saved_attrs[name] = self._attr_scope_map[name]
except KeyError:
pass
if attr is None:
del self._attr_scope_map[name]
else:
self._attr_scope_map[name] = attr
try:
yield # The code within the context runs here.
finally:
# Remove the attributes set for this context, and restore any saved
# attributes.
for name, attr in attr_map.items():
try:
self._attr_scope_map[name] = saved_attrs[name]
except KeyError:
del self._attr_scope_map[name]
# pylint: enable=g-doc-return-or-yield
# pylint: disable=g-doc-return-or-yield
@tf_contextlib.contextmanager
def _kernel_label_map(self, op_to_kernel_label_map):
"""EXPERIMENTAL: A context manager for setting kernel labels.
This context manager can be used to select particular
implementations of kernels within the scope of the context.
For example:
with ops.Graph().as_default() as g:
f_1 = Foo() # Uses the default registered kernel for the Foo op.
with g.kernel_label_map({"Foo": "v_2"}):
f_2 = Foo() # Uses the registered kernel with label "v_2"
# for the Foo op.
with g.kernel_label_map({"Foo": "v_3"}):
f_3 = Foo() # Uses the registered kernel with label "v_3"
# for the Foo op.
with g.kernel_label_map({"Foo": ""}):
f_4 = Foo() # Uses the default registered kernel
# for the Foo op.
Args:
op_to_kernel_label_map: A dictionary mapping op type strings to
kernel label strings.
Returns:
A context manager that sets the kernel label to be used for one or more
ops created in that context.
Raises:
TypeError: If op_to_kernel_label_map is not a dictionary mapping
strings to strings.
"""
if not isinstance(op_to_kernel_label_map, dict):
raise TypeError("op_to_kernel_label_map must be a dictionary mapping "
"strings to strings")
# The saved_labels dictionary stores any currently-set labels that
# will be overridden by this context manager.
saved_labels = {}
# Install the given label
for op_type, label in op_to_kernel_label_map.items():
if not (isinstance(op_type, six.string_types) and
isinstance(label, six.string_types)):
raise TypeError("op_to_kernel_label_map must be a dictionary mapping "
"strings to strings")
try:
saved_labels[op_type] = self._op_to_kernel_label_map[op_type]
except KeyError:
pass
self._op_to_kernel_label_map[op_type] = label
try:
yield # The code within the context runs here.
finally:
# Remove the labels set for this context, and restore any saved labels.
for op_type, label in op_to_kernel_label_map.items():
try:
self._op_to_kernel_label_map[op_type] = saved_labels[op_type]
except KeyError:
del self._op_to_kernel_label_map[op_type]
# pylint: enable=g-doc-return-or-yield
# pylint: disable=g-doc-return-or-yield
@tf_contextlib.contextmanager
def gradient_override_map(self, op_type_map):
"""EXPERIMENTAL: A context manager for overriding gradient functions.
This context manager can be used to override the gradient function
that will be used for ops within the scope of the context.
For example:
```python
@tf.RegisterGradient("CustomSquare")
def _custom_square_grad(op, grad):
# ...
with tf.Graph().as_default() as g:
c = tf.constant(5.0)
s_1 = tf.square(c) # Uses the default gradient for tf.square.
with g.gradient_override_map({"Square": "CustomSquare"}):
s_2 = tf.square(s_2) # Uses _custom_square_grad to compute the
# gradient of s_2.
```
Args:
op_type_map: A dictionary mapping op type strings to alternative op
type strings.
Returns:
A context manager that sets the alternative op type to be used for one
or more ops created in that context.
Raises:
TypeError: If `op_type_map` is not a dictionary mapping strings to
strings.
"""
if not isinstance(op_type_map, dict):
raise TypeError("op_type_map must be a dictionary mapping "
"strings to strings")
# The saved_mappings dictionary stores any currently-set mappings that
# will be overridden by this context manager.
saved_mappings = {}
# Install the given label
for op_type, mapped_op_type in op_type_map.items():
if not (isinstance(op_type, six.string_types) and
isinstance(mapped_op_type, six.string_types)):
raise TypeError("op_type_map must be a dictionary mapping "
"strings to strings")
try:
saved_mappings[op_type] = self._gradient_override_map[op_type]
except KeyError:
pass
self._gradient_override_map[op_type] = mapped_op_type
try:
yield # The code within the context runs here.
finally:
# Remove the labels set for this context, and restore any saved labels.
for op_type, mapped_op_type in op_type_map.items():
try:
self._gradient_override_map[op_type] = saved_mappings[op_type]
except KeyError:
del self._gradient_override_map[op_type]
# pylint: enable=g-doc-return-or-yield
def prevent_feeding(self, tensor):
"""Marks the given `tensor` as unfeedable in this graph."""
self._unfeedable_tensors.add(tensor)
def is_feedable(self, tensor):
"""Returns `True` if and only if `tensor` is feedable."""
return tensor not in self._unfeedable_tensors
def prevent_fetching(self, op):
"""Marks the given `op` as unfetchable in this graph."""
self._unfetchable_ops.add(op)
def is_fetchable(self, tensor_or_op):
"""Returns `True` if and only if `tensor_or_op` is fetchable."""
if isinstance(tensor_or_op, Tensor):
return tensor_or_op.op not in self._unfetchable_ops
else:
return tensor_or_op not in self._unfetchable_ops
def switch_to_thread_local(self):
"""Make device, colocation and dependencies stacks thread-local.
Device, colocation and dependencies stacks are not thread-local be default.
If multiple threads access them, then the state is shared. This means that
one thread may affect the behavior of another thread.
After this method is called, the stacks become thread-local. If multiple
threads access them, then the state is not shared. Each thread uses its own
value; a thread doesn't affect other threads by mutating such a stack.
The initial value for every thread's stack is set to the current value
of the stack when `switch_to_thread_local()` was first called.
"""
if not self._stack_state_is_thread_local:
self._stack_state_is_thread_local = True
@property
def _device_function_stack(self):
if self._stack_state_is_thread_local:
# This may be called from a thread where device_function_stack doesn't yet
# exist.
# pylint: disable=protected-access
if not hasattr(self._thread_local, "_device_function_stack"):
stack_copy_for_this_thread = self._graph_device_function_stack.copy()
self._thread_local._device_function_stack = stack_copy_for_this_thread
return self._thread_local._device_function_stack
# pylint: enable=protected-access
else:
return self._graph_device_function_stack
@property
def _device_functions_outer_to_inner(self):
user_device_specs = self._device_function_stack.peek_objs()
device_functions = [spec.function for spec in user_device_specs]
device_functions_outer_to_inner = list(reversed(device_functions))
return device_functions_outer_to_inner
def _snapshot_device_function_stack_metadata(self):
"""Return device function stack as a list of TraceableObjects.
Returns:
[traceable_stack.TraceableObject, ...] where each TraceableObject's .obj
member is a displayable name for the user's argument to Graph.device, and
the filename and lineno members point to the code location where
Graph.device was called directly or indirectly by the user.
"""
traceable_objects = self._device_function_stack.peek_traceable_objs()
snapshot = []
for obj in traceable_objects:
obj_copy = obj.copy_metadata()
obj_copy.obj = obj.obj.display_name
snapshot.append(obj_copy)
return snapshot
@_device_function_stack.setter
def _device_function_stack(self, device_function_stack):
if self._stack_state_is_thread_local:
# pylint: disable=protected-access
self._thread_local._device_function_stack = device_function_stack
# pylint: enable=protected-access
else:
self._graph_device_function_stack = device_function_stack
@property
def _colocation_stack(self):
"""Return thread-local copy of colocation stack."""
if self._stack_state_is_thread_local:
# This may be called from a thread where colocation_stack doesn't yet
# exist.
# pylint: disable=protected-access
if not hasattr(self._thread_local, "_colocation_stack"):
stack_copy_for_this_thread = self._graph_colocation_stack.copy()
self._thread_local._colocation_stack = stack_copy_for_this_thread
return self._thread_local._colocation_stack
# pylint: enable=protected-access
else:
return self._graph_colocation_stack
def _snapshot_colocation_stack_metadata(self):
"""Return colocation stack metadata as a dictionary."""
traceable_objects = self._colocation_stack.peek_traceable_objs()
return {obj.obj.name: obj.copy_metadata() for obj in traceable_objects}
@_colocation_stack.setter
def _colocation_stack(self, colocation_stack):
if self._stack_state_is_thread_local:
# pylint: disable=protected-access
self._thread_local._colocation_stack = colocation_stack
# pylint: enable=protected-access
else:
self._graph_colocation_stack = colocation_stack
@property
def _control_dependencies_stack(self):
if self._stack_state_is_thread_local:
# This may be called from a thread where control_dependencies_stack
# doesn't yet exist.
if not hasattr(self._thread_local, "_control_dependencies_stack"):
self._thread_local._control_dependencies_stack = (
self._graph_control_dependencies_stack[:])
return self._thread_local._control_dependencies_stack
else:
return self._graph_control_dependencies_stack
@_control_dependencies_stack.setter
def _control_dependencies_stack(self, control_dependencies):
if self._stack_state_is_thread_local:
self._thread_local._control_dependencies_stack = control_dependencies
else:
self._graph_control_dependencies_stack = control_dependencies
@property
def _distribution_strategy_stack(self):
"""A stack to maintain distribution strategy context for each thread."""
if not hasattr(self._thread_local, "_distribution_strategy_stack"):
self._thread_local._distribution_strategy_stack = [] # pylint: disable=protected-access
return self._thread_local._distribution_strategy_stack # pylint: disable=protected-access
@_distribution_strategy_stack.setter
def _distribution_strategy_stack(self, _distribution_strategy_stack):
self._thread_local._distribution_strategy_stack = ( # pylint: disable=protected-access
_distribution_strategy_stack)
def _mutation_lock(self):
"""Returns a lock to guard code that creates & mutates ops.
See the comment for self._group_lock for more info.
"""
return self._group_lock.group(_MUTATION_LOCK_GROUP)
def _session_run_lock(self):
"""Returns a lock to guard code for Session.run.
See the comment for self._group_lock for more info.
"""
return self._group_lock.group(_SESSION_RUN_LOCK_GROUP)
# TODO(agarwal): currently device directives in an outer eager scope will not
# apply to inner graph mode code. Fix that.
@tf_export("device")
def device(device_name_or_function):
"""Wrapper for `Graph.device()` using the default graph.
See
`tf.Graph.device`
for more details.
Args:
device_name_or_function: The device name or function to use in
the context.
Returns:
A context manager that specifies the default device to use for newly
created ops.
Raises:
RuntimeError: If eager execution is enabled and a function is passed in.
"""
if context.executing_eagerly():
# TODO(agarwal): support device functions in EAGER mode.
if callable(device_name_or_function):
raise RuntimeError(
"tf.device does not support functions when eager execution "
"is enabled.")
return context.device(device_name_or_function)
else:
return get_default_graph().device(device_name_or_function)
@tf_export("container")
def container(container_name):
"""Wrapper for `Graph.container()` using the default graph.
Args:
container_name: The container string to use in the context.
Returns:
A context manager that specifies the default container to use for newly
created stateful ops.
"""
return get_default_graph().container(container_name)
def _colocate_with_for_gradient(op, gradient_uid, ignore_existing=False):
if context.executing_eagerly():
if op is not None:
return device(op.device)
else:
return _NullContextmanager()
else:
default_graph = get_default_graph()
if isinstance(op, EagerTensor):
if default_graph.building_function:
return default_graph.device(op.device)
else:
raise ValueError("Encountered an Eager-defined Tensor during graph "
"construction, but a function was not being built.")
return default_graph._colocate_with_for_gradient(
op, gradient_uid=gradient_uid, ignore_existing=ignore_existing)
@tf_export("colocate_with")
def colocate_with(op, ignore_existing=False):
return _colocate_with_for_gradient(op, None, ignore_existing=ignore_existing)
@tf_export("control_dependencies")
def control_dependencies(control_inputs):
"""Wrapper for `Graph.control_dependencies()` using the default graph.
See `tf.Graph.control_dependencies`
for more details.
When eager execution is enabled, any callable object in the `control_inputs`
list will be called.
Args:
control_inputs: A list of `Operation` or `Tensor` objects which
must be executed or computed before running the operations
defined in the context. Can also be `None` to clear the control
dependencies. If eager execution is enabled, any callable object in the
`control_inputs` list will be called.
Returns:
A context manager that specifies control dependencies for all
operations constructed within the context.
"""
if context.executing_eagerly():
if control_inputs:
# Excute any pending callables.
for control in control_inputs:
if callable(control):
control()
return _NullContextmanager()
else:
return get_default_graph().control_dependencies(control_inputs)
class _DefaultStack(threading.local):
"""A thread-local stack of objects for providing implicit defaults."""
def __init__(self):
super(_DefaultStack, self).__init__()
self._enforce_nesting = True
self.stack = []
def get_default(self):
return self.stack[-1] if len(self.stack) >= 1 else None
def reset(self):
self.stack = []
def is_cleared(self):
return not self.stack
@property
def enforce_nesting(self):
return self._enforce_nesting
@enforce_nesting.setter
def enforce_nesting(self, value):
self._enforce_nesting = value
@tf_contextlib.contextmanager
def get_controller(self, default):
"""A context manager for manipulating a default stack."""
self.stack.append(default)
try:
yield default
finally:
# stack may be empty if reset() was called
if self.stack:
if self._enforce_nesting:
if self.stack[-1] is not default:
raise AssertionError(
"Nesting violated for default stack of %s objects" %
type(default))
self.stack.pop()
else:
self.stack.remove(default)
_default_session_stack = _DefaultStack() # pylint: disable=protected-access
def default_session(session):
"""Python "with" handler for defining a default session.
This function provides a means of registering a session for handling
Tensor.eval() and Operation.run() calls. It is primarily intended for use
by session.Session, but can be used with any object that implements
the Session.run() interface.
Use with the "with" keyword to specify that Tensor.eval() and Operation.run()
invocations within the scope of a block should be executed by a particular
session.
The default session applies to the current thread only, so it is always
possible to inspect the call stack and determine the scope of a default
session. If you create a new thread, and wish to use the default session
in that thread, you must explicitly add a "with ops.default_session(sess):"
block in that thread's function.
Example:
The following code examples are equivalent:
# 1. Using the Session object directly:
sess = ...
c = tf.constant(5.0)
sess.run(c)
# 2. Using default_session():
sess = ...
with ops.default_session(sess):
c = tf.constant(5.0)
result = c.eval()
# 3. Overriding default_session():
sess = ...
with ops.default_session(sess):
c = tf.constant(5.0)
with ops.default_session(...):
c.eval(session=sess)
Args:
session: The session to be installed as the default session.
Returns:
A context manager for the default session.
"""
return _default_session_stack.get_controller(session)
@tf_export("get_default_session")
def get_default_session():
"""Returns the default session for the current thread.
The returned `Session` will be the innermost session on which a
`Session` or `Session.as_default()` context has been entered.
NOTE: The default session is a property of the current thread. If you
create a new thread, and wish to use the default session in that
thread, you must explicitly add a `with sess.as_default():` in that
thread's function.
Returns:
The default `Session` being used in the current thread.
"""
return _default_session_stack.get_default()
def _eval_using_default_session(tensors, feed_dict, graph, session=None):
"""Uses the default session to evaluate one or more tensors.
Args:
tensors: A single Tensor, or a list of Tensor objects.
feed_dict: A dictionary that maps Tensor objects (or tensor names) to lists,
numpy ndarrays, TensorProtos, or strings.
graph: The graph in which the tensors are defined.
session: (Optional) A different session to use to evaluate "tensors".
Returns:
Either a single numpy ndarray if "tensors" is a single tensor; or a list
of numpy ndarrays that each correspond to the respective element in
"tensors".
Raises:
ValueError: If no default session is available; the default session
does not have "graph" as its graph; or if "session" is specified,
and it does not have "graph" as its graph.
"""
if session is None:
session = get_default_session()
if session is None:
raise ValueError("Cannot evaluate tensor using `eval()`: No default "
"session is registered. Use `with "
"sess.as_default()` or pass an explicit session to "
"`eval(session=sess)`")
if session.graph is not graph:
raise ValueError("Cannot use the default session to evaluate tensor: "
"the tensor's graph is different from the session's "
"graph. Pass an explicit session to "
"`eval(session=sess)`.")
else:
if session.graph is not graph:
raise ValueError("Cannot use the given session to evaluate tensor: "
"the tensor's graph is different from the session's "
"graph.")
return session.run(tensors, feed_dict)
def _run_using_default_session(operation, feed_dict, graph, session=None):
"""Uses the default session to run "operation".
Args:
operation: The Operation to be run.
feed_dict: A dictionary that maps Tensor objects (or tensor names) to lists,
numpy ndarrays, TensorProtos, or strings.
graph: The graph in which "operation" is defined.
session: (Optional) A different session to use to run "operation".
Raises:
ValueError: If no default session is available; the default session
does not have "graph" as its graph; or if "session" is specified,
and it does not have "graph" as its graph.
"""
if session is None:
session = get_default_session()
if session is None:
raise ValueError("Cannot execute operation using `run()`: No default "
"session is registered. Use `with "
"sess.as_default():` or pass an explicit session to "
"`run(session=sess)`")
if session.graph is not graph:
raise ValueError("Cannot use the default session to execute operation: "
"the operation's graph is different from the "
"session's graph. Pass an explicit session to "
"run(session=sess).")
else:
if session.graph is not graph:
raise ValueError("Cannot use the given session to execute operation: "
"the operation's graph is different from the session's "
"graph.")
session.run(operation, feed_dict)
class _DefaultGraphStack(_DefaultStack): # pylint: disable=protected-access
"""A thread-local stack of objects for providing an implicit default graph."""
def __init__(self):
super(_DefaultGraphStack, self).__init__()
self._global_default_graph = None
def get_default(self):
"""Override that returns a global default if the stack is empty."""
ret = super(_DefaultGraphStack, self).get_default()
if ret is None:
ret = self._GetGlobalDefaultGraph()
return ret
def _GetGlobalDefaultGraph(self):
if self._global_default_graph is None:
# TODO(mrry): Perhaps log that the default graph is being used, or set
# provide some other feedback to prevent confusion when a mixture of
# the global default graph and an explicit graph are combined in the
# same process.
self._global_default_graph = Graph()
return self._global_default_graph
def reset(self):
super(_DefaultGraphStack, self).reset()
self._global_default_graph = None
@tf_contextlib.contextmanager
def get_controller(self, default):
context.context().context_switches.push(
default.building_function, default.as_default)
try:
with super(_DefaultGraphStack, self).get_controller(
default) as g, context.graph_mode():
yield g
finally:
# If an exception is raised here it may be hiding a related exception in
# the try-block (just above).
context.context().context_switches.pop()
_default_graph_stack = _DefaultGraphStack()
# pylint: disable=g-doc-return-or-yield,line-too-long
@tf_contextlib.contextmanager
def init_scope():
"""A context manager that lifts ops out of control-flow scopes and function-building graphs.
There is often a need to lift variable initialization ops out of control-flow
scopes, function-building graphs, and gradient tapes. Entering an
`init_scope` is a mechanism for satisfying these desiderata. In particular,
entering an `init_scope` has three effects:
(1) All control dependencies are cleared the moment the scope is entered;
this is equivalent to entering the context manager returned from
`control_dependencies(None)`, which has the side-effect of exiting
control-flow scopes like `tf.cond` and `tf.while_loop`.
(2) All operations that are created while the scope is active are lifted
into the lowest context on the `context_stack` that is not building a
graph function. Here, a context is defined as either a graph or an eager
context. Every context switch, i.e., every installation of a graph as
the default graph and every switch into eager mode, is logged in a
thread-local stack called `context_switches`; the log entry for a
context switch is popped from the stack when the context is exited.
Entering an `init_scope` is equivalent to crawling up
`context_switches`, finding the first context that is not building a
graph function, and entering it. A caveat is that if graph mode is
enabled but the default graph stack is empty, then entering an
`init_scope` will simply install a fresh graph as the default one.
(3) The gradient tape is paused while the scope is active.
Raises:
RuntimeError: if graph state is incompatible with this initialization.
"""
# pylint: enable=g-doc-return-or-yield,line-too-long
if context.executing_eagerly():
# Fastpath.
with tape.stop_recording():
yield
else:
# Retrieve the active name scope: entering an `init_scope` preserves
# the name scope of the current context.
default_graph = get_default_graph()
scope = default_graph.get_name_scope()
if scope and scope[-1] != "/":
# Names that end with trailing slashes are treated by `name_scope` as
# absolute.
scope = scope + "/"
inner_device_stack = default_graph._device_function_stack # pylint: disable=protected-access
outer_context = None
if not _default_graph_stack.stack:
# If the default graph stack is empty, then we cannot be building a
# function. Install the global graph (which, in this case, is also the
# default graph) as the outer context.
if default_graph.building_function:
raise RuntimeError("The global graph is building a function.")
outer_context = default_graph.as_default
else:
# Find a context that is not building a function.
for stack_entry in reversed(context.context().context_switches.stack):
if not stack_entry.is_building_function:
outer_context = stack_entry.enter_context_fn
break
if outer_context is None:
# As a last resort, obtain the global default graph; this graph doesn't
# necessarily live on the graph stack (and hence it doesn't necessarily
# live on the context stack), but it is stored in the graph stack's
# encapsulating object.
outer_context = _default_graph_stack._GetGlobalDefaultGraph().as_default # pylint: disable=protected-access
if outer_context is None:
# Sanity check; this shouldn't be triggered.
raise RuntimeError("All graphs are building functions, and no "
"eager context was previously active.")
outer_graph = None
outer_device_stack = None
try:
with outer_context(), name_scope(scope), control_dependencies(
None), tape.stop_recording():
if not context.executing_eagerly():
# The device stack is preserved when lifting into a graph. Eager
# execution doesn't implement device stacks and in particular it
# doesn't support device functions, so in general it's not possible
# to do the same when lifting into the eager context.
outer_graph = get_default_graph()
outer_device_stack = outer_graph._device_function_stack # pylint: disable=protected-access
outer_graph._device_function_stack = inner_device_stack # pylint: disable=protected-access
yield
finally:
# If an exception is raised here it may be hiding a related exception in
# try-block (just above).
if outer_graph is not None:
outer_graph._device_function_stack = outer_device_stack # pylint: disable=protected-access
@tf_export("enable_eager_execution")
def enable_eager_execution(config=None,
device_policy=None,
execution_mode=None):
"""Enables eager execution for the lifetime of this program.
Eager execution provides an imperative interface to TensorFlow. With eager
execution enabled, TensorFlow functions execute operations immediately (as
opposed to adding to a graph to be executed later in a `tf.Session`) and
return concrete values (as opposed to symbolic references to a node in a
computational graph).
For example:
```python
tf.enable_eager_execution()
# After eager execution is enabled, operations are executed as they are
# defined and Tensor objects hold concrete values, which can be accessed as
# numpy.ndarray`s through the numpy() method.
assert tf.multiply(6, 7).numpy() == 42
```
Eager execution cannot be enabled after TensorFlow APIs have been used to
create or execute graphs. It is typically recommended to invoke this function
at program startup and not in a library (as most libraries should be usable
both with and without eager execution).
Args:
config: (Optional.) A `tf.ConfigProto` to use to configure the environment
in which operations are executed. Note that `tf.ConfigProto` is also
used to configure graph execution (via `tf.Session`) and many options
within `tf.ConfigProto` are not implemented (or are irrelevant) when
eager execution is enabled.
device_policy: (Optional.) Policy controlling how operations requiring
inputs on a specific device (e.g., a GPU 0) handle inputs on a different
device (e.g. GPU 1 or CPU). When set to None, an appropriate value will be
picked automatically. The value picked may change between TensorFlow
releases.
Valid values:
- tf.contrib.eager.DEVICE_PLACEMENT_EXPLICIT: raises an error if the
placement is not correct.
- tf.contrib.eager.DEVICE_PLACEMENT_WARN: copies the tensors which are not
on the right device but logs a warning.
- tf.contrib.eager.DEVICE_PLACEMENT_SILENT: silently copies the tensors.
Note that this may hide performance problems as there is no notification
provided when operations are blocked on the tensor being copied between
devices.
- tf.contrib.eager.DEVICE_PLACEMENT_SILENT_FOR_INT32: silently copies
int32 tensors, raising errors on the other ones.
execution_mode: (Optional.) Policy controlling how operations dispatched are
actually executed. When set to None, an appropriate value will be picked
automatically. The value picked may change between TensorFlow releases.
Valid values:
- tf.contrib.eager.SYNC: executes each operation synchronously.
- tf.contrib.eager.ASYNC: executes each operation asynchronously. These
operations may return "non-ready" handles.
Raises:
ValueError: If eager execution is enabled after creating/executing a
TensorFlow graph, or if options provided conflict with a previous call
to this function.
"""
return enable_eager_execution_internal(
config=config,
device_policy=device_policy,
execution_mode=execution_mode,
server_def=None)
def enable_eager_execution_internal(config=None,
device_policy=None,
execution_mode=None,
server_def=None):
"""Enables eager execution for the lifetime of this program.
Most of the doc string for enable_eager_execution is relevant here as well.
Args:
config: See enable_eager_execution doc string
device_policy: See enable_eager_execution doc string
execution_mode: See enable_eager_execution doc string
server_def: (Optional.) A tensorflow::ServerDef proto.
Enables execution on remote devices. GrpcServers need to be started by
creating an identical server_def to this, and setting the appropriate
task_indexes, so that the servers can communicate. It will then be
possible to execute operations on remote devices.
Raises:
ValueError
"""
if config is not None and not isinstance(config, config_pb2.ConfigProto):
raise TypeError(
"config must be a tf.ConfigProto, but got %s" % type(config))
if device_policy not in (None, context.DEVICE_PLACEMENT_EXPLICIT,
context.DEVICE_PLACEMENT_WARN,
context.DEVICE_PLACEMENT_SILENT,
context.DEVICE_PLACEMENT_SILENT_FOR_INT32):
raise ValueError(
"device_policy must be one of None, tf.contrib.eager.DEVICE_PLACEMENT_*"
)
if execution_mode not in (None, context.SYNC, context.ASYNC):
raise ValueError(
"execution_mode must be one of None, tf.contrib.eager.SYNC, "
"tf.contrib.eager.ASYNC")
# pylint: disable=protected-access
if context._default_mode == context.GRAPH_MODE:
graph_mode_has_been_used = (
_default_session_stack.stack
or len(get_default_graph().get_operations()) > 0) # pylint: disable=g-explicit-length-test
if graph_mode_has_been_used:
raise ValueError(
"tf.enable_eager_execution must be called at program startup.")
context._default_mode = context.EAGER_MODE
if context._context is None:
context._context = context.Context(
config=config,
device_policy=device_policy,
execution_mode=execution_mode,
server_def=server_def)
elif ((config is not None and config is not context._context._config) or
(device_policy is not None and
device_policy is not context._context._device_policy) or
(execution_mode is not None and
execution_mode is not context._context._execution_mode)):
raise ValueError("Trying to change the options of an active eager"
" execution. Context config: %s, specified config:"
" %s. Context device policy: %s, specified device"
" policy: %s. Context execution mode: %s, "
" specified execution mode %s." %
(context._context._config, config,
context._context._device_policy, device_policy,
context._context._execution_mode, execution_mode))
else:
raise ValueError(
"tf.enable_eager_execution must be called at program startup.")
# Monkey patch to get rid of an unnecessary conditional since the context is
# now initialized.
context.context = context.context_safe
def eager_run(main=None, argv=None):
"""Runs the program with an optional main function and argv list.
The program will run with eager execution enabled.
Example:
```python
import tensorflow as tf
# Import subject to future changes:
from tensorflow.contrib.eager.python import tfe
def main(_):
u = tf.constant(6.0)
v = tf.constant(7.0)
print(u * v)
if __name__ == "__main__":
tfe.run()
```
Args:
main: the main function to run.
argv: the arguments to pass to it.
"""
enable_eager_execution()
app.run(main, argv)
@tf_export("reset_default_graph")
def reset_default_graph():
"""Clears the default graph stack and resets the global default graph.
NOTE: The default graph is a property of the current thread. This
function applies only to the current thread. Calling this function while
a `tf.Session` or `tf.InteractiveSession` is active will result in undefined
behavior. Using any previously created `tf.Operation` or `tf.Tensor` objects
after calling this function will result in undefined behavior.
Raises:
AssertionError: If this function is called within a nested graph.
"""
if not _default_graph_stack.is_cleared():
raise AssertionError("Do not use tf.reset_default_graph() to clear "
"nested graphs. If you need a cleared graph, "
"exit the nesting and create a new graph.")
_default_graph_stack.reset()
@tf_export("get_default_graph")
def get_default_graph():
"""Returns the default graph for the current thread.
The returned graph will be the innermost graph on which a
`Graph.as_default()` context has been entered, or a global default
graph if none has been explicitly created.
NOTE: The default graph is a property of the current thread. If you
create a new thread, and wish to use the default graph in that
thread, you must explicitly add a `with g.as_default():` in that
thread's function.
Returns:
The default `Graph` being used in the current thread.
"""
return _default_graph_stack.get_default()
def has_default_graph():
"""Returns True if there is a default graph."""
return len(_default_graph_stack.stack) >= 1
def get_name_scope():
"""Returns the current name scope in the default_graph.
For example:
```python
with tf.name_scope('scope1'):
with tf.name_scope('scope2'):
print(tf.get_name_scope())
```
would print the string `scope1/scope2`.
Returns:
A string representing the current name scope.
"""
if context.executing_eagerly():
return context.context().scope_name.rstrip("/")
return get_default_graph().get_name_scope()
def _assert_same_graph(original_item, item):
"""Fail if the 2 items are from different graphs.
Args:
original_item: Original item to check against.
item: Item to check.
Raises:
ValueError: if graphs do not match.
"""
if original_item.graph is not item.graph:
raise ValueError("%s must be from the same graph as %s." % (item,
original_item))
def _get_graph_from_inputs(op_input_list, graph=None):
"""Returns the appropriate graph to use for the given inputs.
This library method provides a consistent algorithm for choosing the graph
in which an Operation should be constructed:
1. If the default graph is being used to construct a function, we
use the default graph.
2. If the "graph" is specified explicitly, we validate that all of the inputs
in "op_input_list" are compatible with that graph.
3. Otherwise, we attempt to select a graph from the first Operation-
or Tensor-valued input in "op_input_list", and validate that all other
such inputs are in the same graph.
4. If the graph was not specified and it could not be inferred from
"op_input_list", we attempt to use the default graph.
Args:
op_input_list: A list of inputs to an operation, which may include `Tensor`,
`Operation`, and other objects that may be converted to a graph element.
graph: (Optional) The explicit graph to use.
Raises:
TypeError: If op_input_list is not a list or tuple, or if graph is not a
Graph.
ValueError: If a graph is explicitly passed and not all inputs are from it,
or if the inputs are from multiple graphs, or we could not find a graph
and there was no default graph.
Returns:
The appropriate graph to use for the given inputs.
"""
if get_default_graph().building_function:
return get_default_graph()
op_input_list = tuple(op_input_list) # Handle generators correctly
if graph and not isinstance(graph, Graph):
raise TypeError("Input graph needs to be a Graph: %s" % graph)
# 1. We validate that all of the inputs are from the same graph. This is
# either the supplied graph parameter, or the first one selected from one
# the graph-element-valued inputs. In the latter case, we hold onto
# that input in original_graph_element so we can provide a more
# informative error if a mismatch is found.
original_graph_element = None
for op_input in op_input_list:
# Determine if this is a valid graph_element.
# TODO(josh11b): Note that we exclude subclasses of Tensor. Need to clean this
# up.
graph_element = None
if (isinstance(op_input, (Operation, _TensorLike)) and
((not isinstance(op_input, Tensor)) or type(op_input) == Tensor)): # pylint: disable=unidiomatic-typecheck
graph_element = op_input
else:
graph_element = _as_graph_element(op_input)
if graph_element is not None:
if not graph:
original_graph_element = graph_element
graph = graph_element.graph
elif original_graph_element is not None:
_assert_same_graph(original_graph_element, graph_element)
elif graph_element.graph is not graph:
raise ValueError("%s is not from the passed-in graph." % graph_element)
# 2. If all else fails, we use the default graph, which is always there.
return graph or get_default_graph()
@tf_export("GraphKeys")
class GraphKeys(object):
"""Standard names to use for graph collections.
The standard library uses various well-known names to collect and
retrieve values associated with a graph. For example, the
`tf.Optimizer` subclasses default to optimizing the variables
collected under `tf.GraphKeys.TRAINABLE_VARIABLES` if none is
specified, but it is also possible to pass an explicit list of
variables.
The following standard keys are defined:
* `GLOBAL_VARIABLES`: the default collection of `Variable` objects, shared
across distributed environment (model variables are subset of these). See
`tf.global_variables`
for more details.
Commonly, all `TRAINABLE_VARIABLES` variables will be in `MODEL_VARIABLES`,
and all `MODEL_VARIABLES` variables will be in `GLOBAL_VARIABLES`.
* `LOCAL_VARIABLES`: the subset of `Variable` objects that are local to each
machine. Usually used for temporarily variables, like counters.
Note: use `tf.contrib.framework.local_variable` to add to this collection.
* `MODEL_VARIABLES`: the subset of `Variable` objects that are used in the
model for inference (feed forward). Note: use
`tf.contrib.framework.model_variable` to add to this collection.
* `TRAINABLE_VARIABLES`: the subset of `Variable` objects that will
be trained by an optimizer. See
`tf.trainable_variables`
for more details.
* `SUMMARIES`: the summary `Tensor` objects that have been created in the
graph. See
`tf.summary.merge_all`
for more details.
* `QUEUE_RUNNERS`: the `QueueRunner` objects that are used to
produce input for a computation. See
`tf.train.start_queue_runners`
for more details.
* `MOVING_AVERAGE_VARIABLES`: the subset of `Variable` objects that will also
keep moving averages. See
`tf.moving_average_variables`
for more details.
* `REGULARIZATION_LOSSES`: regularization losses collected during graph
construction.
The following standard keys are _defined_, but their collections are **not**
automatically populated as many of the others are:
* `WEIGHTS`
* `BIASES`
* `ACTIVATIONS`
"""
# Key to collect Variable objects that are global (shared across machines).
# Default collection for all variables, except local ones.
GLOBAL_VARIABLES = "variables"
# Key to collect local variables that are local to the machine and are not
# saved/restored.
LOCAL_VARIABLES = "local_variables"
# Key to collect local variables which are used to accumulate interal state
# to be used in tf.metrics.*.
METRIC_VARIABLES = "metric_variables"
# Key to collect model variables defined by layers.
MODEL_VARIABLES = "model_variables"
# Key to collect Variable objects that will be trained by the
# optimizers.
TRAINABLE_VARIABLES = "trainable_variables"
# Key to collect summaries.
SUMMARIES = "summaries"
# Key to collect QueueRunners.
QUEUE_RUNNERS = "queue_runners"
# Key to collect table initializers.
TABLE_INITIALIZERS = "table_initializer"
# Key to collect asset filepaths. An asset represents an external resource
# like a vocabulary file.
ASSET_FILEPATHS = "asset_filepaths"
# Key to collect Variable objects that keep moving averages.
MOVING_AVERAGE_VARIABLES = "moving_average_variables"
# Key to collect regularization losses at graph construction.
REGULARIZATION_LOSSES = "regularization_losses"
# Key to collect concatenated sharded variables.
CONCATENATED_VARIABLES = "concatenated_variables"
# Key to collect savers.
SAVERS = "savers"
# Key to collect weights
WEIGHTS = "weights"
# Key to collect biases
BIASES = "biases"
# Key to collect activations
ACTIVATIONS = "activations"
# Key to collect update_ops
UPDATE_OPS = "update_ops"
# Key to collect losses
LOSSES = "losses"
# Key to collect BaseSaverBuilder.SaveableObject instances for checkpointing.
SAVEABLE_OBJECTS = "saveable_objects"
# Key to collect all shared resources used by the graph which need to be
# initialized once per cluster.
RESOURCES = "resources"
# Key to collect all shared resources used in this graph which need to be
# initialized once per session.
LOCAL_RESOURCES = "local_resources"
# Trainable resource-style variables.
TRAINABLE_RESOURCE_VARIABLES = "trainable_resource_variables"
# Key to indicate various ops.
INIT_OP = "init_op"
LOCAL_INIT_OP = "local_init_op"
READY_OP = "ready_op"
READY_FOR_LOCAL_INIT_OP = "ready_for_local_init_op"
SUMMARY_OP = "summary_op"
GLOBAL_STEP = "global_step"
# Used to count the number of evaluations performed during a single evaluation
# run.
EVAL_STEP = "eval_step"
TRAIN_OP = "train_op"
# Key for control flow context.
COND_CONTEXT = "cond_context"
WHILE_CONTEXT = "while_context"
# Used to store v2 summary names.
_SUMMARY_COLLECTION = "_SUMMARY_V2"
# List of all collections that keep track of variables.
_VARIABLE_COLLECTIONS = [
GLOBAL_VARIABLES,
LOCAL_VARIABLES,
METRIC_VARIABLES,
MODEL_VARIABLES,
TRAINABLE_VARIABLES,
MOVING_AVERAGE_VARIABLES,
CONCATENATED_VARIABLES,
TRAINABLE_RESOURCE_VARIABLES,
]
# Key for streaming model ports.
# NOTE(yuanbyu): internal and experimental.
_STREAMING_MODEL_PORTS = "streaming_model_ports"
@decorator_utils.classproperty
def VARIABLES(cls): # pylint: disable=no-self-argument
logging.log_first_n(logging.WARN,
"VARIABLES collection name is deprecated, please use "
"GLOBAL_VARIABLES instead; VARIABLES will be removed "
"after 2017-03-02.", 1)
return cls.GLOBAL_VARIABLES
@tf_export("add_to_collection")
def add_to_collection(name, value):
"""Wrapper for `Graph.add_to_collection()` using the default graph.
See `tf.Graph.add_to_collection`
for more details.
Args:
name: The key for the collection. For example, the `GraphKeys` class
contains many standard names for collections.
value: The value to add to the collection.
@compatibility(eager)
Collections are only supported in eager when variables are created inside an
EagerVariableStore (e.g. as part of a layer or template).
@end_compatibility
"""
get_default_graph().add_to_collection(name, value)
@tf_export("add_to_collections")
def add_to_collections(names, value):
"""Wrapper for `Graph.add_to_collections()` using the default graph.
See `tf.Graph.add_to_collections`
for more details.
Args:
names: The key for the collections. The `GraphKeys` class
contains many standard names for collections.
value: The value to add to the collections.
@compatibility(eager)
Collections are only supported in eager when variables are created inside an
EagerVariableStore (e.g. as part of a layer or template).
@end_compatibility
"""
get_default_graph().add_to_collections(names, value)
@tf_export("get_collection_ref")
def get_collection_ref(key):
"""Wrapper for `Graph.get_collection_ref()` using the default graph.
See `tf.Graph.get_collection_ref`
for more details.
Args:
key: The key for the collection. For example, the `GraphKeys` class
contains many standard names for collections.
Returns:
The list of values in the collection with the given `name`, or an empty
list if no value has been added to that collection. Note that this returns
the collection list itself, which can be modified in place to change the
collection.
@compatibility(eager)
Collections are not supported when eager execution is enabled.
@end_compatibility
"""
return get_default_graph().get_collection_ref(key)
@tf_export("get_collection")
def get_collection(key, scope=None):
"""Wrapper for `Graph.get_collection()` using the default graph.
See `tf.Graph.get_collection`
for more details.
Args:
key: The key for the collection. For example, the `GraphKeys` class
contains many standard names for collections.
scope: (Optional.) If supplied, the resulting list is filtered to include
only items whose `name` attribute matches using `re.match`. Items
without a `name` attribute are never returned if a scope is supplied and
the choice or `re.match` means that a `scope` without special tokens
filters by prefix.
Returns:
The list of values in the collection with the given `name`, or
an empty list if no value has been added to that collection. The
list contains the values in the order under which they were
collected.
@compatibility(eager)
Collections are not supported when eager execution is enabled.
@end_compatibility
"""
return get_default_graph().get_collection(key, scope)
def get_all_collection_keys():
"""Returns a list of collections used in the default graph."""
return get_default_graph().get_all_collection_keys()
name_scope_cache = {}
# Named like a function for backwards compatibility with the
# @tf_contextlib.contextmanager version, which was switched to a class to avoid
# some object creation overhead.
@tf_export("name_scope", "keras.backend.name_scope")
class name_scope(object): # pylint: disable=invalid-name
"""A context manager for use when defining a Python op.
This context manager validates that the given `values` are from the
same graph, makes that graph the default graph, and pushes a
name scope in that graph (see
`tf.Graph.name_scope`
for more details on that).
For example, to define a new Python op called `my_op`:
```python
def my_op(a, b, c, name=None):
with tf.name_scope(name, "MyOp", [a, b, c]) as scope:
a = tf.convert_to_tensor(a, name="a")
b = tf.convert_to_tensor(b, name="b")
c = tf.convert_to_tensor(c, name="c")
# Define some computation that uses `a`, `b`, and `c`.
return foo_op(..., name=scope)
```
"""
@property
def name(self):
return self._name
def __init__(self, name, default_name=None, values=None):
"""Initialize the context manager.
Args:
name: The name argument that is passed to the op function.
default_name: The default name to use if the `name` argument is `None`.
values: The list of `Tensor` arguments that are passed to the op function.
"""
self._name = default_name if name is None else name
self._default_name = default_name
self._values = values
self._ctx = context.context()
self._in_eager_mode = self._ctx.executing_eagerly()
def __enter__(self):
"""Start the scope block.
Returns:
The scope name.
Raises:
ValueError: if neither `name` nor `default_name` is provided
but `values` are.
"""
if self._in_eager_mode:
self._old_name = self._ctx.scope_name
if not self._name:
scope_name = ""
else:
cache_key = self._name, self._old_name, self._default_name
if cache_key in name_scope_cache:
self._ctx.scope_name = name_scope_cache[cache_key]
return self._ctx.scope_name
elif self._name[-1] == "/":
# A trailing slash breaks out of nested name scopes, indicating a
# fully specified scope name, for compatibility with Graph.name_scope.
scope_name = self._name
else:
name_with_trailing_slash = self._name + "/"
scope_name = (
self._old_name + name_with_trailing_slash
if self._old_name else name_with_trailing_slash)
name_scope_cache[cache_key] = scope_name
self._ctx.scope_name = scope_name
return scope_name
else:
if self._name is None and self._values is not None:
# We only raise an error if values is not None (provided) because
# currently tf.name_scope(None) (values=None then) is sometimes used as
# an idiom to reset to top scope.
raise ValueError(
"At least one of name (%s) and default_name (%s) must be provided."
% (self._name, self._default_name))
if self._values is None:
self._values = []
g = _get_graph_from_inputs(self._values)
self._g_manager = g.as_default()
self._g_manager.__enter__()
try:
self._name_scope = g.name_scope(self._name)
return self._name_scope.__enter__()
except:
self._g_manager.__exit__(*sys.exc_info())
raise
def __exit__(self, type_arg, value_arg, traceback_arg):
if self._in_eager_mode:
self._ctx.scope_name = self._old_name
else:
self._name_scope.__exit__(type_arg, value_arg, traceback_arg)
self._g_manager.__exit__(type_arg, value_arg, traceback_arg)
return False # False values do not suppress exceptions
def strip_name_scope(name, export_scope):
"""Removes name scope from a name.
Args:
name: A `string` name.
export_scope: Optional `string`. Name scope to remove.
Returns:
Name with name scope removed, or the original name if export_scope
is None.
"""
if export_scope:
if export_scope[-1] == "/":
export_scope = export_scope[:-1]
try:
# Strips export_scope/, export_scope///,
# ^export_scope/, loc:@export_scope/.
str_to_replace = r"([\^]|loc:@|^)" + export_scope + r"[\/]+(.*)"
return re.sub(str_to_replace, r"\1\2", compat.as_str(name), count=1)
except TypeError as e:
# If the name is not of a type we can process, simply return it.
logging.warning(e)
return name
else:
return name
def prepend_name_scope(name, import_scope):
"""Prepends name scope to a name.
Args:
name: A `string` name.
import_scope: Optional `string`. Name scope to add.
Returns:
Name with name scope added, or the original name if import_scope
is None.
"""
if import_scope:
if import_scope[-1] == "/":
import_scope = import_scope[:-1]
try:
str_to_replace = r"([\^]|loc:@|^)(.*)"
return re.sub(str_to_replace, r"\1" + import_scope + r"/\2",
compat.as_str(name))
except TypeError as e:
# If the name is not of a type we can process, simply return it.
logging.warning(e)
return name
else:
return name
# pylint: disable=g-doc-return-or-yield
# pylint: disable=not-context-manager
@tf_export("op_scope")
@tf_contextlib.contextmanager
def op_scope(values, name, default_name=None):
"""DEPRECATED. Same as name_scope above, just different argument order."""
logging.warn("tf.op_scope(values, name, default_name) is deprecated,"
" use tf.name_scope(name, default_name, values)")
with name_scope(name, default_name=default_name, values=values) as scope:
yield scope
_proto_function_registry = registry.Registry("proto functions")
def register_proto_function(collection_name,
proto_type=None,
to_proto=None,
from_proto=None):
"""Registers `to_proto` and `from_proto` functions for collection_name.
`to_proto` function converts a Python object to the corresponding protocol
buffer, and returns the protocol buffer.
`from_proto` function converts protocol buffer into a Python object, and
returns the object..
Args:
collection_name: Name of the collection.
proto_type: Protobuf type, such as `saver_pb2.SaverDef`,
`variable_pb2.VariableDef`, `queue_runner_pb2.QueueRunnerDef`..
to_proto: Function that implements Python object to protobuf conversion.
from_proto: Function that implements protobuf to Python object conversion.
"""
if to_proto and not callable(to_proto):
raise TypeError("to_proto must be callable.")
if from_proto and not callable(from_proto):
raise TypeError("from_proto must be callable.")
_proto_function_registry.register((proto_type, to_proto, from_proto),
collection_name)
def get_collection_proto_type(collection_name):
"""Returns the proto_type for collection_name."""
try:
return _proto_function_registry.lookup(collection_name)[0]
except LookupError:
return None
def get_to_proto_function(collection_name):
"""Returns the to_proto function for collection_name."""
try:
return _proto_function_registry.lookup(collection_name)[1]
except LookupError:
return None
def get_from_proto_function(collection_name):
"""Returns the from_proto function for collection_name."""
try:
return _proto_function_registry.lookup(collection_name)[2]
except LookupError:
return None
def _operation_conversion_error(op, dtype=None, name=None, as_ref=False):
"""Produce a nice error if someone converts an Operation to a Tensor."""
raise TypeError(("Can't convert Operation '%s' to Tensor "
"(target dtype=%r, name=%r, as_ref=%r)") % (op.name, dtype,
name, as_ref))
register_tensor_conversion_function(Operation, _operation_conversion_error)
| {
"content_hash": "09401ad4856b6f27d65cd3eb401011f7",
"timestamp": "",
"source": "github",
"line_count": 6106,
"max_line_length": 116,
"avg_line_length": 36.42581067802162,
"alnum_prop": 0.6636707790806416,
"repo_name": "ZhangXinNan/tensorflow",
"id": "5527f5286074baefaa29c6aec8a7c027a759f377",
"size": "223105",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tensorflow/python/framework/ops.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "1286"
},
{
"name": "Batchfile",
"bytes": "9258"
},
{
"name": "C",
"bytes": "327005"
},
{
"name": "C#",
"bytes": "8215"
},
{
"name": "C++",
"bytes": "46648068"
},
{
"name": "CMake",
"bytes": "206720"
},
{
"name": "Dockerfile",
"bytes": "6978"
},
{
"name": "Go",
"bytes": "1210133"
},
{
"name": "HTML",
"bytes": "4681865"
},
{
"name": "Java",
"bytes": "830576"
},
{
"name": "Jupyter Notebook",
"bytes": "2632421"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "Makefile",
"bytes": "51309"
},
{
"name": "Objective-C",
"bytes": "15650"
},
{
"name": "Objective-C++",
"bytes": "99243"
},
{
"name": "PHP",
"bytes": "1357"
},
{
"name": "Perl",
"bytes": "7536"
},
{
"name": "PureBasic",
"bytes": "25356"
},
{
"name": "Python",
"bytes": "40046802"
},
{
"name": "Ruby",
"bytes": "553"
},
{
"name": "Shell",
"bytes": "455624"
},
{
"name": "Smarty",
"bytes": "6976"
}
],
"symlink_target": ""
} |
<?php
/**
* ItemAction is ...
*
*
* @author Sage Gerard <sage@isodev.us>
* @version
* @package
* @since 1.0
*/
class ItemAction extends CAction
{
public function run($id)
{
$this->controller->layout = '//layouts/column2';
$rest = new RestCurlClient();
$url = Yii::app()->params['apiPrefix'];
$asset = json_decode($rest->get($url."/asset/$id"), true);
// header('Content-Type: text/plain');
// var_dump($asset);
$this->controller->render('item', array('asset'=>$asset));
}
}
| {
"content_hash": "cf383a6604e64aabf0708e2124ad6d02",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 66,
"avg_line_length": 17.65625,
"alnum_prop": 0.5380530973451327,
"repo_name": "freesideatlanta/qr-lbc-website",
"id": "92821f4867a7f3b698ea39efad539c8beaf68b64",
"size": "764",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "protected/actions/shop/ItemAction.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "2283"
},
{
"name": "CSS",
"bytes": "78378"
},
{
"name": "Erlang",
"bytes": "166"
},
{
"name": "JavaScript",
"bytes": "187284"
},
{
"name": "PHP",
"bytes": "17028557"
},
{
"name": "Perl",
"bytes": "150576"
},
{
"name": "Ruby",
"bytes": "613"
},
{
"name": "Shell",
"bytes": "1827"
}
],
"symlink_target": ""
} |
package no.noen.server.hl3;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import no.noen.eos.EMeter;
import no.noen.lms.*;
import no.noen.server.lms.SyncTool;
import no.noen.server.term.TerminalRequest;
/**
* ETM terminal request handler for data from meter-inputs (puls-ports PI).
*/
public class PulsCountRequest extends HL3Request {
private boolean fCheckDuplicates;
/** Constructor. */
public PulsCountRequest(boolean checkDupl) {
super("PulsCount");
this.fCheckDuplicates = checkDupl;
}
/**
* Handle terminal request.
* @param request Request string
*/
public void handleRequest(TerminalRequest request, Terminal terminal) {
// Prepare meters
java.util.Map<Integer,EMeter> meters = loadMeterMap(terminal, "PI");
// Now read data
int count = 0;
int numPorts = Integer.parseInt(request.getFieldAt(count++));
if (numPorts <= 0)
elog(request, "No ports in request from " + terminal.getId());
//ilog("parseData: numPorts=" + numPorts);
//ilog(request, "Ports: " + numPorts);
int numRows = Integer.parseInt(request.getFieldAt(count++));
if (numRows <= 0)
elog(request, "No rows in request from " + terminal.getId());
dlog(request, "Ports: " + numPorts+", rows: "+numRows);
Set<EMeter> modifiedMeters = new java.util.HashSet<EMeter>();
Map<EMeter,Date> meterDates = new java.util.HashMap<EMeter,Date>();
for (int i = 0; i < numRows; i++) {
String strTime = request.getFieldAt(count++);
Long tsLong = java.lang.Long.valueOf(strTime);
java.util.Date rowDate = new Date(tsLong.longValue());//parseDate(strTime, request);
if (rowDate == null) {
elog(request, "TerminalRequest: invalid date string: " + strTime);
continue;
}
// Kun for debug-logging.
Timestamp ts = new Timestamp(rowDate.getTime());
dlog(request, "row date=" + ts.toString());
for (int portNr = 1; portNr < 4; portNr++) {
EMeter meter = meters.get(new Integer(portNr));
String strVal = request.getFieldAt(count++);
if (meter == null) {
//LogWriter.dlog("parseData: no meter on port " + portNr);
continue;
}
if (strVal == null || strVal.length() == 0) {
ilog(request, "no value on port " + portNr);
continue;
}
long meterCount = Long.parseLong(strVal);
if (meterCount < 0) {
ilog(request, "negative value on port " + portNr);
continue;
}
boolean fSaveVal = true;
if (fCheckDuplicates) {
Long oldValue = MCManager.getMeterCount(meter.getId(), strTime);
fSaveVal = (oldValue == null) ||
(oldValue.longValue() != meterCount);
}
if (fSaveVal) {
MCManager.saveMeterCount(meter.getId(),request.getTimeReceived(), rowDate, meterCount);
if (!modifiedMeters.contains(meter)) {
modifiedMeters.add(meter);
meterDates.put(meter, rowDate);
}
} else {
ilog(request, "duplicate entry (" + meter.getId() + ", " +
strTime + ", " + meterCount + ")");
}
}
}
for (Iterator<EMeter> it = modifiedMeters.iterator(); it.hasNext(); ) {
EMeter meter = it.next();
Date firstDate = meterDates.get(meter);
SyncTool.syncMeterHourData(meter.getId(), firstDate);
}
}
}
| {
"content_hash": "ca9cb75cacb26398ddf786313c6a9aae",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 107,
"avg_line_length": 38.728155339805824,
"alnum_prop": 0.5342191025319629,
"repo_name": "haakom/EnergiWeb-remake",
"id": "29d0589224cd90f6871fc7ab3d59b06741213e17",
"size": "3989",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "energiweb/src/no/noen/server/hl3/PulsCountRequest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!doctype html>
<html class="theme-next use-motion theme-next-mist">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<meta name="google-site-verification" content="811fPPMUELrD3T2oiCan5cr2qndoJoOlnQoVQu_5I4g" />
<link rel="stylesheet" type="text/css" href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5"/>
<link href='//fonts.googleapis.com/css?family=Lato:300,400,700,400italic&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="/css/main.css?v=0.4.5.1"/>
<meta name="description" content="~Memory Off~" />
<meta name="keywords" content="GFW,moelf,linux" />
<link rel="alternate" href="/atom.xml" title="The WOrLd" type="application/atom+xml" />
<link rel="shorticon icon" type="image/x-icon" href="/fav.png?v=0.4.5.1" />
<meta name="description" content="~Memory Off~">
<meta property="og:type" content="website">
<meta property="og:title" content="Categories">
<meta property="og:url" content="http://moelf.xyz/categories/index.html">
<meta property="og:site_name" content="The WOrLd">
<meta property="og:description" content="~Memory Off~">
<meta property="og:updated_time" content="2015-08-20T17:45:36.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Categories">
<meta name="twitter:description" content="~Memory Off~">
<script type="text/javascript" id="hexo.configuration">
var CONFIG = {
scheme: 'Mist',
sidebar: 'post'
};
</script>
<title>
Category | The WOrLd
</title>
</head>
<body itemscope itemtype="http://schema.org/WebPage" lang="en">
<!--[if lte IE 8]>
<div style=' clear: both; height: 59px; padding:0 0 0 15px; position: relative;margin:0 auto;'>
<a href="http://windows.microsoft.com/en-US/internet-explorer/products/ie/home?ocid=ie6_countdown_bannercode">
<img src="http://7u2nvr.com1.z0.glb.clouddn.com/picouterie.jpg" border="0" height="42" width="820"
alt="You are using an outdated browser. For a faster, safer browsing experience, upgrade for free today or use other browser ,like chrome firefox safari."
style='margin-left:auto;margin-right:auto;display: block;'/>
</a>
</div>
<![endif]-->
<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-48117789-2', 'auto');
ga('send', 'pageview');
</script>
<script type="text/javascript">
var _hmt = _hmt || [];
(function() {
var hm = document.createElement("script");
hm.src = "//hm.baidu.com/hm.js?fe2ce663ff0205cb2bafa08bd8fee3cf";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
</script>
<div class="container one-column ">
<div class="headband"></div>
<header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
<div class="header-inner"><h1 class="site-meta">
<span class="logo-line-before"><i></i></span>
<a href="/" class="brand" rel="start">
<span class="logo">
<i class="icon-next-logo"></i>
</span>
<span class="site-title">The WOrLd</span>
</a>
<span class="logo-line-after"><i></i></span>
</h1>
<div class="site-nav-toggle">
<button>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
</button>
</div>
<nav class="site-nav">
<ul id="menu" class="menu menu-left">
<li class="menu-item menu-item-acg">
<a href="/categories/ACG" rel="section">
<i class="menu-item-icon icon-next-acg"></i> <br />
二次元
</a>
</li>
<li class="menu-item menu-item-life">
<a href="/categories/Life" rel="section">
<i class="menu-item-icon icon-next-life"></i> <br />
Life
</a>
</li>
<li class="menu-item menu-item-tech">
<a href="/categories/Tech" rel="section">
<i class="menu-item-icon icon-next-tech"></i> <br />
Tech
</a>
</li>
<li class="menu-item menu-item-categories">
<a href="/categories" rel="section">
<i class="menu-item-icon icon-next-categories"></i> <br />
|
</a>
</li>
<li class="menu-item menu-item-about">
<a href="/about" rel="section">
<i class="menu-item-icon icon-next-about"></i> <br />
About Me
</a>
</li>
<li class="menu-item menu-item-tags">
<a href="/tags" rel="section">
<i class="menu-item-icon icon-next-tags"></i> <br />
|
</a>
</li>
<li class="menu-item menu-item-archives">
<a href="/archives" rel="section">
<i class="menu-item-icon icon-next-archives"></i> <br />
Archives
</a>
</li>
</ul>
<div class="site-search">
<form class="site-search-form">
<input type="text" id="st-search-input" class="st-search-input st-default-search-input" />
</form>
<script type="text/javascript">
(function(w,d,t,u,n,s,e){w['SwiftypeObject']=n;w[n]=w[n]||function(){
(w[n].q=w[n].q||[]).push(arguments);};s=d.createElement(t);
e=d.getElementsByTagName(t)[0];s.async=1;s.src=u;e.parentNode.insertBefore(s,e);
})(window,document,'script','//s.swiftypecdn.com/install/v2/st.js','_st');
_st('install', 'KR7pQhQ8hP_sUyeozMGG','2.0.0');
</script>
</div>
</nav>
</div>
</header>
<main id="main" class="main">
<div class="main-inner">
<div id="content" class="content">
<div id="posts" class="posts-expand">
<div class="category-all-page">
<div class="category-all-title">
4 categories in total
</div>
<div class="category-all">
<ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/ACG/">ACG</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Life/">Life</a><span class="category-list-count">12</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Tech/">Tech</a><span class="category-list-count">20</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/Tech/Life/">Life</a><span class="category-list-count">2</span></li></ul></li></ul>
</div>
</div>
</div>
</div>
</div>
<div class="sidebar-toggle">
<div class="sidebar-toggle-line-wrap">
<span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
</div>
</div>
<aside id="sidebar" class="sidebar">
<div class="sidebar-inner">
<section class="site-overview">
<div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
<img class="site-author-image" src="/avatar.jpeg" alt="L" itemprop="image"/>
<p class="site-author-name" itemprop="name">L</p>
</div>
<p class="site-description motion-element" itemprop="description">~Memory Off~</p>
<nav class="site-state motion-element">
<div class="site-state-item site-state-posts">
<a href="/archives">
<span class="site-state-item-count">45</span>
<span class="site-state-item-name">posts</span>
</a>
</div>
<div class="site-state-item site-state-categories">
<a href="/categories">
<span class="site-state-item-count">4</span>
<span class="site-state-item-name">categories</span>
</a>
</div>
<div class="site-state-item site-state-tags">
<a href="/tags">
<span class="site-state-item-count">38</span>
<span class="site-state-item-name">tags</span>
</a>
</div>
</nav>
<div class="feed-link motion-element">
<a href="/atom.xml" rel="alternate">
<i class="menu-item-icon icon-next-feed"></i>
RSS
</a>
</div>
<div class="links-of-author motion-element">
<span class="links-of-author-item">
<a href="https://github.com/jerryling315" target="_blank">GitHub</a>
</span>
<span class="links-of-author-item">
<a href="https://twitter.com/Mo_el_f" target="_blank">Twitter</a>
</span>
<span class="links-of-author-item">
<a href="http://weibo.com/9kun" target="_blank">Weibo</a>
</span>
<span class="links-of-author-item">
<a href="http://zhuanlan.zhihu.com/NeoVim" target="_blank">ZhiHu</a>
</span>
</div>
<div class="cc-license motion-element" itemprop="license">
<a href="http://creativecommons.org/licenses/by-nc-sa/4.0" class="cc-opacity" target="_blank">
<img src="/images/cc-by-nc-sa.svg" alt="Creative Commons" />
</a>
</div>
<div class="links-of-author motion-element">
</div>
</section>
</div>
</aside>
</main>
<footer id="footer" class="footer">
<div class="footer-inner"> <div class="copyright" >
© 2013 -
<span itemprop="copyrightYear">2015</span>
<span class="with-love">
<i class="icon-next-heart"></i>
</span>
<span class="author" itemprop="copyrightHolder">L</span>
</div>
<div class="powered-by">
Haskelly powered by <a class="theme-link" href="http://hexo.io">Hexo</a>
</div>
<div class="theme-info">
Theme -
<a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
NexT.Mist
</a>
</div>
</div>
</footer>
<div class="back-to-top"></div>
</div>
<script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>
<script type="text/javascript">
var disqus_shortname = 'moelf';
var disqus_identifier = 'categories/index.html';
var disqus_title = 'Categories';
var disqus_url = 'http://moelf.xyz/categories/index.html';
function run_disqus_script(disqus_script){
var dsq = document.createElement('script');
dsq.type = 'text/javascript';
dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
}
run_disqus_script('count.js');
</script>
<script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js"></script>
<script type="text/javascript" src="/js/fancy-box.js?v=0.4.5.1"></script>
<script type="text/javascript" src="/js/helpers.js?v=0.4.5.1"></script>
<script type="text/javascript" src="/vendors/velocity/velocity.min.js"></script>
<script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js"></script>
<script type="text/javascript" src="/js/motion_global.js?v=0.4.5.1" id="motion.global"></script>
<script type="text/javascript" src="/js/nav-toggle.js"></script>
<script type="text/javascript">
$(document).ready(function () {
if (CONFIG.sidebar === 'always') {
displaySidebar();
}
});
</script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
processEscapes: true,
skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
}
});
</script>
<script type="text/x-mathjax-config">
MathJax.Hub.Queue(function() {
var all = MathJax.Hub.getAllJax(), i;
for (i=0; i < all.length; i += 1) {
all[i].SourceElement().parentNode.className += ' has-jax';
}
});
</script>
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/javascript" src="/js/lazyload.js"></script>
<script type="text/javascript">
$(function () {
$("#posts").find('img').lazyload({
placeholder: "/images/loading.gif",
effect: "fadeIn"
});
});
</script>
</body>
</html>
| {
"content_hash": "47d803bbfead368e4aa32c6d916c8628",
"timestamp": "",
"source": "github",
"line_count": 475,
"max_line_length": 647,
"avg_line_length": 28.172631578947367,
"alnum_prop": 0.5743536093259602,
"repo_name": "jerryling315/jerryling315.github.io",
"id": "5ca7fcc89f14329fbc7fb07efa10e96e24a2db16",
"size": "13388",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "categories/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "43732"
},
{
"name": "HTML",
"bytes": "2364541"
},
{
"name": "JavaScript",
"bytes": "14932"
}
],
"symlink_target": ""
} |
package com.tiny.demo.firstlinecode.materialdesign;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.tiny.demo.firstlinecode.BaseActivity;
import com.tiny.demo.firstlinecode.R;
/**
* 水果详情页
*/
public class FruitDetailActivity extends BaseActivity {
public static final String FRUIT_NAME = "FRUIT_NAME";
public static final String FRUIT_IMG = "FRUIT_IMG";
private String name;
private Integer imgId;
public static void actionStart(Context context, Bundle bundle) {
Intent intent = new Intent(context, FruitDetailActivity.class);
intent.putExtras(bundle);
context.startActivity(intent);
}
@Override
protected int setContentLayout() {
return R.layout.activity_fruit_detail;
}
@Override
protected void buildContentView() {
Intent intent = getIntent();
if (intent != null) {
name = intent.getStringExtra(FRUIT_NAME);
imgId = intent.getIntExtra(FRUIT_IMG, 0);
}
CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
ImageView img = (ImageView) findViewById(R.id.fruit_image_view);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView txtContent = (TextView) findViewById(R.id.fruit_content_text);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
//设置收缩起来时toolBar的标题和展开时CollapsingToolbarLayout左下角的标题。
collapsingToolbarLayout.setTitle("童童");
Glide.with(mContext).load(imgId).into(img);
String fruitContent = generateFruitContent(name);
txtContent.setText(fruitContent);
}
private String generateFruitContent(String name) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < 500; j++) {
sb.append(name).append(" --> ");
}
return sb.toString();
}
@Override
protected void initViewData() {
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| {
"content_hash": "4bc81f94797c6671e89dd3eb7c8c9875",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 122,
"avg_line_length": 32.548780487804876,
"alnum_prop": 0.6736605470213564,
"repo_name": "tinyvampirepudge/Android_Basis_Demo",
"id": "47c125e319ab51f553f5c7d06ed6bb67643609ba",
"size": "2725",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/tiny/demo/firstlinecode/materialdesign/FruitDetailActivity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "4434358"
}
],
"symlink_target": ""
} |
/**
* @private
*/
Ext.define('Ext.grid.header.DropZone', {
extend: 'Ext.dd.DropZone',
colHeaderCls: Ext.baseCSSPrefix + 'column-header',
proxyOffsets: [-4, -9],
constructor: function(headerCt) {
var me = this;
me.headerCt = headerCt;
me.ddGroup = me.getDDGroup();
me.autoGroup = true;
me.callParent([headerCt.el]);
},
destroy: function () {
this.callParent();
Ext.destroy(this.topIndicator, this.bottomIndicator);
},
getDDGroup: function() {
return 'header-dd-zone-' + this.headerCt.up('[scrollerOwner]').id;
},
getTargetFromEvent : function(e){
return e.getTarget('.' + this.colHeaderCls);
},
getTopIndicator: function() {
if (!this.topIndicator) {
this.topIndicator = Ext.getBody().createChild({
role: 'presentation',
cls: Ext.baseCSSPrefix + "col-move-top",
//<debug>
// tell the spec runner to ignore this element when checking if the dom is clean
"data-sticky": true,
//</debug>
html: " "
});
this.indicatorXOffset = Math.floor((this.topIndicator.dom.offsetWidth + 1) / 2);
}
return this.topIndicator;
},
getBottomIndicator: function() {
if (!this.bottomIndicator) {
this.bottomIndicator = Ext.getBody().createChild({
role: 'presentation',
cls: Ext.baseCSSPrefix + "col-move-bottom",
//<debug>
// tell the spec runner to ignore this element when checking if the dom is clean
"data-sticky": true,
//</debug>
html: " "
});
}
return this.bottomIndicator;
},
getLocation: function(e, t) {
var x = e.getXY()[0],
region = Ext.fly(t).getRegion(),
pos;
if ((region.right - x) <= (region.right - region.left) / 2) {
pos = "after";
} else {
pos = "before";
}
return {
pos: pos,
header: Ext.getCmp(t.id),
node: t
};
},
positionIndicator: function(data, node, e){
var me = this,
dragHeader = data.header,
dropLocation = me.getLocation(e, node),
targetHeader = dropLocation.header,
pos = dropLocation.pos,
nextHd,
prevHd,
topIndicator, bottomIndicator, topAnchor, bottomAnchor,
topXY, bottomXY, headerCtEl, minX, maxX,
allDropZones, ln, i, dropZone;
// Avoid expensive CQ lookups and DOM calculations if dropPosition has not changed
if (targetHeader === me.lastTargetHeader && pos === me.lastDropPos) {
return;
}
nextHd = dragHeader.nextSibling('gridcolumn:not([hidden])');
prevHd = dragHeader.previousSibling('gridcolumn:not([hidden])');
me.lastTargetHeader = targetHeader;
me.lastDropPos = pos;
// Cannot drag to before non-draggable start column
if (!targetHeader.draggable && pos === 'before' && targetHeader.getIndex() === 0) {
return false;
}
data.dropLocation = dropLocation;
if ((dragHeader !== targetHeader) &&
((pos === "before" && nextHd !== targetHeader) ||
(pos === "after" && prevHd !== targetHeader)) &&
!targetHeader.isDescendantOf(dragHeader)) {
// As we move in between different DropZones that are in the same
// group (such as the case when in a locked grid), invalidateDrop
// on the other dropZones.
allDropZones = Ext.dd.DragDropManager.getRelated(me);
ln = allDropZones.length;
i = 0;
for (; i < ln; i++) {
dropZone = allDropZones[i];
if (dropZone !== me && dropZone.invalidateDrop) {
dropZone.invalidateDrop();
}
}
me.valid = true;
topIndicator = me.getTopIndicator();
bottomIndicator = me.getBottomIndicator();
if (pos === 'before') {
topAnchor = 'bc-tl';
bottomAnchor = 'tc-bl';
} else {
topAnchor = 'bc-tr';
bottomAnchor = 'tc-br';
}
// Calculate arrow positions. Offset them to align exactly with column border line
topXY = topIndicator.getAlignToXY(targetHeader.el, topAnchor);
bottomXY = bottomIndicator.getAlignToXY(targetHeader.el, bottomAnchor);
// constrain the indicators to the viewable section
headerCtEl = me.headerCt.el;
minX = headerCtEl.getX() - me.indicatorXOffset;
maxX = headerCtEl.getX() + headerCtEl.getWidth();
topXY[0] = Ext.Number.constrain(topXY[0], minX, maxX);
bottomXY[0] = Ext.Number.constrain(bottomXY[0], minX, maxX);
// position and show indicators
topIndicator.setXY(topXY);
bottomIndicator.setXY(bottomXY);
topIndicator.show();
bottomIndicator.show();
// invalidate drop operation and hide indicators
} else {
me.invalidateDrop();
}
},
invalidateDrop: function() {
this.valid = false;
this.hideIndicators();
},
onNodeOver: function(node, dragZone, e, data) {
var me = this,
from = data.header,
doPosition,
to,
fromPanel,
toPanel;
if (data.header.el.dom === node) {
doPosition = false;
} else {
data.isLock = data.isUnlock = data.crossPanel = false;
to = me.getLocation(e, node).header;
// Dragging within the same container - always valid
doPosition = (from.ownerCt === to.ownerCt);
// If from different containers, and they are not sealed, then continue checking
if (!doPosition && (!from.ownerCt.sealed && !to.ownerCt.sealed)) {
doPosition = true;
fromPanel = from.up('tablepanel');
toPanel = to.up('tablepanel');
if (fromPanel !== toPanel) {
data.crossPanel = true;
// If it's a lock operation, check that it's allowable.
data.isLock = toPanel.isLocked && !fromPanel.isLocked;
data.isUnlock = !toPanel.isLocked && fromPanel.isLocked;
if ((data.isUnlock && from.lockable === false) || (data.isLock && !from.isLockable())) {
doPosition = false;
}
}
}
}
if (doPosition) {
me.positionIndicator(data, node, e);
} else {
me.valid = false;
}
return me.valid ? me.dropAllowed : me.dropNotAllowed;
},
hideIndicators: function() {
var me = this;
me.getTopIndicator().hide();
me.getBottomIndicator().hide();
me.lastTargetHeader = me.lastDropPos = null;
},
onNodeOut: function() {
this.hideIndicators();
},
onNodeDrop: function(node, dragZone, e, data) {
// Note that dropLocation.pos refers to before or after the target node NOT before or after the fromCt!
if (this.valid) {
var dragHeader = data.header,
dropLocation = data.dropLocation,
targetHeader = dropLocation.header,
fromCt = dragHeader.ownerCt,
toCt = targetHeader.ownerCt,
sameCt = fromCt === toCt,
// Use the items collection here, the indices we want are for moving the actual items in the container.
// The HeaderContainer translates this to visible columns for informing the view and firing events.
localFromIdx = fromCt.items.indexOf(data.header),
localToIdx = toCt.items.indexOf(targetHeader),
headerCt = this.headerCt,
// Use the full column manager here, the indices we want are for moving the actual items in the container.
// The HeaderContainer translates this to visible columns for informing the view and firing events.
columns = headerCt.visibleColumnManager,
visibleFromIdx = columns.getHeaderIndex(dragHeader),
// Group headers need to lookup the column index in the items collection NOT the leaf-only full column manager!
visibleToIdx = targetHeader.isGroupHeader ? toCt.items.indexOf(targetHeader) : columns.getHeaderIndex(targetHeader),
colsToMove = dragHeader.isGroupHeader ? dragHeader.query(':not([hidden]):not([isGroupHeader])').length : 1,
// We really only need to know the direction for when dragging the last header of a group out of its grouping.
// `true` === dragged to the right, `false` === dragged to the left.
// Also, the direction is considered `true` (to the right) if the header is dropped directly adjacent to the group
// in the 'after' position.
direction = targetHeader.isGroupHeader ? (dropLocation.pos === 'after') : columns.getHeaderIndex(targetHeader) > columns.getHeaderIndex(dragHeader),
scrollerOwner, savedWidth;
// Drop position is to the right of the targetHeader, increment the toIdx correctly. This is important
// to allow the drop after the last header, for instance, else it would not be possible.
if (dropLocation.pos === 'after') {
localToIdx++;
// Always increment the visibleToIdx index as this is used to swap the columns. Since the column swap uses
// the inserBefore dom method, it must be incremented so it's one more than the slot for the new column.
visibleToIdx += targetHeader.isGroupHeader ? targetHeader.query(':not([hidden]):not([isGroupHeader])').length : 1;
}
// If we are dragging in between two HeaderContainers that have had the lockable
// mixin injected we will lock/unlock headers in between sections, and then continue
// with another execution of onNodeDrop to ensure the header is dropped into the correct group
if (data.isLock) {
scrollerOwner = fromCt.up('[scrollerOwner]');
scrollerOwner.lock(dragHeader, localToIdx, toCt);
} else if (data.isUnlock) {
scrollerOwner = fromCt.up('[scrollerOwner]');
scrollerOwner.unlock(dragHeader, localToIdx, toCt);
}
// This is a drop within the same HeaderContainer.
else {
this.invalidateDrop();
// Cache the width here, we need to get it before we removed it from the DOM
savedWidth = dragHeader.getWidth();
// Dragging within the same container.
if (sameCt) {
// If dragging rightwards, then after removal, the insertion index will be less.
if (localToIdx > localFromIdx) {
localToIdx -= 1;
}
// A no-op. This can happen when cross lockable drag operations recurse (see above).
// If a drop was a lock/unlock, and the lock/unlock call placed the column in the
// desired position (lock places at end, unlock places at beginning) then we're done.
if (localToIdx === localFromIdx) {
// We still need to inform the rest of the components so that events can be fired.
headerCt.onHeaderMoved(dragHeader, colsToMove, visibleFromIdx, visibleToIdx);
return;
}
}
// Suspend layouts while we sort all this out.
Ext.suspendLayouts();
if (sameCt) {
toCt.move(localFromIdx, localToIdx);
} else {
// Do a sanity!
//
// After the offsets are calculated, the visibleToIdx and the localToIdx indices should not be equal
// for when the header is dragged to the right. This can happen, however, when the header that is moved
// is the last in a grouped header and it's moved directly to the right of the group in which it's
// contained (the drap position doesn't matter, either 'before' or 'after'). Therefore, we must decrement
// the localToIdx index otherwise the header will be +1 offset from its data column.
if (direction && (visibleToIdx === localToIdx)) {
localToIdx -= 1;
}
// When removing and then adding, the owning gridpanel will be informed of column mutation twice
// Both remove and add handling inform the owning grid.
// The isDDMoveInGrid flag will prevent the remove operation from doing this.
// See Ext.grid.header.Container#onRemove
fromCt.isDDMoveInGrid = toCt.isDDMoveInGrid = !data.crossPanel;
fromCt.remove(dragHeader, false);
toCt.insert(localToIdx, dragHeader);
fromCt.isDDMoveInGrid = toCt.isDDMoveInGrid = false;
}
// Group headers skrinkwrap their child headers.
// Therefore a child header may not flex; it must contribute a fixed width.
// But we restore the flex value when moving back into the main header container
if (toCt.isGroupHeader) {
// Adjust the width of the "to" group header only if we dragged in from somewhere else.
if (!sameCt) {
dragHeader.savedFlex = dragHeader.flex;
delete dragHeader.flex;
dragHeader.width = savedWidth;
}
} else {
if (dragHeader.savedFlex) {
dragHeader.flex = dragHeader.savedFlex;
delete dragHeader.width;
}
}
Ext.resumeLayouts(true);
// If moving within the same container, the container's onMove method will have ensured that the top level
// headerCt's onHeaderMoved.
if (!sameCt) {
headerCt.onHeaderMoved(dragHeader, colsToMove, visibleFromIdx, visibleToIdx);
}
// Ext.grid.header.Container will handle the removal of empty groups, don't handle it here
}
}
}
});
| {
"content_hash": "867549d11be4661b87f5e04b4b62a696",
"timestamp": "",
"source": "github",
"line_count": 349,
"max_line_length": 169,
"avg_line_length": 43.6189111747851,
"alnum_prop": 0.5445707153649083,
"repo_name": "guillaumeguerin/openmusic",
"id": "650e5ec82b7642bcbdeea71b96bbec365b207ba9",
"size": "15223",
"binary": false,
"copies": "24",
"ref": "refs/heads/master",
"path": "ext/src/grid/header/DropZone.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "14297061"
},
{
"name": "JavaScript",
"bytes": "20219722"
},
{
"name": "Python",
"bytes": "3330"
},
{
"name": "Ruby",
"bytes": "8144"
}
],
"symlink_target": ""
} |
package org.batfish.representation.cumulus_nclu;
import com.google.common.collect.ImmutableSet;
import java.io.Serializable;
import java.util.Set;
import javax.annotation.Nonnull;
import org.batfish.datamodel.IntegerSpace;
/** Settings for bridged ports */
public class Bridge implements Serializable {
private @Nonnull Set<String> _ports;
private int _pvid;
private @Nonnull IntegerSpace _vids;
public Bridge() {
_ports = ImmutableSet.of();
_pvid = 1;
_vids = IntegerSpace.EMPTY;
}
/** Bridged ports */
public @Nonnull Set<String> getPorts() {
return _ports;
}
/** Default native VLAN for bridged ports */
public int getPvid() {
return _pvid;
}
/** Default allowed VLANs for bridged ports */
public @Nonnull IntegerSpace getVids() {
return _vids;
}
public void setPorts(Set<String> ports) {
_ports = ImmutableSet.copyOf(ports);
}
public void setPvid(int pvid) {
_pvid = pvid;
}
public void setVids(IntegerSpace vids) {
_vids = vids;
}
public @Nonnull org.batfish.datamodel.vendor_family.cumulus.Bridge toDataModel() {
return org.batfish.datamodel.vendor_family.cumulus.Bridge.builder()
.setPorts(_ports)
.setPvid(_pvid)
.setVids(_vids)
.build();
}
}
| {
"content_hash": "2c43ce8f125beafdb20334279502a7bc",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 84,
"avg_line_length": 22.821428571428573,
"alnum_prop": 0.676056338028169,
"repo_name": "intentionet/batfish",
"id": "cb95967a4320d9dc407795c87796c9f7d4053e32",
"size": "1278",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "projects/batfish/src/main/java/org/batfish/representation/cumulus_nclu/Bridge.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "399750"
},
{
"name": "CSS",
"bytes": "26879"
},
{
"name": "HTML",
"bytes": "25459"
},
{
"name": "Java",
"bytes": "2927077"
},
{
"name": "JavaScript",
"bytes": "1787307"
},
{
"name": "Prolog",
"bytes": "156345"
},
{
"name": "Python",
"bytes": "51669"
},
{
"name": "Shell",
"bytes": "5542"
}
],
"symlink_target": ""
} |
require 'rufus-json/automatic'
require 'wrong_api_client'
require File.join(File.dirname(__FILE__), 'credentials.rb')
Dir[File.join(File.dirname(__FILE__), 'support/**/*.rb')].each do |f|
require(f)
end
RSpec.configure do |config|
# == Mock Framework
#
# If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
#
# config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr
config.mock_with :rspec
#config.include CredentialHelper
end
| {
"content_hash": "349c1903992a789c7137d20faca80ed8",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 79,
"avg_line_length": 20.791666666666668,
"alnum_prop": 0.6913827655310621,
"repo_name": "jmettraux/wrong_api_client",
"id": "a015b347d50296493eb6441c5941dbdb3d0dd70c",
"size": "499",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/spec_helper.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "9354"
}
],
"symlink_target": ""
} |
#include <okui/View.h>
#include <okui/Application.h>
#include <okui/BitmapFont.h>
#include <okui/blending.h>
#include <okui/opengl/opengl.h>
#include <okui/shapes/Rectangle.h>
#include <okui/Window.h>
#include <scraps/Reverse.h>
#include <cassert>
namespace okui {
View::~View() {
if (application()) {
application()->removeListeners(this);
}
if (_nextFocus) {
_nextFocus->_previousFocus = _previousFocus;
}
if (_previousFocus) {
_previousFocus->_nextFocus = _nextFocus;
}
removeSubviews();
if (superview()) {
superview()->removeSubview(this);
}
}
void View::addSubview(View* view) {
assert(view != this);
if (view->_name.empty()) {
view->setName(view->name()); // name() returns typeid if _name is empty
}
bool viewIsAppearing = !view->isVisibleInOpenWindow() && view->isVisible() && isVisibleInOpenWindow();
if (viewIsAppearing) {
view->_dispatchFutureVisibilityChange(true);
}
if (view->superview()) {
view->superview()->removeSubview(view);
}
addChildToFront(view);
assert(view->window() == nullptr);
if (_window && _window->isOpen()) {
view->_dispatchWindowChange(_window);
}
if (viewIsAppearing) {
view->_dispatchVisibilityChange(true);
}
invalidateRenderCache();
}
void View::addHiddenSubview(View* view) {
view->hide();
addSubview(view);
}
void View::removeSubview(View* view) {
assert(view != this);
if (view->isFocus()) {
view->focusAncestor();
}
bool viewIsDisappearing = view->isVisibleInOpenWindow();
if (viewIsDisappearing) {
view->_dispatchFutureVisibilityChange(false);
}
if (_subviewWithMouse == view) {
_subviewWithMouse = nullptr;
}
removeChild(view);
if (view->window() != nullptr) {
view->_dispatchWindowChange(nullptr);
}
if (viewIsDisappearing) {
view->_dispatchVisibilityChange(false);
}
invalidateRenderCache();
}
void View::removeSubviews() {
while (!subviews().empty()) {
removeSubview(subviews().front());
}
}
void View::setIsVisible(bool isVisible) {
if (_isVisible == isVisible) { return; }
if (superview() && superview()->isVisibleInOpenWindow()) {
_dispatchFutureVisibilityChange(isVisible);
}
_isVisible = isVisible;
if (superview() && superview()->isVisibleInOpenWindow()) {
_dispatchVisibilityChange(isVisible);
}
if (superview()) {
superview()->invalidateRenderCache();
}
}
bool View::ancestorsAreVisible() const {
return !superview() || (superview()->isVisible() && superview()->ancestorsAreVisible());
}
bool View::isVisibleInOpenWindow() const {
return isVisible() && ancestorsAreVisible() && window() && window()->isOpen();
}
void View::setInterceptsInteractions(bool intercepts) {
_interceptsInteractions = intercepts;
}
void View::setInterceptsInteractions(bool intercepts, bool childrenIntercept) {
_interceptsInteractions = intercepts;
_childrenInterceptInteractions = childrenIntercept;
}
void View::setChildrenInterceptInteractions(bool childrenIntercept) {
_childrenInterceptInteractions = childrenIntercept;
}
ShaderCache* View::shaderCache() {
return window()->shaderCache();
}
void View::setScale(double scaleX, double scaleY) {
if (_scale.x == scaleX && _scale.y == scaleY) { return; }
_scale.x = scaleX;
_scale.y = scaleY;
invalidateRenderCache();
}
void View::setTintColor(const Color& color) {
if (_tintColor == color) { return; }
_tintColor = color;
_invalidateSuperviewRenderCache();
}
void View::sendToBack() {
TreeNode::sendToBack();
if (isVisible()) {
superview()->invalidateRenderCache();
}
}
void View::bringToFront() {
TreeNode::bringToFront();
if (isVisible()) {
superview()->invalidateRenderCache();
}
}
void View::focus() {
if (window()) {
window()->setFocus(this);
}
}
View* View::expectedFocus() {
auto view = this;
View* ret = nullptr;
while (view) {
if (view->canBecomeDirectFocus() && view->isVisibleInOpenWindow()) {
ret = view;
}
view = view->preferredFocus();
}
return ret;
}
void View::focusAncestor() {
for (auto ancestor = superview(); ancestor; ancestor = ancestor->superview()) {
auto focus = ancestor->expectedFocus();
if (focus && focus != this && !focus->isDescendantOf(this)) {
focus->focus();
return;
}
}
unfocus();
}
void View::unfocus() {
if (isFocus()) {
window()->setFocus(nullptr);
}
}
void View::setNextFocus(View* view) {
if (_nextFocus == view) { return; }
if (_nextFocus) {
if (_nextFocus->_previousFocus && _nextFocus->_previousFocus != this) {
_nextFocus->_previousFocus->_nextFocus = nullptr;
}
_nextFocus->_previousFocus = nullptr;
}
_nextFocus = view;
if (_nextFocus) {
_nextFocus->_previousFocus = this;
}
}
View* View::nextAvailableFocus() {
auto view = _nextFocus;
while (view && view != this) {
if (view->isVisible() && view->canBecomeDirectFocus()) {
return view;
}
view = view->_nextFocus;
}
return nullptr;
}
View* View::previousAvailableFocus() {
auto view = _previousFocus;
while (view && view != this) {
if (view->isVisible() && view->canBecomeDirectFocus()) {
return view;
}
view = view->_previousFocus;
}
return nullptr;
}
bool View::isFocus() const {
return window() && window()->focus() && (window()->focus() == this || window()->focus()->isDescendantOf(this));
}
bool View::hasMouse() const {
return superview() && superview()->_subviewWithMouse == this;
}
std::shared_ptr<TextureInterface> View::renderTexture() const {
return _renderCacheTexture;
}
void View::invalidateRenderCache() {
_hasCachedRender = false;
_invalidateSuperviewRenderCache();
}
TextureHandle View::loadTextureResource(const std::string& name) {
if (!window()) { return nullptr; }
auto handle = window()->loadTextureResource(name);
handle.onLoad([this]{ invalidateRenderCache(); });
return handle;
}
TextureHandle View::loadTextureFromMemory(std::shared_ptr<const std::string> data) {
if (!window()) { return nullptr; }
auto handle = window()->loadTextureFromMemory(data);
handle.onLoad([this]{ invalidateRenderCache(); });
return handle;
}
TextureHandle View::loadTextureFromURL(const std::string& url) {
if (!window()) { return nullptr; }
auto handle = window()->loadTextureFromURL(url);
handle.onLoad([this]{ invalidateRenderCache(); });
return handle;
}
Application* View::application() const {
return window() ? window()->application() : nullptr;
}
Rectangle<double> View::windowBounds() const {
auto min = localToWindow(0, 0);
auto max = localToWindow(bounds().width, bounds().height);
return Rectangle<double>(min, max - min);
}
void View::setBoundsRelative(double x, double y, double width, double height) {
if (superview()) {
auto& superBounds = superview()->bounds();
setBounds(x * superBounds.width, y * superBounds.height, width * superBounds.width, height * superBounds.height);
}
}
Point<double> View::localToAncestor(double x, double y, const View* ancestor) const {
assert(!ancestor || ancestor->isAncestorOf(this));
const auto xSuper = bounds().x + x;
const auto ySuper = bounds().y + y;
return ancestor && ancestor != superview() ? superview()->localToAncestor(xSuper, ySuper, ancestor) : Point<double>(xSuper, ySuper);
}
Point<double> View::superviewToLocal(double x, double y) const {
return Point<double>(x - bounds().x, y - bounds().y);
}
Point<double> View::superviewToLocal(const Point<double>& p) const {
return superviewToLocal(p.x, p.y);
}
Point<double> View::localToWindow(double x, double y) const {
Point<double> ret(x, y);
auto view = this;
while (view) {
ret = view->localToSuperview(ret);
view = view->superview();
}
return ret;
}
Point<double> View::localToWindow(const Point<double>& p) const {
return localToWindow(p.x, p.y);
}
bool View::hitTest(double x, double y) {
return x >= 0 && x < bounds().width &&
y >= 0 && y < bounds().height;
}
View* View::hitTestView(double x, double y) {
auto hit = hitTest(x, y);
if (hit || !_clipsToBounds) {
for (auto& subview : subviews()) {
if (subview->isVisible()) {
auto point = subview->superviewToLocal(x, y);
auto view = subview->hitTestView(point.x, point.y);
if (view) { return view; }
}
}
}
return hit ? this : nullptr;
}
void View::mouseDown(MouseButton button, double x, double y) {
if (superview() && superview()->_interceptsInteractions) {
auto point = localToSuperview(x, y);
superview()->mouseDown(button, point.x, point.y);
window()->beginDragging(superview());
}
}
void View::mouseUp(MouseButton button, double startX, double startY, double x, double y) {
if (superview() && superview()->_interceptsInteractions) {
auto startPoint = localToSuperview(startX, startY);
auto point = localToSuperview(x, y);
superview()->mouseUp(button, startPoint.x, startPoint.y, point.x, point.y);
}
}
void View::mouseWheel(double xPos, double yPos, int xWheel, int yWheel) {
if (superview() && superview()->_interceptsInteractions) {
auto point = localToSuperview(xPos, yPos);
superview()->mouseWheel(point.x, point.y, xWheel, yWheel);
}
}
void View::mouseDrag(double startX, double startY, double x, double y) {
if (superview() && superview()->_interceptsInteractions) {
auto startPoint = localToSuperview(startX, startY);
auto point = localToSuperview(x, y);
superview()->mouseDrag(startPoint.x, startPoint.y, point.x, point.y);
}
}
void View::mouseMovement(double x, double y) {
if (superview() && superview()->_interceptsInteractions) {
auto point = localToSuperview(x, y);
superview()->mouseMovement(point.x, point.y);
}
}
Responder* View::nextResponder() {
return superview() ? dynamic_cast<Responder*>(superview()) : dynamic_cast<Responder*>(window());
}
void View::keyDown(KeyCode key, KeyModifiers mod, bool repeat) {
if (key == KeyCode::kTab) {
if (_previousFocus && (mod & KeyModifier::kShift)) {
if (auto view = previousAvailableFocus()) {
view->focus();
}
return;
} else if (_nextFocus) {
if (auto view = nextAvailableFocus()) {
view->focus();
}
return;
}
}
if (window() && (false
|| (key == KeyCode::kRight && window()->moveFocus(Direction::kRight))
|| (key == KeyCode::kLeft && window()->moveFocus(Direction::kLeft))
|| (key == KeyCode::kUp && window()->moveFocus(Direction::kUp))
|| (key == KeyCode::kDown && window()->moveFocus(Direction::kDown))
)) {
return;
}
Responder::keyDown(key, mod, repeat);
}
bool View::hasRelation(Relation relation, const View* view) const {
switch (relation) {
case Relation::kAny:
return application() ? application() == view->application() : commonView(view) != nullptr;
case Relation::kHierarchy:
return TreeNode::hasRelation(TreeNode::Relation::kCommonRoot, view);
case Relation::kDescendant:
return TreeNode::hasRelation(TreeNode::Relation::kDescendant, view);
case Relation::kAncestor:
return TreeNode::hasRelation(TreeNode::Relation::kAncestor, view);
case Relation::kSibling:
return TreeNode::hasRelation(TreeNode::Relation::kSibling, view);
case Relation::kSelf:
return TreeNode::hasRelation(TreeNode::Relation::kSelf, view);
}
}
void View::dispatchUpdate(std::chrono::high_resolution_clock::duration elapsed) {
if (!_shouldSubscribeToUpdates()) {
window()->unsubscribeFromUpdates(this);
return;
}
if (scraps::platform::kIsTVOS && canBecomeDirectFocus()) {
View* newFocus = nullptr;
_touchpadFocus.update(elapsed, this, &newFocus);
if (newFocus) {
newFocus->_checkUpdateSubscription();
}
}
auto hooks = _updateHooks;
for (auto& hook : hooks) {
if (_updateHooks.count(hook.first)) {
hook.second();
}
}
}
void View::renderAndRenderSubviews(const RenderTarget* target, const Rectangle<int>& area, stdts::optional<Rectangle<int>> clipBounds) {
if (!isVisible() || !area.width || !area.height) { return; }
if (!_requiresTextureRendering() && !_cachesRender) {
// render directly
_renderAndRenderSubviews(target, area, false, clipBounds);
_renderCacheTexture->set();
return;
}
clipBounds = clipBounds ? clipBounds->intersection(area) : area;
if (!_rendersToTexture && clipBounds->size().magnitudeSquared() == 0) {
return;
}
// make sure the render cache is up-to-date
GLint previousFramebuffer = 0;
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &previousFramebuffer);
if (!_renderCacheColorAttachment || _renderCacheColorAttachment->width() != area.width || _renderCacheColorAttachment->height() != area.height) {
// update the framebuffer
_renderCache = std::make_unique<opengl::Framebuffer>();
_renderCacheColorAttachment = _renderCache->addColorAttachment(area.width, area.height);
// TODO: stencil attachment
assert(_renderCache->isComplete());
_hasCachedRender = false;
}
_renderCacheTexture->set(_renderCacheColorAttachment->texture(), area.width, area.height, true);
if (!_cachesRender || !_hasCachedRender) {
// render to _renderCache
_renderCache->bind();
Rectangle<int> cacheArea(0, 0, area.width, area.height);
RenderTarget cacheTarget(area.width, area.height);
_renderAndRenderSubviews(&cacheTarget, cacheArea, true);
_hasCachedRender = true;
}
glBindFramebuffer(GL_FRAMEBUFFER, previousFramebuffer);
// do the actual rendering
glViewport(area.x, target->height() - area.maxY(), area.width, area.height);
Blending blending{BlendFunction::kDefault};
glEnable(GL_SCISSOR_TEST);
glScissor(clipBounds->x, target->height() - clipBounds->maxY(), clipBounds->width, clipBounds->height);
AffineTransformation transformation{-1, -1, 0, 0, 2.0/_bounds.width, 2.0/_bounds.height};
postRender(_renderCacheTexture, transformation);
glDisable(GL_SCISSOR_TEST);
}
void View::addUpdateHook(const std::string& handle, std::function<void()> hook) {
_updateHooks[std::hash<std::string>()(handle)] = std::move(hook);
_checkUpdateSubscription();
}
void View::removeUpdateHook(const std::string& handle) {
_updateHooks.erase(std::hash<std::string>()(handle));
_checkUpdateSubscription();
}
void View::postRender(std::shared_ptr<TextureInterface> texture, const AffineTransformation& transformation) {
auto shader = textureShader();
shader->setTransformation(transformation);
shader->setColor(_tintColor);
shader->drawScaledFill(*texture, Rectangle<double>(0.0, 0.0, bounds().width, bounds().height));
shader->flush();
}
bool View::dispatchMouseDown(MouseButton button, double x, double y) {
if (!isVisible()) { return false; }
if (_childrenInterceptInteractions) {
for (auto& subview : subviews()) {
auto point = subview->superviewToLocal(x, y);
if ((!subview->clipsToBounds() || subview->hitTest(point.x, point.y)) && subview->dispatchMouseDown(button, point.x, point.y)) {
return true;
}
}
}
if (_interceptsInteractions && hitTest(x, y)) {
mouseDown(button, x, y);
window()->beginDragging(this);
return true;
}
return false;
}
bool View::dispatchMouseUp(MouseButton button, double startX, double startY, double x, double y) {
if (!isVisible()) { return false; }
if (_childrenInterceptInteractions) {
for (auto& subview : subviews()) {
auto startPoint = subview->superviewToLocal(startX, startY);
auto point = subview->superviewToLocal(x, y);
if ((!subview->clipsToBounds() || subview->hitTest(point.x, point.y)) && subview->dispatchMouseUp(button, startPoint.x, startPoint.y, point.x, point.y)) {
return true;
}
}
}
if (_interceptsInteractions && hitTest(x, y)) {
mouseUp(button, startX, startY, x, y);
return true;
}
return false;
}
bool View::dispatchMouseMovement(double x, double y) {
if (!isVisible()) { return false; }
View* subviewWithMouse = nullptr;
if (_childrenInterceptInteractions) {
for (auto& subview : subviews()) {
auto point = subview->superviewToLocal(x, y);
if ((!subview->clipsToBounds() || subview->hitTest(point.x, point.y)) && subview->dispatchMouseMovement(point.x, point.y)) {
subviewWithMouse = subview;
break;
}
}
}
if (subviewWithMouse != _subviewWithMouse) {
if (_subviewWithMouse) {
_subviewWithMouse->_mouseExit();
}
_subviewWithMouse = subviewWithMouse;
if (_subviewWithMouse) {
_subviewWithMouse->mouseEnter();
}
}
if (subviewWithMouse) {
return true;
}
if (_interceptsInteractions && hitTest(x, y)) {
mouseMovement(x, y);
return true;
}
return false;
}
bool View::dispatchMouseWheel(double xPos, double yPos, int xWheel, int yWheel) {
if (!isVisible()) { return false; }
if (_childrenInterceptInteractions) {
for (auto& subview : subviews()) {
auto point = subview->superviewToLocal(xPos, yPos);
if ((!subview->clipsToBounds() || subview->hitTest(point.x, point.y)) &&
subview->dispatchMouseWheel(point.x, point.y, xWheel, yWheel)) {
return true;
}
}
}
if (_interceptsInteractions && hitTest(xPos, yPos)) {
mouseWheel(xPos, yPos, xWheel, yWheel);
return true;
}
return false;
}
void View::touchUp(size_t finger, Point<double> position, double pressure) {
if (!scraps::platform::kIsTVOS) { return; }
_touchpadFocus.touchUp(position);
_checkUpdateSubscription();
}
void View::touchDown(size_t finger, Point<double> position, double pressure) {
if (!scraps::platform::kIsTVOS) { return; }
_touchpadFocus.touchDown(position);
_checkUpdateSubscription();
}
void View::touchMovement(size_t finger, Point<double> position, Point<double> distance, double pressure) {
if (!scraps::platform::kIsTVOS) { return; }
_touchpadFocus.touchMovement(position, distance);
_checkUpdateSubscription();
}
void View::_invalidateSuperviewRenderCache() {
if (isVisible() && superview()) {
superview()->invalidateRenderCache();
}
}
void View::_setBounds(const Rectangle<double>& bounds) {
auto willMove = (_bounds.x != bounds.x || _bounds.y != bounds.y);
auto willResize = (_bounds.width != bounds.width || _bounds.height != bounds.height);
if (!willMove && !willResize) {
return;
}
_bounds = std::move(bounds);
if (willResize) {
layout();
invalidateRenderCache();
}
if (isVisible() && superview()) {
superview()->invalidateRenderCache();
}
}
void View::_dispatchFutureVisibilityChange(bool visible) {
if (visible) {
willAppear();
} else {
willDisappear();
}
for (auto& subview : subviews()) {
if (subview->isVisible()) {
subview->_dispatchFutureVisibilityChange(visible);
}
}
}
void View::_dispatchVisibilityChange(bool visible) {
if (!visible && isFocus()) {
focusAncestor();
}
if (visible) {
appeared();
} else {
disappeared();
}
for (auto& subview : subviews()) {
if (subview->isVisible()) {
subview->_dispatchVisibilityChange(visible);
}
}
_checkUpdateSubscription();
}
void View::_dispatchWindowChange(Window* window) {
if (application()) {
application()->removeListeners(this);
}
if (_window) {
_window->endDragging(this);
_window->unsubscribeFromUpdates(this);
}
assert(_window != window);
_window = window;
if (application()) {
for (auto& listener : _listeners) {
application()->addListener(this, listener.index, &listener.action, listener.relation);
}
}
windowChanged();
for (auto& subview : subviews()) {
if (window == subview->window()) {
// subviews added in the above windowChanged call will have already gotten the change
continue;
}
subview->_dispatchWindowChange(window);
}
_checkUpdateSubscription();
}
void View::_mouseExit() {
if (_subviewWithMouse && _clipsToBounds) {
_subviewWithMouse->_mouseExit();
_subviewWithMouse = nullptr;
}
mouseExit();
}
void View::_updateFocusableRegions(std::vector<std::tuple<View*, Rectangle<double>>>& regions) {
if (!isVisible() || !window()) { return; }
if (_interceptsInteractions) {
auto windowBounds = this->windowBounds();
std::vector<std::tuple<View*, Rectangle<double>>> prev;
prev.swap(regions);
for (auto& region : prev) {
auto diff = std::get<Rectangle<double>>(region) - windowBounds;
for (auto& r : diff) {
regions.emplace_back(std::get<View*>(region), r);
}
}
auto focus = window()->focus();
if (canBecomeDirectFocus() && (!focus || (focus != this && !isDescendantOf(focus) && !isAncestorOf(focus)))) {
regions.emplace_back(this, windowBounds);
if (clipsToBounds()) {
return;
}
}
}
if (_childrenInterceptInteractions) {
for (auto subview : Reverse(subviews())) {
subview->_updateFocusableRegions(regions);
}
}
}
bool View::_requiresTextureRendering() {
return _rendersToTexture || _tintColor != Color::kWhite;
}
void View::_renderAndRenderSubviews(const RenderTarget* target, const Rectangle<int>& area, bool shouldClear, stdts::optional<Rectangle<int>> clipBounds) {
auto xScale = (_bounds.width != 0.0 ? area.width / _bounds.width : 1.0);
auto yScale = (_bounds.height != 0.0 ? area.height / _bounds.height : 1.0);
auto visibleArea = Rectangle<int>{0, 0, target->width(), target->height()}.intersection(area);
_renderTransformation = AffineTransformation(
-1, 1,
(area.x - visibleArea.x) / xScale, (area.y - visibleArea.y) / yScale,
2.0/_bounds.width*area.width/visibleArea.width, -2.0/_bounds.height*area.height/visibleArea.height
);
if (_clipsToBounds) {
clipBounds = clipBounds ? clipBounds->intersection(visibleArea) : visibleArea;
if (clipBounds->size().magnitudeSquared() == 0) {
return;
}
}
glViewport(visibleArea.x, target->height() - visibleArea.maxY(), visibleArea.width, visibleArea.height);
Blending blending{BlendFunction::kDefault};
if (shouldClear) {
glDisable(GL_SCISSOR_TEST);
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
}
if (clipBounds) {
glEnable(GL_SCISSOR_TEST);
glScissor(clipBounds->x, target->height() - clipBounds->maxY(), clipBounds->width, clipBounds->height);
} else {
glDisable(GL_SCISSOR_TEST);
}
if (_backgroundColor.alpha() > 0) {
auto backgroundShader = colorShader();
backgroundShader->setColor(_backgroundColor);
shapes::Rectangle(0.0, 0.0, bounds().width, bounds().height).draw(backgroundShader);
backgroundShader->flush();
}
render(target, area);
for (auto& subview : Reverse(subviews())) {
Rectangle<int> subarea(std::round(area.x + xScale * subview->_bounds.x),
std::round(area.y + yScale * subview->_bounds.y),
std::round(xScale * subview->_scale.x * subview->_bounds.width),
std::round(yScale * subview->_scale.y * subview->_bounds.height));
subview->renderAndRenderSubviews(target, subarea, clipBounds);
}
if (clipBounds) {
glDisable(GL_SCISSOR_TEST);
}
}
void View::_post(std::type_index index, const void* ptr, Relation relation) {
if (application()) {
application()->post(this, index, ptr, relation);
}
}
void View::_listen(std::type_index index, std::function<void(const void*, View*)> action, Relation relation) {
_listeners.emplace_back(index, std::move(action), relation);
if (application()) {
application()->addListener(this, index, &_listeners.back().action, relation);
}
}
std::vector<View*> View::_topViewsForRelation(Relation relation) {
auto* thisRootView = root();
std::vector<View*> ret{thisRootView};
if (relation == Relation::kAny && application()) {
for (auto window : application()->windows()) {
if (window->contentView() != thisRootView) {
ret.emplace_back(window->contentView());
}
}
}
return ret;
}
scraps::AbstractTaskScheduler* View::_taskScheduler() const {
assert(application());
return application()->taskScheduler();
}
void View::_checkUpdateSubscription() {
if (!window()) { return; }
if (_shouldSubscribeToUpdates()) {
window()->subscribeToUpdates(this);
} else {
window()->unsubscribeFromUpdates(this);
}
}
bool View::_shouldSubscribeToUpdates() {
return (!_updateHooks.empty() || _touchpadFocus.needsUpdates()) && isVisibleInOpenWindow();
}
} // namespace okui
| {
"content_hash": "e8c7e41d5b5666371963cfba588962a5",
"timestamp": "",
"source": "github",
"line_count": 888,
"max_line_length": 166,
"avg_line_length": 29.69481981981982,
"alnum_prop": 0.6167469376919869,
"repo_name": "bittorrent/okui",
"id": "1e8cc98c6428f0dcbc2fa131b130e92f76fe3123",
"size": "26953",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/View.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "3008"
},
{
"name": "C++",
"bytes": "616483"
},
{
"name": "Java",
"bytes": "5819"
},
{
"name": "Objective-C",
"bytes": "63367"
},
{
"name": "Python",
"bytes": "15764"
},
{
"name": "Shell",
"bytes": "2543"
}
],
"symlink_target": ""
} |
package com.intellij.uiDesigner.i18n;
import com.intellij.uiDesigner.lw.StringDescriptor;
import com.intellij.uiDesigner.radComponents.RadComponent;
import com.intellij.uiDesigner.radComponents.RadContainer;
class FormBorderStringDescriptorAccessor extends StringDescriptorAccessor {
private final RadContainer myContainer;
FormBorderStringDescriptorAccessor(RadContainer container) {
myContainer = container;
}
@Override
public RadComponent getComponent() {
return myContainer;
}
@Override
protected StringDescriptor getStringDescriptorValue() {
return myContainer.getBorderTitle();
}
@Override
protected void setStringDescriptorValue(final StringDescriptor descriptor) throws Exception {
myContainer.setBorderTitle(descriptor);
}
}
| {
"content_hash": "55e272e764c670278e95c91079972fde",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 95,
"avg_line_length": 27.857142857142858,
"alnum_prop": 0.8076923076923077,
"repo_name": "google/intellij-community",
"id": "5c780b063080dbd533f20464fca8316e0c6e87a7",
"size": "921",
"binary": false,
"copies": "12",
"ref": "refs/heads/master",
"path": "plugins/ui-designer/src/com/intellij/uiDesigner/i18n/FormBorderStringDescriptorAccessor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "80cc7aecbb55689d771e3aa1d3ebfad8",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "098131be59d1b0984af74c9bd6d8425bf491d7b0",
"size": "173",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Apocynaceae/Pandaca/Pandaca debrayi/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!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_151) on Fri Jun 22 04:34:14 MST 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.wildfly.swarm.cdi.jaxrsapi.deployment Class Hierarchy (BOM: * : All 2.0.0.Final API)</title>
<meta name="date" content="2018-06-22">
<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="org.wildfly.swarm.cdi.jaxrsapi.deployment Class Hierarchy (BOM: * : All 2.0.0.Final 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>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.0.0.Final</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/wildfly/swarm/cdi/jaxrsapi/package-tree.html">Prev</a></li>
<li><a href="../../../../../../org/wildfly/swarm/cli/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/wildfly/swarm/cdi/jaxrsapi/deployment/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.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">
<h1 class="title">Hierarchy For Package org.wildfly.swarm.cdi.jaxrsapi.deployment</h1>
<span class="packageHierarchyLabel">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../../../../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a>
<ul>
<li type="circle">org.wildfly.swarm.cdi.jaxrsapi.deployment.<a href="../../../../../../org/wildfly/swarm/cdi/jaxrsapi/deployment/ProxyBuilder.html" title="class in org.wildfly.swarm.cdi.jaxrsapi.deployment"><span class="typeNameLink">ProxyBuilder</span></a><T></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>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.0.0.Final</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/wildfly/swarm/cdi/jaxrsapi/package-tree.html">Prev</a></li>
<li><a href="../../../../../../org/wildfly/swarm/cli/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/wildfly/swarm/cdi/jaxrsapi/deployment/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.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>Copyright © 2018 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "0f50b7381ecbacb9f0230c05e4e6cfc3",
"timestamp": "",
"source": "github",
"line_count": 141,
"max_line_length": 271,
"avg_line_length": 38.61702127659574,
"alnum_prop": 0.6152433425160698,
"repo_name": "wildfly-swarm/wildfly-swarm-javadocs",
"id": "d3b222530efa113cc04b51cd5deb50b866cc0731",
"size": "5445",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "2.0.0.Final/apidocs/org/wildfly/swarm/cdi/jaxrsapi/deployment/package-tree.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta name="robots" content="noindex, nofollow"> <meta http-equiv="Content-Type" content="text/html; charset={ini:settings.charset}"> <meta http-equiv="Cache-Control" content="public"> <style type="text/css">
body {
background-color: #ffffff;
padding: 0px;
margin: 0px;
text-align:left;
}
.table_box {
table-layout: fixed;
text-align:center;
}
.display_no {
display:none;
}
</style> </head> <body id="print"> </body> <script type="text/javascript">
onload = function()
{
_create_shipping_print();
}
/**
* 创建快递单打印内容
*/
function _create_shipping_print()
{
//创建快递单
var print_bg = _create_print_bg();
//创建文本
var config_lable = '{$cdpCFG}';
var lable = config_lable.split("||,||");
if (lable.length <= 0)
{
return false; //未设置打印内容
}
for (var i = 0; i < lable.length; i++)
{
//获取标签参数
var text = lable[i].split(",");
if (text.length <= 0 || text[0] == null || typeof(text[0]) == "undefined" || text[0] == '')
{
continue;
}
text[4] -= 10;
text[5] -= 10;
_create_text_box(print_bg, text[0], text[1], text[2], text[3], text[4], text[5]);
}
}
/**
* 创建快递单背景
*/
function _create_print_bg()
{
var print_bg = document.createElement('div');
print_bg.setAttribute('id', 'print_bg');
var print = document.getElementById('print');
print.appendChild(print_bg);
//测试打印效果
//print_bg.style.background = 'url({$background["url"]}?{~time()})';
//设置快递单样式
print_bg.style.width = '{$background["extra"]["width"]}px';
print_bg.style.height = '{$background["extra"]["height"]}px';
print_bg.style.zIndex = 1;
print_bg.style.border = "solid 1px #FFF";
print_bg.style.padding = "0";
print_bg.style.position = "relative";
print_bg.style.margin = "0";
return print_bg;
}
/**
* 创建快递单文本
*/
function _create_text_box(print_bg, id, text_content, text_width, text_height, x, y)
{//alert(id + '|' + text_content + '|' + text_width + '|' + text_height + '|' + x + '|' + y);
var text_box = document.createElement('div');
//设置属性
text_box.setAttribute('id', id);
print_bg.appendChild(text_box);
//设置样式
text_box.style.width = text_width + "px";
text_box.style.height = text_height + "px";
text_box.style.border = "0";
text_box.style.padding = "0";
text_box.style.margin = "0 auto";
text_box.style.position = "absolute";
text_box.style.top = y + "px";
text_box.style.left = x + "px";
text_box.style.wordBreak = 'break-all'; //内容自动换行 严格断字
text_box.style.textAlign = 'left';
//赋值
text_box.innerHTML = text_content;
return true;
}
</script> </html> | {
"content_hash": "c0c683e3e4637670656363e2467425b0",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 360,
"avg_line_length": 27.717391304347824,
"alnum_prop": 0.6556862745098039,
"repo_name": "kinglion/tttuangou",
"id": "fdb4ea5577a8aa42bda5e1192592b3aea1f416a3",
"size": "2706",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "templates/admin/print_delivery.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "347451"
},
{
"name": "JavaScript",
"bytes": "466989"
},
{
"name": "PHP",
"bytes": "2698716"
}
],
"symlink_target": ""
} |
/**
* @fileoverview Tests for restore key UI
*/
/** @suppress {extraProvide} */
goog.provide('e2e.ext.actions.RestoreKeyringDataTest');
goog.require('e2e.error.InvalidArgumentsError');
goog.require('e2e.ext.actions.RestoreKeyringData');
goog.require('e2e.ext.constants');
goog.require('goog.crypt.base64');
goog.require('goog.testing.MockControl');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.asserts');
goog.require('goog.testing.jsunit');
goog.require('goog.ui.Component');
goog.setTestOnly();
var stubs = new goog.testing.PropertyReplacer();
var constants = e2e.ext.constants;
var ui = null;
function setUp() {
mockControl = new goog.testing.MockControl();
stubs.setPath('e2e.openpgp.KeyRing.ECC_SEED_SIZE', 5);
ui = new goog.ui.Component();
ui.render(document.body);
}
function tearDown() {
stubs.reset();
mockControl.$tearDown();
ui = null;
}
function testRestoreData() {
var ctx = {
restoreKeyring: function(d) {
assertArrayEquals(d.seed, [1, 2, 3, 4, 5]);
assertEquals(d.count, 6);
}
};
new e2e.ext.actions.RestoreKeyringData().execute(ctx, {
action: constants.Actions.RESTORE_KEYRING_DATA,
content: {
data: goog.crypt.base64.encodeByteArray([3, 1, 2, 3, 4, 5]),
email: 'Ryan Chan <rcc@google.com>'
}
}, ui, goog.partial(assertEquals, 'Ryan Chan <rcc@google.com>'));
}
function testInvalidVersion() {
new e2e.ext.actions.RestoreKeyringData().execute({}, {
action: constants.Actions.RESTORE_KEYRING_DATA,
content: {
data: goog.crypt.base64.encodeByteArray([0x80 | 3, 1, 2, 3, 4, 5]),
email: 'Ryan Chan <rcc@google.com>'
}
}, ui, function() {
assert('Invalid version bit not detected', false);
}, function(err) {
assertTrue(err instanceof e2e.error.InvalidArgumentsError);
assertEquals(err.message, 'Invalid version bit');
});
}
function testInvalidRestoreSize() {
new e2e.ext.actions.RestoreKeyringData().execute({}, {
action: constants.Actions.RESTORE_KEYRING_DATA,
content: {
data: goog.crypt.base64.encodeByteArray([3, 1, 2, 3, 4, 5, 6]),
email: 'Ryan Chan <rcc@google.com>'
}
}, ui, function() {
assert('Invalid restore size not detected', false);
}, function(err) {
assertTrue(err instanceof e2e.error.InvalidArgumentsError);
assertEquals(err.message, 'Backup data has invalid length');
});
}
| {
"content_hash": "d883befece04bbb12e9db6a057ef2dff",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 73,
"avg_line_length": 26.755555555555556,
"alnum_prop": 0.6785714285714286,
"repo_name": "01022499/end-to-end",
"id": "bc1566a38f077e9e53cc3c01fc9fcee49f42d47a",
"size": "3031",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "src/javascript/crypto/e2e/extension/actions/restorekeyringdata_test.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "15330"
},
{
"name": "JavaScript",
"bytes": "2286438"
},
{
"name": "Python",
"bytes": "3136"
},
{
"name": "Shell",
"bytes": "12233"
}
],
"symlink_target": ""
} |
var canvas;
var gl;
var numVertices = 36;
var pointsArray = [];
var normalsArray = [];
var vertices = [
vec4( -0.5, -0.5, 0.5, 1.0 ),
vec4( -0.5, 0.5, 0.5, 1.0 ),
vec4( 0.5, 0.5, 0.5, 1.0 ),
vec4( 0.5, -0.5, 0.5, 1.0 ),
vec4( -0.5, -0.5, -0.5, 1.0 ),
vec4( -0.5, 0.5, -0.5, 1.0 ),
vec4( 0.5, 0.5, -0.5, 1.0 ),
vec4( 0.5, -0.5, -0.5, 1.0 )
];
var lightPosition = vec4(1.0, 1.0, 1.0, 0.0 );
var lightAmbient = vec4(0.2, 0.2, 0.2, 1.0 );
var lightDiffuse = vec4( 1.0, 1.0, 1.0, 1.0 );
var lightSpecular = vec4( 1.0, 1.0, 1.0, 1.0 );
var materialAmbient = vec4( 1.0, 0.0, 1.0, 1.0 );
var materialDiffuse = vec4( 1.0, 0.8, 0.0, 1.0);
var materialSpecular = vec4( 1.0, 0.8, 0.0, 1.0 );
var materialShininess = 100.0;
var ctm;
var ambientColor, diffuseColor, specularColor;
var modelView, projection;
var viewerPos;
var program;
var xAxis = 0;
var yAxis = 1;
var zAxis = 2;
var axis = 0;
var theta =[0, 0, 0];
var thetaLoc;
var flag = true;
function quad(a, b, c, d) {
var t1 = subtract(vertices[b], vertices[a]);
var t2 = subtract(vertices[c], vertices[b]);
var normal = cross(t1, t2);
var normal = vec3(normal);
pointsArray.push(vertices[a]);
normalsArray.push(normal);
pointsArray.push(vertices[b]);
normalsArray.push(normal);
pointsArray.push(vertices[c]);
normalsArray.push(normal);
pointsArray.push(vertices[a]);
normalsArray.push(normal);
pointsArray.push(vertices[c]);
normalsArray.push(normal);
pointsArray.push(vertices[d]);
normalsArray.push(normal);
}
function colorCube()
{
quad( 1, 0, 3, 2 );
quad( 2, 3, 7, 6 );
quad( 3, 0, 4, 7 );
quad( 6, 5, 1, 2 );
quad( 4, 5, 6, 7 );
quad( 5, 4, 0, 1 );
}
window.onload = function init() {
canvas = document.getElementById( "gl-canvas" );
gl = WebGLUtils.setupWebGL( canvas );
if ( !gl ) { alert( "WebGL isn't available" ); }
gl.viewport( 0, 0, canvas.width, canvas.height );
gl.clearColor( 1.0, 1.0, 1.0, 1.0 );
gl.enable(gl.DEPTH_TEST);
//
// Load shaders and initialize attribute buffers
//
program = initShaders( gl, "vertex-shader", "fragment-shader" );
gl.useProgram( program );
colorCube();
var nBuffer = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, nBuffer );
gl.bufferData( gl.ARRAY_BUFFER, flatten(normalsArray), gl.STATIC_DRAW );
var vNormal = gl.getAttribLocation( program, "vNormal" );
gl.vertexAttribPointer( vNormal, 3, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vNormal );
var vBuffer = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, vBuffer );
gl.bufferData( gl.ARRAY_BUFFER, flatten(pointsArray), gl.STATIC_DRAW );
var vPosition = gl.getAttribLocation(program, "vPosition");
gl.vertexAttribPointer(vPosition, 4, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(vPosition);
thetaLoc = gl.getUniformLocation(program, "theta");
viewerPos = vec3(0.0, 0.0, -20.0 );
projection = ortho(-1, 1, -1, 1, -100, 100);
ambientProduct = mult(lightAmbient, materialAmbient);
diffuseProduct = mult(lightDiffuse, materialDiffuse);
specularProduct = mult(lightSpecular, materialSpecular);
document.getElementById("ButtonX").onclick = function(){axis = xAxis;};
document.getElementById("ButtonY").onclick = function(){axis = yAxis;};
document.getElementById("ButtonZ").onclick = function(){axis = zAxis;};
document.getElementById("ButtonT").onclick = function(){flag = !flag;};
gl.uniform4fv(gl.getUniformLocation(program, "ambientProduct"),
flatten(ambientProduct));
gl.uniform4fv(gl.getUniformLocation(program, "diffuseProduct"),
flatten(diffuseProduct) );
gl.uniform4fv(gl.getUniformLocation(program, "specularProduct"),
flatten(specularProduct) );
gl.uniform4fv(gl.getUniformLocation(program, "lightPosition"),
flatten(lightPosition) );
gl.uniform1f(gl.getUniformLocation(program,
"shininess"),materialShininess);
gl.uniformMatrix4fv( gl.getUniformLocation(program, "projectionMatrix"),
false, flatten(projection));
render();
}
var render = function(){
gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
if(flag) theta[axis] += 2.0;
modelView = mat4();
modelView = mult(modelView, rotate(theta[xAxis], [1, 0, 0] ));
modelView = mult(modelView, rotate(theta[yAxis], [0, 1, 0] ));
modelView = mult(modelView, rotate(theta[zAxis], [0, 0, 1] ));
gl.uniformMatrix4fv( gl.getUniformLocation(program,
"modelViewMatrix"), false, flatten(modelView) );
gl.drawArrays( gl.TRIANGLES, 0, numVertices );
requestAnimFrame(render);
}
| {
"content_hash": "aed4e07439e474e6a4caf300797f95f7",
"timestamp": "",
"source": "github",
"line_count": 166,
"max_line_length": 76,
"avg_line_length": 29.52409638554217,
"alnum_prop": 0.613140175474393,
"repo_name": "llucbrell/WebGL",
"id": "cde62f797a1caf7c53af40f47d3f0d97e9c7fa4e",
"size": "4903",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Chap6/shadedCube.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "GLSL",
"bytes": "182"
},
{
"name": "HTML",
"bytes": "121846"
},
{
"name": "JavaScript",
"bytes": "414683"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.apache.npanday</groupId>
<artifactId>npanday-dist-parent</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>npanday-repository-builder</artifactId>
<packaging>pom</packaging>
<name>NPanday :: Repository Builder</name>
<dependencies>
<!--
NPANDAY PLUGINS
-->
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>application-maven-plugin</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>aspnet-maven-plugin</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>azure-maven-plugin</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>library-importer-maven-plugin</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>maven-compile-plugin</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>maven-aspx-plugin</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>maven-fxcop-plugin</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>maven-ilmerge-plugin</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>maven-link-plugin</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>maven-mojo-generator-plugin</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>msdeploy-maven-plugin</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>partcover-maven-plugin</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>maven-resgen-plugin</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>maven-resolver-plugin</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>maven-test-plugin</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>maven-wsdl-plugin</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>maven-xsd-plugin</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>maven-xsp-plugin</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>silverlight-maven-plugin</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>wix-maven-plugin</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>custom-lifecycle-maven-plugin</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<!--
NPANDAY ARCHETYPES
-->
<dependency>
<groupId>org.apache.npanday</groupId>
<artifactId>maven-archetype-dotnet-simple</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday</groupId>
<artifactId>maven-archetype-netexecutable</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday</groupId>
<artifactId>maven-archetype-vb-simple</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<!--assemblies-->
<dependency>
<groupId>org.apache.npanday</groupId>
<artifactId>NPanday.Artifact</artifactId>
<version>${project.version}</version>
<type>dotnet-library</type>
</dependency>
<dependency>
<groupId>org.apache.logging</groupId>
<artifactId>log4net</artifactId>
<version>1.2.11</version>
<type>dotnet-library</type>
<classifier>net-2.0</classifier>
</dependency>
<dependency>
<groupId>org.apache.npanday</groupId>
<artifactId>NPanday.Model.Pom</artifactId>
<version>${project.version}</version>
<type>dotnet-library</type>
</dependency>
<dependency>
<groupId>org.apache.npanday</groupId>
<artifactId>NPanday.Model.Pom</artifactId>
<version>${project.version}</version>
<type>dotnet-library</type>
<classifier>4b435f4d76e2f0e6</classifier>
</dependency>
<dependency>
<groupId>org.apache.npanday</groupId>
<artifactId>NPanday.Model.AutomationExtensibility</artifactId>
<version>${project.version}</version>
<type>dotnet-library</type>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>NPanday.Plugin</artifactId>
<version>${project.version}</version>
<type>dotnet-library</type>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>NPanday.Plugin</artifactId>
<version>${project.version}</version>
<type>dotnet-library</type>
<classifier>4b435f4d76e2f0e6</classifier>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>NPanday.Plugin.Loader</artifactId>
<version>${project.version}</version>
<type>dotnet-executable</type>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>NPanday.Plugin.MojoGenerator</artifactId>
<version>${project.version}</version>
<type>dotnet-executable</type>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>NPanday.Plugin.Runner</artifactId>
<version>${project.version}</version>
<type>dotnet-executable</type>
</dependency>
<dependency>
<groupId>org.apache.npanday.visualstudio</groupId>
<artifactId>NPanday.VisualStudio.Addin</artifactId>
<version>${project.version}</version>
<exclusions>
<exclusion>
<groupId>Microsoft.VisualStudio.CommandBars</groupId>
<artifactId>Microsoft.VisualStudio.CommandBars</artifactId>
</exclusion>
<exclusion>
<groupId>EnvDTE</groupId>
<artifactId>EnvDTE</artifactId>
</exclusion>
<exclusion>
<groupId>EnvDTE80</groupId>
<artifactId>EnvDTE80</artifactId>
</exclusion>
<exclusion>
<groupId>Extensibility</groupId>
<artifactId>Extensibility</artifactId>
</exclusion>
<exclusion>
<groupId>VSLangProj</groupId>
<artifactId>VSLangProj</artifactId>
</exclusion>
<exclusion>
<groupId>VSLangProj80</groupId>
<artifactId>VSLangProj80</artifactId>
</exclusion>
<exclusion>
<groupId>VsWebSite.Interop</groupId>
<artifactId>VsWebSite.Interop</artifactId>
</exclusion>
<exclusion>
<groupId>Microsoft.Build.Engine</groupId>
<artifactId>Microsoft.Build.Engine</artifactId>
</exclusion>
<exclusion>
<groupId>Microsoft.Build.Framework</groupId>
<artifactId>Microsoft.Build.Framework</artifactId>
</exclusion>
<exclusion>
<groupId>Microsoft.Build.Utilities</groupId>
<artifactId>Microsoft.Build.Utilities</artifactId>
</exclusion>
<exclusion>
<groupId>Microsoft.Build.Tasks</groupId>
<artifactId>Microsoft.Build.Tasks</artifactId>
</exclusion>
</exclusions>
<type>visual-studio-addin</type>
</dependency>
<!--
NPANDAY NETPLUGINS
-->
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>NPanday.Plugin.Addin.JavaBinding</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>NPanday.Plugin.Devenv.JavaBinding</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>NPanday.Plugin.Settings.JavaBinding</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>NPanday.Plugin.SysRef.JavaBinding</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>NPanday.Plugin.Msbuild.JavaBinding</artifactId>
<version>1.5.0-incubating-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>NPanday.Plugin.SysRef</artifactId>
<version>${project.version}</version>
<type>dotnet-maven-plugin</type>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>NPanday.Plugin.Addin</artifactId>
<version>${project.version}</version>
<type>dotnet-maven-plugin</type>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>NPanday.Plugin.Devenv</artifactId>
<version>${project.version}</version>
<type>dotnet-maven-plugin</type>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>NPanday.Plugin.Resx</artifactId>
<version>${project.version}</version>
<type>dotnet-executable</type>
</dependency>
<dependency>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>NPanday.Plugin.Settings</artifactId>
<version>${project.version}</version>
<type>dotnet-maven-plugin</type>
</dependency>
<dependency>
<groupId>NUnit</groupId>
<artifactId>NUnit.Framework</artifactId>
<version>2.2.8.0</version>
<type>dotnet-library</type>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.4.1</version>
<configuration>
<descriptor>src/main/assembly/repo.xml</descriptor>
<finalName>repository</finalName>
<attach>false</attach>
</configuration>
<executions>
<execution>
<phase>prepare-package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<phase>package</phase>
<configuration>
<tasks>
<copy file="${basedir}/../../LICENSE" todir="${project.build.directory}/repository-bin" />
<tar destfile="${project.build.directory}/repository-bin.tar">
<tarfileset dir="${project.build.directory}/repository-bin" preserveLeadingSlashes="true">
<exclude name="**/commons-*/**" />
<exclude name="**/backport-util-concurrent/**" />
<exclude name="**/classworlds/**" />
<exclude name="**/com/**" />
<exclude name="**/de/**" />
<exclude name="**/dom4j/**" />
<exclude name="**/javassist/**" />
<exclude name="**/jdom/**" />
<exclude name="**/jline/**" />
<exclude name="**/jtidy/**" />
<exclude name="**/junit/**" />
<exclude name="**/nekohtml/**" />
<exclude name="**/net/**" />
<exclude name="**/org/apache/ant/**" />
<exclude name="**/org/apache/commons/**" />
<exclude name="**/org/apache/apache/**" />
<exclude name="**/org/apache/jackrabbit/**" />
<exclude name="**/org/apache/maven/**" />
<exclude name="**/org/codehaus/**" />
<exclude name="**/org/easymock/**" />
<exclude name="**/org/reflections/**" />
<exclude name="**/org/slf4j/**" />
<exclude name="**/org/sonatype/**" />
<exclude name="**/slide/**" />
<exclude name="**/xml*/**" />
</tarfileset>
</tar>
<gzip src="${project.build.directory}/repository-bin.tar" destfile="${project.build.directory}/repository-bin.tar.gz" />
</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>attach-artifact</goal>
</goals>
<configuration>
<artifacts>
<artifact>
<file>${project.build.directory}/repository-bin.tar.gz</file>
<type>tar.gz</type>
<classifier>bin</classifier>
</artifact>
</artifacts>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.npanday.plugins</groupId>
<artifactId>maven-compile-plugin</artifactId>
<version>${bootstrap.npanday.version}</version>
<extensions>true</extensions>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "a42f2557b40232765f9bb4b5818c5e4a",
"timestamp": "",
"source": "github",
"line_count": 444,
"max_line_length": 201,
"avg_line_length": 37.4527027027027,
"alnum_prop": 0.6220458235612484,
"repo_name": "apache/npanday",
"id": "0859e6257f93942807f06966738107ce4277f769",
"size": "16629",
"binary": false,
"copies": "2",
"ref": "refs/heads/trunk",
"path": "dist/npanday-repository-builder/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "18901"
},
{
"name": "Batchfile",
"bytes": "1894"
},
{
"name": "C#",
"bytes": "1212356"
},
{
"name": "CSS",
"bytes": "807"
},
{
"name": "Groovy",
"bytes": "113168"
},
{
"name": "HTML",
"bytes": "17887"
},
{
"name": "Java",
"bytes": "1069144"
},
{
"name": "Shell",
"bytes": "1503"
},
{
"name": "Visual Basic",
"bytes": "115680"
}
],
"symlink_target": ""
} |
import pytest
from spacy.serialize.packer import Packer
from spacy.attrs import ORTH, SPACY
from spacy.tokens import Doc
import math
@pytest.mark.models
def test_read_write(EN):
doc1 = EN(u'This is a simple test. With a couple of sentences.')
doc2 = EN(u'This is another test document.')
with open('/tmp/spacy_docs.bin', 'wb') as file_:
file_.write(doc1.to_bytes())
file_.write(doc2.to_bytes())
with open('/tmp/spacy_docs.bin', 'rb') as file_:
bytes1, bytes2 = Doc.read_bytes(file_)
r1 = Doc(EN.vocab).from_bytes(bytes1)
r2 = Doc(EN.vocab).from_bytes(bytes2)
assert r1.string == doc1.string
assert r2.string == doc2.string
@pytest.mark.models
def test_left_right(EN):
orig = EN(u'This is a simple test. With a couple of sentences.')
result = Doc(orig.vocab).from_bytes(orig.to_bytes())
for word in result:
assert word.head.i == orig[word.i].head.i
if word.head is not word:
assert word.i in [w.i for w in word.head.children]
for child in word.lefts:
assert child.head.i == word.i
for child in word.rights:
assert child.head.i == word.i
@pytest.mark.models
def test_lemmas(EN):
orig = EN(u'The geese are flying')
result = Doc(orig.vocab).from_bytes(orig.to_bytes())
the, geese, are, flying = result
assert geese.lemma_ == 'goose'
assert are.lemma_ == 'be'
assert flying.lemma_ == 'fly'
| {
"content_hash": "32866957be4e772c525bd6afbb161343",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 68,
"avg_line_length": 28.764705882352942,
"alnum_prop": 0.6319018404907976,
"repo_name": "pombredanne/spaCy",
"id": "f90bb20c2473d6873041cc310118fc3f11ff25d4",
"size": "1467",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spacy/tests/serialize/test_io.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "315320"
},
{
"name": "Groff",
"bytes": "188349"
},
{
"name": "HTML",
"bytes": "544516"
},
{
"name": "Makefile",
"bytes": "89484"
},
{
"name": "PostScript",
"bytes": "460967"
},
{
"name": "Python",
"bytes": "516087"
},
{
"name": "Shell",
"bytes": "96067"
}
],
"symlink_target": ""
} |
@implementation SMState
@synthesize entry = _entry;
@synthesize exit = _exit;
- (id)initWithName:(NSString *)name {
return [super initWithName:name];
}
- (void)setEntrySelector:(SEL)entrySel executeIn:(NSObject *)object {
self.entry = [SMAction actionWithSel:entrySel executeIn:object];
}
- (void)setExitSelector:(SEL)exitSel executeIn:(NSObject *)object {
self.exit = [SMAction actionWithSel:exitSel executeIn:object];
}
- (void)setEntrySelector:(SEL)entrySel {
self.entry = [SMAction actionWithSel:entrySel];
}
- (void)setEntrySelectors:(SEL)firstSelector,...{
va_list args;
va_start(args, firstSelector);
self.entry = [SMCompositeAction actionWithFirstSelector:firstSelector andVaList:args];
va_end(args);
}
- (void)setExitSelector:(SEL)exitSel {
self.exit = [SMAction actionWithSel:exitSel];
}
- (void)setExitSelectors:(SEL)firstSelector,...{
va_list args;
va_start(args, firstSelector);
self.exit = [SMCompositeAction actionWithFirstSelector:firstSelector andVaList:args];
va_end(args);
}
- (void)_postEvent:(NSString *)event withContext:(SMStateMachineExecuteContext *)context {
SMTransition *curTr = [self _getTransitionForEvent:event];
if ([context.monitor respondsToSelector:@selector(receiveEvent:forState:foundTransition:)]) {
[context.monitor receiveEvent:event forState:self foundTransition:curTr];
}
if (curTr != nil) {
const BOOL shouldChangeStates = (nil != curTr.to);
// Exit the old state.
if (shouldChangeStates) {
[self _exitWithContext:context];
context.curState = curTr.to;
}
// Execute the transition action.
[[curTr action] executeWithGlobalObject:context.globalExecuteIn];
// Enter the new state.
if (shouldChangeStates) {
[context.curState _entryWithContext:context];
}
// Inform the monitor.
if ([context.monitor respondsToSelector:@selector(didExecuteTransitionFrom:to:withEvent:)]) {
[context.monitor didExecuteTransitionFrom:curTr.from to:context.curState withEvent:event];
}
}
}
- (void)_entryWithContext:(SMStateMachineExecuteContext *)context {
[self.entry executeWithGlobalObject:context.globalExecuteIn];
}
- (void)_exitWithContext:(SMStateMachineExecuteContext *)context {
[self.exit executeWithGlobalObject:context.globalExecuteIn];
}
@end | {
"content_hash": "6eebd7f817d442eae18ccd389e8777c7",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 102,
"avg_line_length": 29.662650602409638,
"alnum_prop": 0.690089358245329,
"repo_name": "fredmajor/WDFlickrPhotoUploader",
"id": "67e0b9255e8a011e665a40eee4ae991e09795768",
"size": "2654",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Pod/Classes/External/SMStateMachine/SMState.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "502880"
},
{
"name": "Ruby",
"bytes": "1150"
},
{
"name": "Shell",
"bytes": "17226"
}
],
"symlink_target": ""
} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.opentransport.rdfmapper.nmbs.containers;
public class NetworkDisturbance {
private String headerText;
private String descriptionText;
private String url;
private String language;
private long start; // Unix Epoch
private long end; // Unix Epoch
private int startStationId;
private int endStationId;
private int impactStationId;
private String id;
public NetworkDisturbance(String headerText, String descriptionText, String url, String language, long start, long end, int startStationId, int endStationId, int impactStationId, String id) {
this.headerText = headerText;
this.descriptionText = descriptionText;
this.url = url;
this.language = language;
this.start = start;
this.end = end;
this.startStationId = startStationId;
this.endStationId = endStationId;
this.impactStationId = impactStationId;
this.id = id;
}
public String getHeaderText() {
return headerText;
}
public void setHeaderText(String headerText) {
this.headerText = headerText;
}
public String getDescriptionText() {
return descriptionText;
}
public void setDescriptionText(String descriptionText) {
this.descriptionText = descriptionText;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public long getStart() {
return start;
}
public void setStart(long start) {
this.start = start;
}
public long getEnd() {
return end;
}
public void setEnd(long end) {
this.end = end;
}
public int getStartStationId() {
return startStationId;
}
public void setStartStationId(int startStationId) {
this.startStationId = startStationId;
}
public int getEndStationId() {
return endStationId;
}
public void setEndStationId(int endStationId) {
this.endStationId = endStationId;
}
public int getImpactStationId() {
return impactStationId;
}
public void setImpactStationId(int impactStationId) {
this.impactStationId = impactStationId;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
} | {
"content_hash": "2ae40ff81a2dcceba3f76be67215c5a4",
"timestamp": "",
"source": "github",
"line_count": 113,
"max_line_length": 195,
"avg_line_length": 24,
"alnum_prop": 0.6423303834808259,
"repo_name": "iRail/brail2gtfs-rt",
"id": "a3c0856a5ab61194dab820f66294f40855af8816",
"size": "2712",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/opentransport/rdfmapper/nmbs/containers/NetworkDisturbance.java",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "103218"
},
{
"name": "Protocol Buffer",
"bytes": "28067"
}
],
"symlink_target": ""
} |
@interface NSObject (RunTime)
+ (NSSet *)propertiesNames;
+ (NSSet *)allPropertiesNames;
+ (NSSet *)subclassesNames;
- (NSString *)fullDescription;
@end
#endif | {
"content_hash": "27e48b9c0dd973151cf10d99992cb195",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 30,
"avg_line_length": 12.692307692307692,
"alnum_prop": 0.7151515151515152,
"repo_name": "noughts/WebHere",
"id": "e7928d41799d614f2222d11393b3b8e08dd46703",
"size": "1474",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Pod/Classes/NSObject+Runtime.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "6423"
},
{
"name": "C++",
"bytes": "853"
},
{
"name": "Objective-C",
"bytes": "754409"
},
{
"name": "Ruby",
"bytes": "4273"
},
{
"name": "Shell",
"bytes": "7884"
}
],
"symlink_target": ""
} |
<!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.7.0_67) on Wed Oct 08 15:57:24 PDT 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class org.apache.hadoop.hbase.filter.KeyOnlyFilter (HBase 0.98.7-hadoop2 API)</title>
<meta name="date" content="2014-10-08">
<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 org.apache.hadoop.hbase.filter.KeyOnlyFilter (HBase 0.98.7-hadoop2 API)";
}
//-->
</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="../../../../../../org/apache/hadoop/hbase/filter/KeyOnlyFilter.html" title="class in org.apache.hadoop.hbase.filter">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-all.html">Index</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/hadoop/hbase/filter/class-use/KeyOnlyFilter.html" target="_top">Frames</a></li>
<li><a href="KeyOnlyFilter.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.hadoop.hbase.filter.KeyOnlyFilter" class="title">Uses of Class<br>org.apache.hadoop.hbase.filter.KeyOnlyFilter</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="../../../../../../org/apache/hadoop/hbase/filter/KeyOnlyFilter.html" title="class in org.apache.hadoop.hbase.filter">KeyOnlyFilter</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.hadoop.hbase.filter">org.apache.hadoop.hbase.filter</a></td>
<td class="colLast">
<div class="block">Provides row-level filters applied to HRegion scan results during calls to
<a href="../../../../../../org/apache/hadoop/hbase/client/ResultScanner.html#next()"><code>ResultScanner.next()</code></a>.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.apache.hadoop.hbase.filter">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../org/apache/hadoop/hbase/filter/KeyOnlyFilter.html" title="class in org.apache.hadoop.hbase.filter">KeyOnlyFilter</a> in <a href="../../../../../../org/apache/hadoop/hbase/filter/package-summary.html">org.apache.hadoop.hbase.filter</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../org/apache/hadoop/hbase/filter/package-summary.html">org.apache.hadoop.hbase.filter</a> that return <a href="../../../../../../org/apache/hadoop/hbase/filter/KeyOnlyFilter.html" title="class in org.apache.hadoop.hbase.filter">KeyOnlyFilter</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>static <a href="../../../../../../org/apache/hadoop/hbase/filter/KeyOnlyFilter.html" title="class in org.apache.hadoop.hbase.filter">KeyOnlyFilter</a></code></td>
<td class="colLast"><span class="strong">KeyOnlyFilter.</span><code><strong><a href="../../../../../../org/apache/hadoop/hbase/filter/KeyOnlyFilter.html#parseFrom(byte[])">parseFrom</a></strong>(byte[] pbBytes)</code> </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="../../../../../../org/apache/hadoop/hbase/filter/KeyOnlyFilter.html" title="class in org.apache.hadoop.hbase.filter">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-all.html">Index</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/hadoop/hbase/filter/class-use/KeyOnlyFilter.html" target="_top">Frames</a></li>
<li><a href="KeyOnlyFilter.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>Copyright © 2014 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "02bf5ed8fd508d51c958355219595f59",
"timestamp": "",
"source": "github",
"line_count": 160,
"max_line_length": 347,
"avg_line_length": 42.925,
"alnum_prop": 0.6370122306348281,
"repo_name": "gsoundar/mambo-ec2-deploy",
"id": "71e7a11bf9e73bc9258d854a309f5f0bcbed3172",
"size": "6868",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/hbase-0.98.7-hadoop2/docs/devapidocs/org/apache/hadoop/hbase/filter/class-use/KeyOnlyFilter.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "23179"
},
{
"name": "CSS",
"bytes": "39965"
},
{
"name": "HTML",
"bytes": "263271260"
},
{
"name": "Java",
"bytes": "103085"
},
{
"name": "JavaScript",
"bytes": "1347"
},
{
"name": "Python",
"bytes": "4101"
},
{
"name": "Ruby",
"bytes": "262588"
},
{
"name": "Shell",
"bytes": "118548"
}
],
"symlink_target": ""
} |
template <typename T>
SD_LIB_HIDDEN void NDArray::applyTriplewiseLambda(NDArray& second, NDArray& third,
const std::function<T(T, T, T)>& func, NDArray& target) {
if (dataType() != DataTypeUtils::fromT<T>())
throw std::runtime_error(
"NDArray::applyTriplewiseLambda<T> method: wrong template parameter T, its type should be the same as type of "
"this array!");
if (dataType() != second.dataType() || dataType() != third.dataType() || dataType() != target.dataType())
throw std::runtime_error(
"NDArray::applyTriplewiseLambda<T> method: bother four arrays (this, second, third, target) should have the "
"same type !");
if (this->lengthOf() != second.lengthOf() || this->lengthOf() != third.lengthOf() || !this->isSameShape(second) ||
!this->isSameShape(third)) {
sd_printf("applyTriplewiseLambda requires all operands to have the same shape\n", "");
throw std::runtime_error("Shapes mismatch");
}
auto f = this->bufferAsT<T>();
auto s = second.bufferAsT<T>();
auto t = third.bufferAsT<T>();
auto z = target.bufferAsT<T>();
if (this->ordering() == second.ordering() && this->ordering() == third.ordering() &&
this->ordering() == target.ordering() && (this->ews() == 1 && target.ews() == 1) && this->ews() == second.ews() &&
this->ews() == third.ews()) {
auto loop = PRAGMA_THREADS_FOR {
for (auto e = start; e < stop; e++) z[e] = func(f[e], s[e], t[e]);
};
samediff::Threads::parallel_for(loop, 0, _length);
} else {
if (f == z) {
auto loop = PRAGMA_THREADS_FOR {
for (auto e = start; e < stop; e++) {
auto tOffset = this->getOffset(e);
auto uOffset = second.getOffset(e);
auto vOffset = third.getOffset(e);
f[tOffset] = func(f[tOffset], s[uOffset], t[vOffset]);
}
};
samediff::Threads::parallel_for(loop, 0, _length);
} else {
auto loop = PRAGMA_THREADS_FOR {
for (auto e = start; e < stop; e++) {
auto tOffset = this->getOffset(e);
auto uOffset = second.getOffset(e);
auto vOffset = third.getOffset(e);
auto zOffset = target.getOffset(e);
z[zOffset] = func(f[tOffset], s[uOffset], t[vOffset]);
}
};
samediff::Threads::parallel_for(loop, 0, _length);
}
}
}
template SD_LIB_HIDDEN void NDArray::applyTriplewiseLambda(NDArray& second, NDArray& third,
const std::function<double(double, double, double)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyTriplewiseLambda(NDArray& second, NDArray& third,
const std::function<float(float, float, float)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyTriplewiseLambda(
NDArray& second, NDArray& third, const std::function<float16(float16, float16, float16)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyTriplewiseLambda(
NDArray& second, NDArray& third, const std::function<bfloat16(bfloat16, bfloat16, bfloat16)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyTriplewiseLambda(
NDArray& second, NDArray& third, const std::function<sd::LongType(sd::LongType, sd::LongType, sd::LongType)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyTriplewiseLambda(NDArray& second, NDArray& third,
const std::function<int(int, int, int)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyTriplewiseLambda(
NDArray& second, NDArray& third, const std::function<int16_t(int16_t, int16_t, int16_t)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyTriplewiseLambda(
NDArray& second, NDArray& third, const std::function<uint8_t(uint8_t, uint8_t, uint8_t)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyTriplewiseLambda(
NDArray& second, NDArray& third, const std::function<uint16_t(uint16_t, uint16_t, uint16_t)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyTriplewiseLambda(
NDArray& second, NDArray& third, const std::function<uint32_t(uint32_t, uint32_t, uint32_t)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyTriplewiseLambda(
NDArray& second, NDArray& third, const std::function<uint64_t(uint64_t, uint64_t, uint64_t)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyTriplewiseLambda(NDArray& second, NDArray& third,
const std::function<int8_t(int8_t, int8_t, int8_t)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyTriplewiseLambda(NDArray& second, NDArray& third,
const std::function<bool(bool, bool, bool)>& func,
NDArray& target);
//////////////////////////////////////////////////////////////////////////
template <typename T>
SD_LIB_HIDDEN void NDArray::applyPairwiseLambda(const NDArray& other, const std::function<T(T, T)>& func,
NDArray& target) {
if (dataType() != DataTypeUtils::fromT<T>())
throw std::runtime_error(
"NDArray::applyPairwiseLambda<T> method: wrong template parameter T, its type should be the same as type of "
"this array!");
if (dataType() != other.dataType() || dataType() != target.dataType())
throw std::runtime_error(
"NDArray::applyPairwiseLambda<T> method: all three arrays (this, other, target) must have the same type !");
// scalar is broadcastable
if (this->lengthOf() != other.lengthOf() && !this->isScalar() && !other.isScalar()) {
sd_printf("applyPairwiseLambda requires both operands to have the same shape\n", "");
throw std::runtime_error("Shapes mismatch");
}
auto f = this->bufferAsT<T>();
auto s = other.bufferAsT<T>();
auto z = target.bufferAsT<T>();
auto isTargetOrderEws = this->ordering() == target.ordering() && (this->ews() == 1 && target.ews() == 1);
if (other.isScalar()) {
auto otherVal = s[other.getOffset(0)];
if (isTargetOrderEws) {
auto loop = PRAGMA_THREADS_FOR {
for (auto e = start; e < stop; e++) z[e] = func(f[e], otherVal);
};
samediff::Threads::parallel_for(loop, 0, _length);
} else {
if (f == z) {
auto loop = PRAGMA_THREADS_FOR {
for (auto e = start; e < stop; e++) {
auto xOffset = this->getOffset(e);
f[xOffset] = func(f[xOffset], otherVal);
}
};
samediff::Threads::parallel_for(loop, 0, _length);
} else {
auto loop = PRAGMA_THREADS_FOR {
for (auto e = start; e < stop; e++) {
auto xOffset = this->getOffset(e);
auto zOffset = target.getOffset(e);
z[zOffset] = func(f[xOffset], otherVal);
}
};
samediff::Threads::parallel_for(loop, 0, _length);
}
}
} else if (isTargetOrderEws && this->ordering() == other.ordering() && this->ews() == other.ews()) {
auto loop = PRAGMA_THREADS_FOR {
for (auto e = start; e < stop; e++) z[e] = func(f[e], s[e]);
};
samediff::Threads::parallel_for(loop, 0, _length);
} else {
if (f == z) {
auto loop = PRAGMA_THREADS_FOR {
for (auto e = start; e < stop; e++) {
auto xOffset = this->getOffset(e);
auto yOffset = other.getOffset(e);
f[xOffset] = func(f[xOffset], s[yOffset]);
}
};
samediff::Threads::parallel_for(loop, 0, _length);
} else {
auto loop = PRAGMA_THREADS_FOR {
for (auto e = start; e < stop; e++) {
auto xOffset = this->getOffset(e);
auto yOffset = other.getOffset(e);
auto zOffset = target.getOffset(e);
z[zOffset] = func(f[xOffset], s[yOffset]);
}
};
samediff::Threads::parallel_for(loop, 0, _length);
}
}
}
template SD_LIB_HIDDEN void NDArray::applyPairwiseLambda(const NDArray& other,
const std::function<double(double, double)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyPairwiseLambda(const NDArray& other,
const std::function<float(float, float)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyPairwiseLambda(const NDArray& other,
const std::function<float16(float16, float16)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyPairwiseLambda(const NDArray& other,
const std::function<bfloat16(bfloat16, bfloat16)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyPairwiseLambda(
const NDArray& other, const std::function<sd::LongType(sd::LongType, sd::LongType)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyPairwiseLambda(const NDArray& other, const std::function<int(int, int)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyPairwiseLambda(const NDArray& other,
const std::function<int16_t(int16_t, int16_t)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyPairwiseLambda(const NDArray& other,
const std::function<uint8_t(uint8_t, uint8_t)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyPairwiseLambda(const NDArray& other,
const std::function<uint16_t(uint16_t, uint16_t)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyPairwiseLambda(const NDArray& other,
const std::function<uint32_t(uint32_t, uint32_t)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyPairwiseLambda(const NDArray& other,
const std::function<uint64_t(uint64_t, uint64_t)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyPairwiseLambda(const NDArray& other,
const std::function<int8_t(int8_t, int8_t)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyPairwiseLambda(const NDArray& other,
const std::function<bool(bool, bool)>& func, NDArray& target);
//////////////////////////////////////////////////////////////////////////
template <typename T>
SD_LIB_HIDDEN void NDArray::applyLambda(const std::function<T(T)>& func, NDArray& target) {
if (dataType() != DataTypeUtils::fromT<T>())
throw std::runtime_error(
"NDArray::applyLambda<T> method: wrong template parameter T, its type should be the same as type of this "
"array!");
if (dataType() != target.dataType())
throw std::runtime_error("NDArray::applyLambda<T> method: types of this and target array should match !");
auto f = this->bufferAsT<T>();
auto z = target.bufferAsT<T>();
if (this->ordering() == target.ordering() && (this->ews() == 1 && target.ews() == 1)) {
auto loop = PRAGMA_THREADS_FOR {
for (auto e = start; e < stop; e++) z[e] = func(f[e]);
};
samediff::Threads::parallel_for(loop, 0, _length);
} else {
if (f == z) {
auto loop = PRAGMA_THREADS_FOR {
for (auto e = start; e < stop; e++) {
auto xOffset = this->getOffset(e);
f[xOffset] = func(f[xOffset]);
}
};
samediff::Threads::parallel_for(loop, 0, _length);
} else {
auto loop = PRAGMA_THREADS_FOR {
for (auto e = start; e < stop; e++) {
auto xOffset = this->getOffset(e);
auto zOffset = target.getOffset(e);
z[zOffset] = func(f[xOffset]);
}
};
samediff::Threads::parallel_for(loop, 0, _length);
}
}
}
template SD_LIB_HIDDEN void NDArray::applyLambda(const std::function<double(double)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyLambda(const std::function<float(float)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyLambda(const std::function<float16(float16)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyLambda(const std::function<bfloat16(bfloat16)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyLambda(const std::function<sd::LongType(sd::LongType)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyLambda(const std::function<int16_t(int16_t)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyLambda(const std::function<int32_t(int32_t)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyLambda(const std::function<uint8_t(uint8_t)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyLambda(const std::function<uint16_t(uint16_t)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyLambda(const std::function<uint32_t(uint32_t)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyLambda(const std::function<uint64_t(uint64_t)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyLambda(const std::function<int8_t(int8_t)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyLambda(const std::function<bool(bool)>& func, NDArray& target);
//////////////////////////////////////////////////////////////////////////
template <typename T>
SD_LIB_HIDDEN void NDArray::applyIndexedLambda(const std::function<T(sd::LongType, T)>& func, NDArray& target) {
if (dataType() != DataTypeUtils::fromT<T>())
throw std::runtime_error(
"NDArray::applyIndexedLambda<T> method: wrong template parameter T, its type should be the same as type of "
"this array!");
if (dataType() != target.dataType())
throw std::runtime_error("NDArray::applyIndexedLambda<T> method: types of this and target array should match !");
auto f = this->bufferAsT<T>();
auto z = target.bufferAsT<T>();
if (this->ordering() == target.ordering() && (this->ews() == 1 && target.ews() == 1)) {
auto loop = PRAGMA_THREADS_FOR {
for (auto e = start; e < stop; e++) z[e] = func(e, f[e]);
};
samediff::Threads::parallel_for(loop, 0, _length);
} else {
if (f == z) {
auto loop = PRAGMA_THREADS_FOR {
for (auto e = start; e < stop; e++) {
auto xOffset = this->getOffset(e);
f[xOffset] = func(e, f[xOffset]);
}
};
samediff::Threads::parallel_for(loop, 0, _length);
} else {
auto loop = PRAGMA_THREADS_FOR {
for (auto e = start; e < stop; e++) {
auto xOffset = this->getOffset(e);
auto zOffset = target.getOffset(e);
z[zOffset] = func(e, f[xOffset]);
}
};
samediff::Threads::parallel_for(loop, 0, _length);
}
}
}
template SD_LIB_HIDDEN void NDArray::applyIndexedLambda(const std::function<double(sd::LongType, double)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyIndexedLambda(const std::function<float(sd::LongType, float)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyIndexedLambda(const std::function<float16(sd::LongType, float16)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyIndexedLambda(const std::function<bfloat16(sd::LongType, bfloat16)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyIndexedLambda(
const std::function<sd::LongType(sd::LongType, sd::LongType)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyIndexedLambda(const std::function<int(sd::LongType, int)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyIndexedLambda(const std::function<int16_t(sd::LongType, int16_t)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyIndexedLambda(const std::function<uint8_t(sd::LongType, uint8_t)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyIndexedLambda(const std::function<uint16_t(sd::LongType, uint16_t)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyIndexedLambda(const std::function<uint32_t(sd::LongType, uint32_t)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyIndexedLambda(const std::function<uint64_t(sd::LongType, uint64_t)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyIndexedLambda(const std::function<int8_t(sd::LongType, int8_t)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyIndexedLambda(const std::function<bool(sd::LongType, bool)>& func,
NDArray& target);
//////////////////////////////////////////////////////////////////////////
template <typename T>
SD_LIB_HIDDEN void NDArray::applyIndexedPairwiseLambda(NDArray& other, const std::function<T(sd::LongType, T, T)>& func,
NDArray& target) {
if (dataType() != DataTypeUtils::fromT<T>())
throw std::runtime_error(
"NDArray::applyIndexedPairwiseLambda<T> method: wrong template parameter T, its type should be the same as "
"type of this array!");
if (dataType() != target.dataType())
throw std::runtime_error(
"NDArray::applyIndexedPairwiseLambda<T> method: types of this and target array should match !");
if (this->lengthOf() != other.lengthOf()) {
sd_printf("applyIndexedPairwiseLambda requires both operands to have the same shape\n", "");
throw std::runtime_error("Shapes mismatch");
}
auto f = this->bufferAsT<T>();
auto s = other.bufferAsT<T>();
auto z = target.bufferAsT<T>();
if (this->ordering() == other.ordering() && this->ordering() == target.ordering() &&
(this->ews() == 1 && target.ews() == 1) && this->ews() == other.ews()) {
auto loop = PRAGMA_THREADS_FOR {
for (auto e = start; e < stop; e++) z[e] = func((sd::LongType)e, f[e], s[e]);
};
samediff::Threads::parallel_for(loop, 0, _length);
} else {
if (f == z) {
auto loop = PRAGMA_THREADS_FOR {
for (auto e = start; e < stop; e++) {
auto xOffset = this->getOffset(e);
auto yOffset = other.getOffset(e);
f[xOffset] = func((sd::LongType)e, f[xOffset], s[yOffset]);
}
};
samediff::Threads::parallel_for(loop, 0, _length);
} else {
auto loop = PRAGMA_THREADS_FOR {
for (auto e = start; e < stop; e++) {
auto xOffset = this->getOffset(e);
auto yOffset = other.getOffset(e);
auto zOffset = target.getOffset(e);
z[zOffset] = func((sd::LongType)e, f[xOffset], s[yOffset]);
}
};
samediff::Threads::parallel_for(loop, 0, _length);
}
}
}
template SD_LIB_HIDDEN void NDArray::applyIndexedPairwiseLambda(
NDArray& other, const std::function<double(sd::LongType, double, double)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyIndexedPairwiseLambda(
NDArray& other, const std::function<float(sd::LongType, float, float)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyIndexedPairwiseLambda(
NDArray& other, const std::function<float16(sd::LongType, float16, float16)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyIndexedPairwiseLambda(
NDArray& other, const std::function<bfloat16(sd::LongType, bfloat16, bfloat16)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyIndexedPairwiseLambda(
NDArray& other, const std::function<sd::LongType(sd::LongType, sd::LongType, sd::LongType)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyIndexedPairwiseLambda(NDArray& other,
const std::function<int(sd::LongType, int, int)>& func,
NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyIndexedPairwiseLambda(
NDArray& other, const std::function<int16_t(sd::LongType, int16_t, int16_t)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyIndexedPairwiseLambda(
NDArray& other, const std::function<uint8_t(sd::LongType, uint8_t, uint8_t)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyIndexedPairwiseLambda(
NDArray& other, const std::function<uint16_t(sd::LongType, uint16_t, uint16_t)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyIndexedPairwiseLambda(
NDArray& other, const std::function<uint32_t(sd::LongType, uint32_t, uint32_t)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyIndexedPairwiseLambda(
NDArray& other, const std::function<uint64_t(sd::LongType, uint64_t, uint64_t)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyIndexedPairwiseLambda(
NDArray& other, const std::function<int8_t(sd::LongType, int8_t, int8_t)>& func, NDArray& target);
template SD_LIB_HIDDEN void NDArray::applyIndexedPairwiseLambda(
NDArray& other, const std::function<bool(sd::LongType, bool, bool)>& func, NDArray& target);
| {
"content_hash": "eb984ff44510542f02fd303df4c44538",
"timestamp": "",
"source": "github",
"line_count": 433,
"max_line_length": 120,
"avg_line_length": 52.91916859122402,
"alnum_prop": 0.5777254080474818,
"repo_name": "deeplearning4j/deeplearning4j",
"id": "39af1ba76dfb4d55f3ff75a425589528ea7b3248",
"size": "23803",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "libnd4j/include/array/cpu/NDArrayLambda.hpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1458"
},
{
"name": "C",
"bytes": "165340"
},
{
"name": "C++",
"bytes": "17817311"
},
{
"name": "CMake",
"bytes": "112697"
},
{
"name": "CSS",
"bytes": "12974"
},
{
"name": "Cuda",
"bytes": "2413085"
},
{
"name": "Cython",
"bytes": "12094"
},
{
"name": "FreeMarker",
"bytes": "77257"
},
{
"name": "HTML",
"bytes": "18609"
},
{
"name": "Java",
"bytes": "47657420"
},
{
"name": "JavaScript",
"bytes": "296767"
},
{
"name": "Kotlin",
"bytes": "2041047"
},
{
"name": "PureBasic",
"bytes": "12254"
},
{
"name": "Python",
"bytes": "77566"
},
{
"name": "Ruby",
"bytes": "4558"
},
{
"name": "Scala",
"bytes": "1026"
},
{
"name": "Shell",
"bytes": "92012"
},
{
"name": "Smarty",
"bytes": "975"
},
{
"name": "Starlark",
"bytes": "931"
},
{
"name": "TypeScript",
"bytes": "81217"
}
],
"symlink_target": ""
} |
<?php
namespace DesignPatterns\Creational\FactoryMethod;
use DesignPatterns\Creational\Builder\BuilderInterface;
/**
* class FactoryMethod
*/
abstract class FactoryMethod
{
const CHEAP = 1;
const FAST = 2;
/**
* The children of the class must implement this method
*
* Sometimes this method can be public to get "raw" object
*
* @param string $type a generic type
*
* @return VehicleInterface a new vehicle
*/
abstract protected function createVehicle($type);
/**
* Creates a new vehicle
*
* @param int $type
*
* @return VehicleInterface a new vehicle
*/
public function create($type)
{
$obj = $this->createVehicle($type);
$obj->setColor("#f00");
return $obj;
}
}
| {
"content_hash": "0da5a3de86c0b896cefe520d5ad6d2ec",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 62,
"avg_line_length": 20.075,
"alnum_prop": 0.6077210460772104,
"repo_name": "ineista/pattern",
"id": "3c2755820defb0dd95d480b635febfc895f7a260",
"size": "803",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Creational/FactoryMethod/FactoryMethod.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "128351"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://maven.apache.org/POM/4.0.0
https://maven.apache.org/maven-v4_0_0.xsd
"
>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>ca.bc.gov.open.cpf</groupId>
<artifactId>cpf-parent</artifactId>
<version>6.1.x-SNAPSHOT</version>
</parent>
<artifactId>tests</artifactId>
<name>CPF Unit Tests</name>
<description>CPF Unit Tests</description>
<dependencies>
<dependency>
<groupId>ca.bc.gov.open.cpf</groupId>
<artifactId>cpf-api-app</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>ca.bc.gov.open.cpf</groupId>
<artifactId>cpf-api-client</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
| {
"content_hash": "a36a1f3a446f9aa9d710feffdb325838",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 55,
"avg_line_length": 28.605263157894736,
"alnum_prop": 0.6550137994480221,
"repo_name": "revolsys/ca.bc.gov.open.cpf",
"id": "bb7c761ae60a2e199d7668508a2faf967894579e",
"size": "1087",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "tests/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5176"
},
{
"name": "CSS",
"bytes": "6120"
},
{
"name": "HTML",
"bytes": "29245"
},
{
"name": "Java",
"bytes": "1570567"
},
{
"name": "JavaScript",
"bytes": "37325"
},
{
"name": "PLSQL",
"bytes": "2068"
},
{
"name": "PLpgSQL",
"bytes": "4803"
},
{
"name": "SQLPL",
"bytes": "384"
},
{
"name": "Shell",
"bytes": "6430"
},
{
"name": "Visual Basic",
"bytes": "1703"
}
],
"symlink_target": ""
} |
@interface RadioDetailInfoModel : BaseModel
@property (nonatomic, copy) NSString *coverimg;
@property (nonatomic, copy) NSString *desc;
@property (nonatomic, copy) NSString *radioid;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, strong) NSNumber *musicvisitnum;
@property (nonatomic, strong) RadioUserInfoModel *userInfo;
@end
| {
"content_hash": "f4ee022fbe2d95cecb7bd891169137cd",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 59,
"avg_line_length": 31.90909090909091,
"alnum_prop": 0.7806267806267806,
"repo_name": "NeighborWangShushu/Leisure",
"id": "b3974ee197bf0d4099182fa6d62a188f15d3cb44",
"size": "542",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Leisure/CodeClass/Radio/Model/RadioDetailInfoModel.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "8625"
},
{
"name": "Objective-C",
"bytes": "198667"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.