text stringlengths 2 1.04M | meta dict |
|---|---|
package runtime_test
import (
"bytes"
"runtime"
"testing"
)
const (
typeScalar = 0
typePointer = 1
)
// TestGCInfo tests that various objects in heap, data and bss receive correct GC pointer type info.
func TestGCInfo(t *testing.T) {
verifyGCInfo(t, "bss Ptr", &bssPtr, infoPtr)
verifyGCInfo(t, "bss ScalarPtr", &bssScalarPtr, infoScalarPtr)
verifyGCInfo(t, "bss PtrScalar", &bssPtrScalar, infoPtrScalar)
verifyGCInfo(t, "bss BigStruct", &bssBigStruct, infoBigStruct())
verifyGCInfo(t, "bss string", &bssString, infoString)
verifyGCInfo(t, "bss slice", &bssSlice, infoSlice)
verifyGCInfo(t, "bss eface", &bssEface, infoEface)
verifyGCInfo(t, "bss iface", &bssIface, infoIface)
verifyGCInfo(t, "data Ptr", &dataPtr, infoPtr)
verifyGCInfo(t, "data ScalarPtr", &dataScalarPtr, infoScalarPtr)
verifyGCInfo(t, "data PtrScalar", &dataPtrScalar, infoPtrScalar)
verifyGCInfo(t, "data BigStruct", &dataBigStruct, infoBigStruct())
verifyGCInfo(t, "data string", &dataString, infoString)
verifyGCInfo(t, "data slice", &dataSlice, infoSlice)
verifyGCInfo(t, "data eface", &dataEface, infoEface)
verifyGCInfo(t, "data iface", &dataIface, infoIface)
{
var x Ptr
verifyGCInfo(t, "stack Ptr", &x, infoPtr)
runtime.KeepAlive(x)
}
{
var x ScalarPtr
verifyGCInfo(t, "stack ScalarPtr", &x, infoScalarPtr)
runtime.KeepAlive(x)
}
{
var x PtrScalar
verifyGCInfo(t, "stack PtrScalar", &x, infoPtrScalar)
runtime.KeepAlive(x)
}
{
var x BigStruct
verifyGCInfo(t, "stack BigStruct", &x, infoBigStruct())
runtime.KeepAlive(x)
}
{
var x string
verifyGCInfo(t, "stack string", &x, infoString)
runtime.KeepAlive(x)
}
{
var x []string
verifyGCInfo(t, "stack slice", &x, infoSlice)
runtime.KeepAlive(x)
}
{
var x any
verifyGCInfo(t, "stack eface", &x, infoEface)
runtime.KeepAlive(x)
}
{
var x Iface
verifyGCInfo(t, "stack iface", &x, infoIface)
runtime.KeepAlive(x)
}
for i := 0; i < 10; i++ {
verifyGCInfo(t, "heap Ptr", runtime.Escape(new(Ptr)), trimDead(infoPtr))
verifyGCInfo(t, "heap PtrSlice", runtime.Escape(&make([]*byte, 10)[0]), trimDead(infoPtr10))
verifyGCInfo(t, "heap ScalarPtr", runtime.Escape(new(ScalarPtr)), trimDead(infoScalarPtr))
verifyGCInfo(t, "heap ScalarPtrSlice", runtime.Escape(&make([]ScalarPtr, 4)[0]), trimDead(infoScalarPtr4))
verifyGCInfo(t, "heap PtrScalar", runtime.Escape(new(PtrScalar)), trimDead(infoPtrScalar))
verifyGCInfo(t, "heap BigStruct", runtime.Escape(new(BigStruct)), trimDead(infoBigStruct()))
verifyGCInfo(t, "heap string", runtime.Escape(new(string)), trimDead(infoString))
verifyGCInfo(t, "heap eface", runtime.Escape(new(any)), trimDead(infoEface))
verifyGCInfo(t, "heap iface", runtime.Escape(new(Iface)), trimDead(infoIface))
}
}
func verifyGCInfo(t *testing.T, name string, p any, mask0 []byte) {
mask := runtime.GCMask(p)
if !bytes.Equal(mask, mask0) {
t.Errorf("bad GC program for %v:\nwant %+v\ngot %+v", name, mask0, mask)
return
}
}
func trimDead(mask []byte) []byte {
for len(mask) > 0 && mask[len(mask)-1] == typeScalar {
mask = mask[:len(mask)-1]
}
return mask
}
var infoPtr = []byte{typePointer}
type Ptr struct {
*byte
}
var infoPtr10 = []byte{typePointer, typePointer, typePointer, typePointer, typePointer, typePointer, typePointer, typePointer, typePointer, typePointer}
type ScalarPtr struct {
q int
w *int
e int
r *int
t int
y *int
}
var infoScalarPtr = []byte{typeScalar, typePointer, typeScalar, typePointer, typeScalar, typePointer}
var infoScalarPtr4 = append(append(append(append([]byte(nil), infoScalarPtr...), infoScalarPtr...), infoScalarPtr...), infoScalarPtr...)
type PtrScalar struct {
q *int
w int
e *int
r int
t *int
y int
}
var infoPtrScalar = []byte{typePointer, typeScalar, typePointer, typeScalar, typePointer, typeScalar}
type BigStruct struct {
q *int
w byte
e [17]byte
r []byte
t int
y uint16
u uint64
i string
}
func infoBigStruct() []byte {
switch runtime.GOARCH {
case "386", "arm", "mips", "mipsle":
return []byte{
typePointer, // q *int
typeScalar, typeScalar, typeScalar, typeScalar, typeScalar, // w byte; e [17]byte
typePointer, typeScalar, typeScalar, // r []byte
typeScalar, typeScalar, typeScalar, typeScalar, // t int; y uint16; u uint64
typePointer, typeScalar, // i string
}
case "arm64", "amd64", "loong64", "mips64", "mips64le", "ppc64", "ppc64le", "riscv64", "s390x", "wasm":
return []byte{
typePointer, // q *int
typeScalar, typeScalar, typeScalar, // w byte; e [17]byte
typePointer, typeScalar, typeScalar, // r []byte
typeScalar, typeScalar, typeScalar, // t int; y uint16; u uint64
typePointer, typeScalar, // i string
}
default:
panic("unknown arch")
}
}
type Iface interface {
f()
}
type IfaceImpl int
func (IfaceImpl) f() {
}
var (
// BSS
bssPtr Ptr
bssScalarPtr ScalarPtr
bssPtrScalar PtrScalar
bssBigStruct BigStruct
bssString string
bssSlice []string
bssEface any
bssIface Iface
// DATA
dataPtr = Ptr{new(byte)}
dataScalarPtr = ScalarPtr{q: 1}
dataPtrScalar = PtrScalar{w: 1}
dataBigStruct = BigStruct{w: 1}
dataString = "foo"
dataSlice = []string{"foo"}
dataEface any = 42
dataIface Iface = IfaceImpl(42)
infoString = []byte{typePointer, typeScalar}
infoSlice = []byte{typePointer, typeScalar, typeScalar}
infoEface = []byte{typeScalar, typePointer}
infoIface = []byte{typeScalar, typePointer}
)
| {
"content_hash": "ff596dc6a4b6560d003215806dc1a1c6",
"timestamp": "",
"source": "github",
"line_count": 203,
"max_line_length": 152,
"avg_line_length": 27.423645320197043,
"alnum_prop": 0.6838512663912341,
"repo_name": "nawawi/go",
"id": "787160dc2779c8583240e35f0fcc60b172842da8",
"size": "5727",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "src/runtime/gcinfo_test.go",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "2677262"
},
{
"name": "Awk",
"bytes": "450"
},
{
"name": "Batchfile",
"bytes": "8218"
},
{
"name": "C",
"bytes": "121521"
},
{
"name": "C++",
"bytes": "917"
},
{
"name": "Dockerfile",
"bytes": "2514"
},
{
"name": "Fortran",
"bytes": "394"
},
{
"name": "Go",
"bytes": "45552264"
},
{
"name": "HTML",
"bytes": "2621340"
},
{
"name": "JavaScript",
"bytes": "20486"
},
{
"name": "Makefile",
"bytes": "748"
},
{
"name": "Perl",
"bytes": "31365"
},
{
"name": "Python",
"bytes": "15702"
},
{
"name": "Shell",
"bytes": "61020"
}
],
"symlink_target": ""
} |
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const makeSerializable = require("../util/makeSerializable");
const HarmonyExportInitFragment = require("./HarmonyExportInitFragment");
const NullDependency = require("./NullDependency");
/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
/** @typedef {import("../Dependency")} Dependency */
/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */
/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
/** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */
class HarmonyExportSpecifierDependency extends NullDependency {
constructor(id, name) {
super();
this.id = id;
this.name = name;
}
get type() {
return "harmony export specifier";
}
/**
* Returns the exported names
* @param {ModuleGraph} moduleGraph module graph
* @returns {ExportsSpec | undefined} export names
*/
getExports(moduleGraph) {
return {
exports: [this.name],
terminalBinding: true,
dependencies: undefined
};
}
/**
* @param {ModuleGraph} moduleGraph the module graph
* @returns {ConnectionState} how this dependency connects the module to referencing modules
*/
getModuleEvaluationSideEffectsState(moduleGraph) {
return false;
}
serialize(context) {
const { write } = context;
write(this.id);
write(this.name);
super.serialize(context);
}
deserialize(context) {
const { read } = context;
this.id = read();
this.name = read();
super.deserialize(context);
}
}
makeSerializable(
HarmonyExportSpecifierDependency,
"webpack/lib/dependencies/HarmonyExportSpecifierDependency"
);
HarmonyExportSpecifierDependency.Template = class HarmonyExportSpecifierDependencyTemplate extends (
NullDependency.Template
) {
/**
* @param {Dependency} dependency the dependency for which the template should be applied
* @param {ReplaceSource} source the current replace source which can be modified
* @param {DependencyTemplateContext} templateContext the context object
* @returns {void}
*/
apply(
dependency,
source,
{ module, moduleGraph, initFragments, runtime, concatenationScope }
) {
const dep = /** @type {HarmonyExportSpecifierDependency} */ (dependency);
if (concatenationScope) {
concatenationScope.registerExport(dep.name, dep.id);
return;
}
const used = moduleGraph
.getExportsInfo(module)
.getUsedName(dep.name, runtime);
if (!used) {
const set = new Set();
set.add(dep.name || "namespace");
initFragments.push(
new HarmonyExportInitFragment(module.exportsArgument, undefined, set)
);
return;
}
const map = new Map();
map.set(used, `/* binding */ ${dep.id}`);
initFragments.push(
new HarmonyExportInitFragment(module.exportsArgument, map, undefined)
);
}
};
module.exports = HarmonyExportSpecifierDependency;
| {
"content_hash": "7fc535c47d7dd2e809b77192d9b852b8",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 101,
"avg_line_length": 27.318181818181817,
"alnum_prop": 0.7211314475873544,
"repo_name": "arvenil/resume",
"id": "d3735c48b849c25fd7f9c719e00d2213cb30189b",
"size": "3005",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "node_modules/webpack/lib/dependencies/HarmonyExportSpecifierDependency.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1704"
}
],
"symlink_target": ""
} |
package com.oneops.boo;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class BooYaml {
private Boo boo;
private BooAssembly assembly;
private Map<String, BooPlatform> platforms;
private Map<String, BooEnvironment> environments;
private BooEnvironment environment;
private Map<String, Map<String, Map<String, Map<String, String>>>> scale;
private Map<String, Object> variables;
public Boo getBoo() {
return boo;
}
public void setBoo(Boo boo) {
this.boo = boo;
}
public BooAssembly getAssembly() {
return assembly;
}
public void setAssembly(BooAssembly assembly) {
this.assembly = assembly;
}
public Map<String, BooPlatform> getPlatforms() {
return platforms;
}
public void setPlatforms(Map<String, BooPlatform> platforms) {
this.platforms = platforms;
}
public Map<String, BooEnvironment> getEnvironments() {
return environments;
}
public void setEnvironments(Map<String, BooEnvironment> environments) {
this.environments = environments;
}
public List<BooPlatform> getPlatformList() {
List<BooPlatform> platformList = Lists.newArrayList();
for (Entry<String, BooPlatform> entry : platforms.entrySet()) {
BooPlatform platform = entry.getValue();
platform.setName(entry.getKey());
platformList.add(platform);
}
return platformList;
}
public Map<String, Map<String, Map<String, Map<String, String>>>> getScale() {
return scale;
}
public void setScale(Map<String, Map<String, Map<String, Map<String, String>>>> scale) {
this.scale = scale;
}
public List<BooEnvironment> getEnvironmentList() {
List<BooEnvironment> environmentList = Lists.newArrayList();
if (this.environments != null && this.environments.size() > 0) {
for (Entry<String, BooEnvironment> entry : environments.entrySet()) {
BooEnvironment environment = entry.getValue();
environment.setName(entry.getKey());
environmentList.add(environment);
}
} else {
this.environment.setName(boo.getEnvironment_name());
environmentList.add(this.environment);
}
return environmentList;
}
public void setEnvironment(BooEnvironment environment) {
this.environment = environment;
}
public List<BooScale> getScaleList() {
List<BooScale> booScaleList = Lists.newArrayList();
for (Entry<String, Map<String, Map<String, Map<String, String>>>> entry0 : scale.entrySet()) {
String platformName = entry0.getKey();
Map<String, Map<String, String>> booScaleMap = entry0.getValue().get("scaling");
for (Entry<String, Map<String, String>> entry : booScaleMap.entrySet()) {
Map<String, String> scaleMap = entry.getValue();
BooScale booScale = new BooScale();
booScale.setPlatformName(platformName);
booScale.setComponentName(entry.getKey());
booScale.setCurrent(scaleMap.get("current"));
booScale.setMin(scaleMap.get("min"));
booScale.setMax(scaleMap.get("max"));
booScaleList.add(booScale);
}
}
return booScaleList;
}
public Map<String, Object> getVariables() {
return variables;
}
public void setVariables(Map<String, Object> variables) {
this.variables = variables;
}
}
| {
"content_hash": "13721e03a70b8086e83fb931a0590c5e",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 98,
"avg_line_length": 28.982608695652175,
"alnum_prop": 0.6864686468646864,
"repo_name": "okornev/oneops",
"id": "28fd703c9dc6634f16190019e8c9a3a9af34ece8",
"size": "3333",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "oneops-model/src/main/java/com/oneops/boo/BooYaml.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "959"
},
{
"name": "CSS",
"bytes": "110128"
},
{
"name": "HTML",
"bytes": "965028"
},
{
"name": "Java",
"bytes": "5145505"
},
{
"name": "JavaScript",
"bytes": "23642"
},
{
"name": "PLpgSQL",
"bytes": "2309562"
},
{
"name": "Perl",
"bytes": "209764"
},
{
"name": "Ruby",
"bytes": "1470362"
},
{
"name": "SQLPL",
"bytes": "8926"
},
{
"name": "Shell",
"bytes": "72909"
}
],
"symlink_target": ""
} |
import mock
import neutron.plugins.ml2.drivers.openvswitch.agent.common.constants \
as ovs_const
from neutron.tests.unit.plugins.ml2.drivers.openvswitch.agent.\
openflow.ovs_ofctl import ovs_bridge_test_base
call = mock.call # short hand
class OVSPhysicalBridgeTest(ovs_bridge_test_base.OVSBridgeTestBase,
ovs_bridge_test_base.OVSDVRProcessTestMixin):
dvr_process_table_id = ovs_const.DVR_PROCESS_VLAN
dvr_process_next_table_id = ovs_const.LOCAL_VLAN_TRANSLATION
def setUp(self):
super(OVSPhysicalBridgeTest, self).setUp()
self.setup_bridge_mock('br-phys', self.br_phys_cls)
def test_setup_default_table(self):
self.br.setup_default_table()
expected = [
call.add_flow(priority=0, table=0, actions='normal'),
]
self.assertEqual(expected, self.mock.mock_calls)
def test_provision_local_vlan(self):
port = 999
lvid = 888
segmentation_id = 777
distributed = False
self.br.provision_local_vlan(port=port, lvid=lvid,
segmentation_id=segmentation_id,
distributed=distributed)
expected = [
call.add_flow(priority=4, table=0, dl_vlan=lvid, in_port=port,
actions='mod_vlan_vid:%s,normal' % segmentation_id),
]
self.assertEqual(expected, self.mock.mock_calls)
def test_provision_local_vlan_novlan(self):
port = 999
lvid = 888
segmentation_id = None
distributed = False
self.br.provision_local_vlan(port=port, lvid=lvid,
segmentation_id=segmentation_id,
distributed=distributed)
expected = [
call.add_flow(priority=4, table=0, dl_vlan=lvid, in_port=port,
actions='strip_vlan,normal')
]
self.assertEqual(expected, self.mock.mock_calls)
def test_reclaim_local_vlan(self):
port = 999
lvid = 888
self.br.reclaim_local_vlan(port=port, lvid=lvid)
expected = [
call.delete_flows(dl_vlan=lvid, in_port=port),
]
self.assertEqual(expected, self.mock.mock_calls)
def test_add_dvr_mac_vlan(self):
mac = '00:02:b3:13:fe:3d'
port = 8888
self.br.add_dvr_mac_vlan(mac=mac, port=port)
expected = [
call.add_flow(priority=2, table=3, dl_src=mac,
actions='output:%s' % port),
]
self.assertEqual(expected, self.mock.mock_calls)
def test_remove_dvr_mac_vlan(self):
mac = '00:02:b3:13:fe:3d'
self.br.remove_dvr_mac_vlan(mac=mac)
expected = [
call.delete_flows(dl_src=mac, table=3),
]
self.assertEqual(expected, self.mock.mock_calls)
| {
"content_hash": "0e34b44315a20ffa6c11066a81a90b0f",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 78,
"avg_line_length": 35.72839506172839,
"alnum_prop": 0.580511402902557,
"repo_name": "noironetworks/neutron",
"id": "317294f5515b5f387b6cb45d3a1332dc5b52171c",
"size": "3617",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "neutron/tests/unit/plugins/ml2/drivers/openvswitch/agent/openflow/ovs_ofctl/test_br_phys.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Mako",
"bytes": "1047"
},
{
"name": "Python",
"bytes": "11420614"
},
{
"name": "Shell",
"bytes": "38791"
}
],
"symlink_target": ""
} |
```lua
local sprite = Sprite(width, height)
local sprite = Sprite(width, height, colorMode)
local sprite = Sprite(spec)
local sprite = Sprite(otherSprite)
local sprite = Sprite{ fromFile=filename }
local sprite = Sprite{ fromFile=filename, oneFrame }
```
Creates a new sprite with the given `width` and `height`. The
[color mode](colormode.md#colormode) is optional, [RGB](colormode.md#colormodergb)
by default.
The `spec` parameter is an [image specification](imagespec.md#imagespec) object.
If `otherSprite` is given (other `Sprite` object), the sprite is duplicated.
If `fromFile` is given, it indicates a file name (a string) and it's
like opening a new document with [`app.open()`](app.md#appopen).
## Sprite.width
```lua
local w = sprite.width
sprite.width = w
```
Returns or changes the sprite width. Use
[Sprite:resize](#spriteresize) if you want to change the sprite size
resizing layers, images, etc.
## Sprite.height
```lua
local h = sprite.height
sprite.height = h
```
Returns or changes the sprite height. Use
[Sprite:resize](#spriteresize) if you want to change the sprite size
resizing layers, images, etc.
## Sprite.bounds
```lua
local rectangle = sprite.bounds
```
Returns the bounds of the sprite as a
[rectangle](rectangle.md#rectangle) in the position `0,0`.
This is like calling `Rectangle{ x=0, y=0, width=sprite.width, height=sprite.height }`.
## Sprite.gridBounds
```lua
local rectangle = sprite.gridBounds
sprite.gridBounds = rectangle
```
Gets or sets the bounds of the sprite grid as a
[rectangle](rectangle.md#rectangle).
## Sprite.pixelRatio
```lua
local size = sprite.pixelRatio
sprite.pixelRatio = size
```
Gets or sets the pixel ratio of the sprite as a
[size](size.md#size).
## Sprite.selection
```lua
local selection = sprite.selection
sprite.selection = newSelection
```
Gets or sets the active sprite selection. This property is an instance
of the [Selection class](selection.md#selection) to manipulate the set of
selected pixels in the canvas.
## Sprite.filename
```lua
local name = sprite.filename
sprite.filename = newName
```
Gets or sets the name of the file from where this sprite was loaded or
saved. Or an empty string if this is a new sprite without an
associated file.
## Sprite.colorMode
Returns the [color mode](colormode.md#colormode) of this sprite.
## Sprite.spec
```lua
local spec = sprite.spec
```
The [specification](imagespec.md#imagespec) for image in this sprite.
## Sprite.frames
```lua
for i,frame in ipairs(s.frames) do
-- ...
end
for i = 1,#s.frames do
-- s.frames[i]
end
```
An array of [frames](frame.md#frame).
## Sprite.palettes
An array of [palettes](palette.md#palette). Generally it contains only one
palette (`sprite.palettes[1]`).
In the future we'll support multiple palettes to create
[color cycling animations](https://en.wikipedia.org/wiki/Color_cycling).
## Sprite.layers
```lua
for i,layer in ipairs(s.layers) do
-- ...
end
for i = 1,#s.layers do
-- s.layers[i]
end
```
An array of [layers](layer.md#layer).
## Sprite.cels
```lua
for i,cel in ipairs(s.cels) do
-- ...
end
for i = 1,#s.cels do
-- s.cels[i]
end
```
An array of [cels](cel.md#cel).
## Sprite.tags
```lua
for i,tag in ipairs(s.tags) do
-- ...
end
for i = 1,#s.tags do
-- s.tags[i]
end
```
An array of [tags](tag.md#tag).
## Sprite.slices
```lua
for i,slice in ipairs(s.slices) do
-- ...
end
for i = 1,#s.slices do
-- s.slices[i]
end
```
An array of [slices](slice.md#slice).
## Sprite.backgroundLayer
Returns the [background
layer](https://www.aseprite.org/docs/layers/#background-layer) a
[layer](layer.md#layer) object or `nil` if the sprite doesn't contain a
background layer.
## Sprite.transparentColor
```lua
local number = sprite.transparentColor
sprite.transparentColor = number
```
The transparent color is an intenger that specifies what index (`0` by
default) is the transparent color in transparent layers on indexed
sprites.
## Sprite:resize()
```lua
sprite:resize(width, height)
sprite:resize(size)
```
Resize the sprite (and all frames/cels) to the given dimensions. See
[Size class](size.md#size).
## Sprite:crop()
```lua
sprite:crop(x, y, width, height)
sprite:crop(rectangle)
```
Crops the sprite to the given dimensions. See the
[Rectangle class](rectangle.md#rectangle).
## Sprite:saveAs()
```lua
sprite:saveAs(filename)
```
Saves the sprite to the given file and mark the sprite as saved so
closing it doesn't will ask to save changes.
## Sprite:saveCopyAs()
```lua
sprite:saveCopyAs(filename)
```
Saves a copy of the sprite in the given file but doesn't change the
saved state of the sprite, if the sprite is modified and then try to
close it, the user will be asked to save changes.
## Sprite:close()
```lua
sprite:close()
```
Closes the sprite. This doesn't ask the user to save changes. If you
want to do the classic *File > Close* where the user is asking to save
changes, you can use `app.command.CloseFile()`.
## Sprite:loadPalette()
```lua
sprite:loadPalette(filename)
```
Sets the sprite palette loading it from the given file.
The same can be achieved using [`Palette{ fromFile }`](palette.md#palette):
```lua
sprite:setPalette(Palette{ fromFile=filename })
```
## Sprite:setPalette()
```lua
sprite:setPalette(palette)
```
Changes the sprite [palette](palette.md#palette).
## Sprite:assignColorSpace
```lua
local colorSpace = ColorSpace{ sRGB=true }
sprite:assignColorSpace(colorSpace)
```
Assign a new [color space](colorspace.md#colorspace) to the sprite without
modifying the sprite pixels.
## Sprite:convertColorSpace
```lua
local colorSpace = ColorSpace{ sRGB=true }
sprite:convertColorSpace(colorSpace)
```
Converts all the sprite pixels to a new [color space](colorspace.md#colorspace)
so the image looks the same as in the previous color space (all pixels
will be adjusted to the new color space).
## Sprite:newLayer()
```lua
local layer = sprite:newLayer()
```
Creates a new [layer](layer.md#layer) at the top of the layers stack.
## Sprite:newGroup()
```lua
local layerGroup = sprite:newGroup()
```
Creates a new empty [layer group](layer.md#layer) at the top of the layers stack.
## Sprite:deleteLayer()
```lua
sprite:deleteLayer(layer)
sprite:deleteLayer(layerName)
```
Deletes the given [layer](layer.md#layer) or the layer with the given `layerName` (a string).
## Sprite:newFrame()
```lua
local frame = sprite:newFrame(frame)
local frame = sprite:newFrame(frameNumber)
```
Creates a copy of the given [frame](frame.md#frame) object or frame number
and returns a [`Frame`](frame.md#frame) that points to the newly created
frame in `frameNumber` position.
## Sprite:newEmptyFrame()
Creates a new empty frame in the given `frameNumber` (an integer) and
returns the new [frame](frame.md#frame).
## Sprite:deleteFrame()
```lua
sprite:deleteFrame(frame)
```
## Sprite:newCel()
```lua
cel = sprite:newCel(layer, frame)
cel = sprite:newCel(layer, frame, image, position)
```
Creates a new [cel](cel.md#cel) in the given [layer](layer.md#layer) and `frame`
number. If the [image](image.md#image) is not specified, a new image will be
created with the size of the sprite canvas. The [position](point.md#point)
is a point to locate the image.
## Sprite:deleteCel()
```lua
sprite:deleteCel(cel)
sprite:deleteCel(layer, frame)
```
Deletes the given [cel](cel.md#cel). If the cel is from a transparent
layer, the cel is completely deleted, but if the cel is from a
background layer, the cel will be delete with the
[background color](app.md#appbgcolor).
## Sprite:newTag()
```lua
local tag = sprite:newTag(fromFrameNumber, toFrameNumber)
```
Creates a new [tag](tag.md#tag) in the given frame range and with the given name.
## Sprite:deleteTag()
```lua
sprite:deleteTag(tag)
sprite:deleteTag(tagName)
```
Deletes the given [tag](tag.md#tag).
## Sprite:newSlice()
```lua
local slice = sprite:newSlice()
local slice = sprite:newSlice(Rectangle)
```
Returns a new [slice](slice.md#slice).
## Sprite:deleteSlice()
```lua
sprite:deleteSlice(slice)
sprite:deleteSlice(sliceName)
```
Deletes the given [slice](slice.md#slice).
## Sprite:flatten()
```lua
sprite:flatten()
```
Flatten all layers of the sprite into one layer.
It's like calling `app.commands.FlattenLayers()`.
| {
"content_hash": "7427eda0292cfe08ce3cc12b67071cd4",
"timestamp": "",
"source": "github",
"line_count": 403,
"max_line_length": 93,
"avg_line_length": 20.53846153846154,
"alnum_prop": 0.7220007249003262,
"repo_name": "aseprite/api-draft",
"id": "51847dd70478308c730af0e589bd762b078800b4",
"size": "8300",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "api/sprite.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<?php
namespace Paymer\OneClickIssueSvc;
class OneClickGetPriceExResponse
{
/**
* @var \Paymer\OneClickIssueSvc\Result
*/
public $OneClickGetPriceExResult;
/**
* @var decimal
*/
public $price;
/**
* @var string
*/
public $PurseN;
/**
* @var decimal
*/
public $amountLimit;
}
| {
"content_hash": "0a0d7cb7572e8830e525b444ad17a3e0",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 43,
"avg_line_length": 15.173913043478262,
"alnum_prop": 0.5587392550143266,
"repo_name": "zakharovvi/paymer-client",
"id": "ca4fa50bdad78a40769adaba75c2574651f4e700",
"size": "349",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Paymer/OneClickIssueSvc/OneClickGetPriceExResponse.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "36790"
}
],
"symlink_target": ""
} |
namespace AgileObjects.AgileMapper.UnitTests.Orms.EfCore1
{
using System.Threading.Tasks;
using Infrastructure;
using Xunit;
public class WhenProjectingToEnumerableMembers : WhenProjectingToEnumerableMembers<EfCore1TestDbContext>
{
public WhenProjectingToEnumerableMembers(InMemoryEfCore1TestContext context)
: base(context)
{
}
[Fact]
public Task ShouldProjectToAComplexTypeCollectionMember()
=> RunShouldProjectToAComplexTypeCollectionMember();
}
} | {
"content_hash": "bb7cc62b3c6c6900330ea5cab5f47c47",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 108,
"avg_line_length": 30.055555555555557,
"alnum_prop": 0.7190388170055453,
"repo_name": "agileobjects/AgileMapper",
"id": "19a1c8b5c283dc283f1faf6e08e5a4fff2e9c051",
"size": "543",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "AgileMapper.UnitTests.Orms.EfCore1/WhenProjectingToEnumerableMembers.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "3564095"
},
{
"name": "Visual Basic .NET",
"bytes": "659"
}
],
"symlink_target": ""
} |
{% load i18n %}
<div id="currentCity"><a>{{ current_city.name }}</a></div>
<div id="otherCities">
<div class="closeButton"><span> </span></div>
{% regroup other_cities|dictsort:"initial" by initial as initial_list %}
{% for initial in initial_list %}
<div class="initialGroup">{{ initial.grouper }}:</div>
<div class="cityList">
{% for city in initial.list %}
<span><a href="{% url switch_city_to city.id %}{{ city.slug }}/{% if next %}?next={{ next }}{% endif %}">{{ city.name }}</a></span>
{% endfor %}
</div>
{% endfor %}
<div class="moreCities"><a href="{{ select_city_url }}">{% trans 'more cities>>' %}</a></div>
</div>
| {
"content_hash": "a0f4f7ef52b231ae140e3defb8c88e50",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 135,
"avg_line_length": 44.46666666666667,
"alnum_prop": 0.5817091454272864,
"repo_name": "georgema1982/django-city-switch",
"id": "9299e55156217e2fffd942b58d8740caa695fad0",
"size": "667",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "city_switch/templates/city_switch/switch_city_button.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "844"
},
{
"name": "Python",
"bytes": "13738"
}
],
"symlink_target": ""
} |
* [Introduction](README.md)
* [Getting Started](Tutorial-Introduction-to-the-NoSQL-world.md)
* [Multi-Model Database](Tutorial-Document-and-graph-model.md)
* [Installation](Tutorial-Installation.md)
* [Run the server](Tutorial-Run-the-server.md)
* [Run the console](Tutorial-Run-the-console.md)
* [Classes](Tutorial-Classes.md)
* [Clusters](Tutorial-Clusters.md)
* [Record ID](Tutorial-Record-ID.md)
* [SQL](Tutorial-SQL.md)
* [Relationships](Tutorial-Relationships.md)
* [Working with Graphs](Tutorial-Working-with-graphs.md)
* [Using Schema with Graphs](Tutorial-Using-schema-with-graphs.md)
* [Setup a Distributed Database](Tutorial-Setup-a-distributed-database.md)
* [Working with Distributed Graphs](Tutorial-Working-with-distributed-graph-database.md)
* [Java API](Tutorial-Java.md)
* [More on Tutorials](Quick-Start.md)
* [Presentations](Presentations.md)
* [Basic Concepts](Concepts.md)
* [Supported Types](Types.md)
* [Inheritance](Inheritance.md)
* [Concurrency](Concurrency.md)
* [Schema](Schema.md)
* [Cluster Selection](Cluster-Selection.md)
* [Managing Dates](Managing-Dates.md)
* [Fetching Strategies](Fetching-Strategies.md)
* [Indexes](Indexes.md)
* [SB-Tree](SB-Tree-index.md)
* [Hash](Hash-Index.md)
* [Full Text](FullTextIndex.md)
* [Lucene Full Text](Full-Text-Index.md)
* [Lucene Spatial](Spatial-Index.md)
* [Security](Security.md)
* [Database security](Database-Security.md)
* [Server security](Server-Security.md)
* [Database encryption](Database-Encryption.md)
* [Secure SSL connections](Using-SSL-with-OrientDB.md)
* [Web Server](Web-Server.md)
* [Caching](Caching.md)
* [Functions](Functions.md)
* [Transaction](Transactions.md)
* [Hook - Triggers](Hook.md)
* [Dynamic Hooks](Dynamic-Hooks.md)
* [Java (Native) Hooks](Java-Hooks.md)
* [Java Hook Tutorial](Tutorial-Java-Hooks.md)
* [API](Programming-Language-Bindings.md)
* [Graph or Document API?](Choosing-between-Graph-or-Document-API.md)
* [SQL](SQL.md)
* [Filtering](SQL-Where.md)
* [Functions](SQL-Functions.md)
* [Methods](SQL-Methods.md)
* [Batch](SQL-batch.md)
* [Pagination](Pagination.md)
* [Sequences and auto increment](Sequences-and-auto-increment.md)
* [Commands](Commands.md)
* [Select](SQL-Query.md)
* [Insert](SQL-Insert.md)
* [Update](SQL-Update.md)
* [Delete](SQL-Delete.md)
* [Alter Class](SQL-Alter-Class.md)
* [Alter Cluster](SQL-Alter-Cluster.md)
* [Alter Database](SQL-Alter-Database.md)
* [Alter Property](SQL-Alter-Property.md)
* [Create Class](SQL-Create-Class.md)
* [Create Cluster](SQL-Create-Cluster.md)
* [Create Edge](SQL-Create-Edge.md)
* [Create Function](SQL-Create-Function.md)
* [Create Index](SQL-Create-Index.md)
* [Create Link](SQL-Create-Link.md)
* [Create Property](SQL-Create-Property.md)
* [Create User](SQL-Create-User.md)
* [Create Vertex](SQL-Create-Vertex.md)
* [Move Vertex](SQL-Move-Vertex.md)
* [Delete Edge](SQL-Delete-Edge.md)
* [Delete Vertex](SQL-Delete-Vertex.md)
* [Drop Class](SQL-Drop-Class.md)
* [Drop Cluster](SQL-Drop-Cluster.md)
* [Drop Index](SQL-Drop-Index.md)
* [Drop Property](SQL-Drop-Property.md)
* [Drop User](SQL-Drop-User.md)
* [Explain](SQL-Explain.md)
* [Find References](SQL-Find-References.md)
* [Grant](SQL-Grant.md)
* [Optimize Database](SQL-Optimize-Database.md)
* [Rebuild Index](SQL-Rebuild-Index.md)
* [Revoke](SQL-Revoke.md)
* [Traverse](SQL-Traverse.md)
* [Truncate Class](SQL-Truncate-Class.md)
* [Truncate Cluster](SQL-Truncate-Cluster.md)
* [Trucate Record](SQL-Truncate-Record.md)
* [Pivoting with Query](Pivoting-With-Query.md)
* [Command Cache](Command-Cache.md)
* [Java API](Java-API.md)
* [Graph API](Graph-Database-Tinkerpop.md)
* [Factory](Graph-Factory.md)
* [Schema](Graph-Schema.md)
* [Partitioned](Partitioned-Graphs.md)
* [Comparison](GraphDB-Comparison.md)
* [Lightweight Edges](Lightweight-Edges.md)
* [Document API](Document-Database.md)
* [Schema](Java-Schema-Api.md)
* [Field Part](Document-Field-Part.md)
* [Comparison](DocumentDB-Comparison.md)
* [Object API](Object-Database.md)
* [Binding](Object-2-Record-Java-Binding.md)
* [Traverse](Java-Traverse.md)
* [Live Query](Live-Query.md)
* [Multi-Threading](Java-Multi-Threading.md)
* [Transactions](Transaction-propagation.md)
* [Binary Data](Binary-Data.md)
* [Web Apps](Java-Web-Apps.md)
* [Server Management](Server-Management-Java.md)
* [JDBC Driver](JDBC-Home.md)
* [JPA](JPA-Configuration.md)
* [Gremlin API](Gremlin.md)
* [Javascript](Javascript-Command.md)
* [Javascript API](Javascript-Driver.md)
* [Scala API](Scala-Language.md)
* [HTTP API](OrientDB-REST.md)
* [Binary Protocol](Network-Binary-Protocol.md)
* [CSV Serialization](Record-CSV-Serialization.md)
* [Schemaless Serialization](Record-Schemaless-Binary-Serialization.md)
* [Commands](Network-Binary-Protocol-Commands.md)
* [Use Cases](Use-Cases.md)
* [Time Series](Time-series-use-case.md)
* [Chat](Chat-use-case.md)
* [Key Value](Key-Value-use-case.md)
* [Queue system](Queue-use-case.md)
* [Server](DB-Server.md)
* [Embed the Server](Embedded-Server.md)
* [Web Server](Web-Server.md)
* [Plugins](Extend-Server.md)
* [Automatic Backup](Automatic-Backup.md)
* [Mail](Mail-Plugin.md)
* [JMX](JMX-Plugin.md)
* [Studio](Home-page.md)
* [Query](Query.md)
* [Edit Document](Edit-Document.md)
* [Edit Vertex](Edit-Vertex.md)
* [Schema](Studio-Schema.md)
* [Class](Class.md)
* [Graph Editor](Graph-Editor.md)
* [Functions](Studio-Functions.md)
* [Security](Studio-Security.md)
* [Database Management](Database-Management.md)
* [Server Management](Server-Management.md)
* [Auditing](Studio-Auditing.md)
* [Console](Console-Commands.md)
* [Backup](Console-Command-Backup.md)
* [Begin](Console-Command-Begin.md)
* [Browse Class](Console-Command-Browse-Class.md)
* [Browse Cluster](Console-Command-Browse-Cluster.md)
* [List Classes](Console-Command-Classes.md)
* [Cluster Status](Console-Command-Cluster-Status.md)
* [List Clusters](Console-Command-Clusters.md)
* [List Server Users](Console-Command-List-Server-Users.md)
* [Commit](Console-Command-Commit.md)
* [Config](Console-Command-Config.md)
* [Config Get](Console-Command-Config-Get.md)
* [Config Set](Console-Command-Config-Set.md)
* [Connect](Console-Command-Connect.md)
* [Create Cluster](Console-Command-Create-Cluster.md)
* [Create Database](Console-Command-Create-Database.md)
* [Create Index](Console-Command-Create-Index.md)
* [Create Link](Console-Command-Create-Link.md)
* [Create Property](Console-Command-Create-Property.md)
* [Declare Intent](Console-Command-Declare-Intent.md)
* [Delete](Console-Command-Delete.md)
* [Dictionary Get](Console-Command-Dictionary-Get.md)
* [Dictionary Keys](Console-Command-Dictionary-Keys.md)
* [Dictionary Put](Console-Command-Dictionary-Put.md)
* [Dictionary Remove](Console-Command-Dictionary-Remove.md)
* [Disconnect](Console-Command-Disconnect.md)
* [Display Record](Console-Command-Display-Record.md)
* [Display Raw Record](Console-Command-Display-Raw-Record.md)
* [Drop Cluster](Console-Command-Drop-Cluster.md)
* [Drop Database](Console-Command-Drop-Database.md)
* [Drop Server User](Console-Command-Drop-Server-User.md)
* [Export](Console-Command-Export.md)
* [Export Record](Console-Command-Export-Record.md)
* [Freeze DB](Console-Command-Freeze-Db.md)
* [Get](Console-Command-Get.md)
* [Import](Console-Command-Import.md)
* [Indexes](Console-Command-Indexes.md)
* [Info](Console-Command-Info.md)
* [Info Class](Console-Command-Info-Class.md)
* [Info Property](Console-Command-Info-Property.md)
* [Insert](Console-Command-Insert.md)
* [List Databases](Console-Command-List-Databases.md)
* [Load Record](Console-Command-Load-Record.md)
* [Profiler](Console-Command-Profiler.md)
* [Properties](Console-Command-Properties.md)
* [Release DB](Console-Command-Release-Db.md)
* [Reload Record](Console-Command-Reload-Record.md)
* [Restore](Console-Command-Restore.md)
* [Rollback](Console-Command-Rollback.md)
* [Set](Console-Command-Set.md)
* [Set Server User](Console-Command-Set-Server-User.md)
* [Sleep](Console-Command-Sleep.md)
* [Operations](Operations.md)
* [Installation](Tutorial-Installation-Operations.md)
* [Install with Docker](Docker-Home.md)
* [Install as Service on Unix/Linux](Unix-Service.md)
* [Install as Service on Windows](Windows-Service.md)
* [Performance Tuning](Performance-Tuning.md)
* [Setting Configuration](Configuration.md)
* [Graph API](Performance-Tuning-Graph.md)
* [Document API](Performance-Tuning-Document.md)
* [Object API](Performance-Tuning-Object.md)
* [Profiler](Profiler.md)
* [ETL](ETL-Introduction.md)
* [Configuration](Configuration-File.md)
* [Blocks](Block.md)
* [Sources](Source.md)
* [Extractors](Extractor.md)
* [Transformers](Transformer.md)
* [Loaders](Loader.md)
* [Import the database of Beers](Import-the-Database-of-Beers.md)
* [Import from CSV to a Graph](Import-from-CSV-to-a-Graph.md)
* [Import a tree structure](Import-a-tree-structure.md)
* [Import from JSON](Import-from-JSON.md)
* [Import from RDBMS](Import-from-DBMS.md)
* [Import from DB-Pedia](Import-from-DBPedia.md)
* [Import from Parse (Facebook)](Import-from-PARSE.md)
* [Distributed Architecture](Distributed-Architecture.md)
* [Lifecycle](Distributed-Architecture-Lifecycle.md)
* [Configuration](Distributed-Configuration.md)
* [Server Manager](Distributed-Server-Manager.md)
* [Replication](Replication.md)
* [Sharding](Distributed-Sharding.md)
* [Cache](Distributed-Cache.md)
* [Backup and Restore](Backup-and-Restore.md)
* [Export and Import](Export-and-Import.md)
* [Export format](Export-Format.md)
* [Import From RDBMS](Import-From-RDBMS.md)
* [To Document Model](Import-RDBMS-to-Document-Model.md)
* [To Graph Model](Import-RDBMS-to-Graph-Model.md)
* [Import From Neo4j](Import-from-Neo4j-into-OrientDB.md)
* [Logging](Logging.md)
* [Enterprise Edition](Enterprise-Edition.md)
* [Auditing](Auditing.md)
* [Troubleshooting](Troubleshooting.md)
* [Java](Troubleshooting-Java.md)
* [Query Examples](Query-Examples.md)
* [Available Plugins](Plugins.md)
* [Rexster](Rexster.md)
* [Gephi Graph Render](Gephi.md)
* [Roadmap](Roadmap.md)
* [Upgrade](Upgrade.md)
* [Backward compatibility](Backward-compatibility.md)
* [From 2.0.x to 2.1.x](Release-2.1.0.md)
* [From 1.7.x to 2.0.x](Migration-from-1.7.x-to-2.0.x.md)
* [From 1.6.x to 1.7.x](Migration-from-1.6.x-to-1.7.x.md)
* [From 1.5.x to 1.6.x](Migration-from-1.5.x-to-1.6.x.md)
* [From 1.4.x to 1.5.x](Migration-from-1.4.x-to-1.5.x.md)
* [From 1.3.x to 1.4.x](Migration-from-1.3.x-to-1.4.x.md)
* [Internals](Internals.md)
* [Storages](Storages.md)
* [Memory storage](Memory-storage.md)
* [PLocal storage](Paginated-Local-Storage.md)
* [Engine](plocal-storage-engine.md)
* [Disk-Cache](plocal-storage-disk-cache.md)
* [WAL (Journal)](Write-Ahead-Log.md)
* [Local storage (deprecated)](Local-Storage.md)
* [Clusters](Clusters.md)
* [Limits](Limits.md)
* [RidBag](RidBag.md)
* [SQL Syntax](SQL-Syntax.md)
* [Custom Index Engine](Custom-Index-Engine.md)
* [Contribute to OrientDB](Contribute-to-OrientDB.md)
* [The Team](Team.md)
* [Hackaton](Hackaton.md)
* [Report an issue](Report-an-issue.md)
* [Get in touch](Get-in-Touch.md)
| {
"content_hash": "411f121167f7fc1dd888ad66f9ba1d4a",
"timestamp": "",
"source": "github",
"line_count": 275,
"max_line_length": 91,
"avg_line_length": 45.04727272727273,
"alnum_prop": 0.6504681950274459,
"repo_name": "aomega08/orientdb-docs",
"id": "c82548220148c17dae7a9c14a8b6d8f7be7d436e",
"size": "12399",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "SUMMARY.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import { checkTest } from './utils';
var MethodCallTracker = function(env, methodName) {
this._env = env;
this._methodName = methodName;
this._isExpectingNoCalls = false;
this._expecteds = [];
this._actuals = [];
};
MethodCallTracker.prototype = {
stubMethod() {
if (this._originalMethod) {
// Method is already stubbed
return;
}
let env = this._env;
let methodName = this._methodName;
this._originalMethod = env.getDebugFunction(methodName);
env.setDebugFunction(methodName, (message, test) => {
let resultOfTest = checkTest(test);
this._actuals.push([ message, resultOfTest ]);
});
},
restoreMethod() {
if (this._originalMethod) {
this._env.setDebugFunction(this._methodName, this._originalMethod);
}
},
expectCall(message) {
this.stubMethod();
this._expecteds.push(message || /.*/);
},
expectNoCalls() {
this.stubMethod();
this._isExpectingNoCalls = true;
},
isExpectingNoCalls() {
return this._isExpectingNoCalls;
},
isExpectingCalls() {
return !this._isExpectingNoCalls && this._expecteds.length;
},
assert() {
let { assert } = QUnit.config.current;
let env = this._env;
let methodName = this._methodName;
let isExpectingNoCalls = this._isExpectingNoCalls;
let expecteds = this._expecteds;
let actuals = this._actuals;
let o, i;
if (!isExpectingNoCalls && expecteds.length === 0 && actuals.length === 0) {
return;
}
if (env.runningProdBuild) {
assert.ok(true, `calls to Ember.${methodName} disabled in production builds.`);
return;
}
if (isExpectingNoCalls) {
let actualMessages = [];
for (i = 0; i < actuals.length; i++) {
if (!actuals[i][1]) {
actualMessages.push(actuals[i][0]);
}
}
assert.ok(actualMessages.length === 0, `Expected no Ember.${methodName} calls, got ${actuals.length}: ${actualMessages.join(', ')}`);
return;
}
let expected, actual, match;
for (o = 0; o < expecteds.length; o++) {
expected = expecteds[o];
for (i = 0; i < actuals.length; i++) {
actual = actuals[i];
if (!actual[1]) {
if (expected instanceof RegExp) {
if (expected.test(actual[0])) {
match = actual;
break;
}
} else {
if (expected === actual[0]) {
match = actual;
break;
}
}
}
}
if (!actual) {
assert.ok(false, `Received no Ember.${methodName} calls at all, expecting: ${expected}`);
} else if (match && !match[1]) {
assert.ok(true, `Received failing Ember.${methodName} call with message: ${match[0]}`);
} else if (match && match[1]) {
assert.ok(false, `Expected failing Ember.${methodName} call, got succeeding with message: ${match[0]}`);
} else if (actual[1]) {
assert.ok(false, `Did not receive failing Ember.${methodName} call matching '${expected}', last was success with '${actual[0]}'`);
} else if (!actual[1]) {
assert.ok(false, `Did not receive failing Ember.${methodName} call matching '${expected}', last was failure with '${actual[0]}'`);
}
}
}
};
export default MethodCallTracker;
| {
"content_hash": "352694f02192d7f15e8d42a33356995f",
"timestamp": "",
"source": "github",
"line_count": 119,
"max_line_length": 139,
"avg_line_length": 27.92436974789916,
"alnum_prop": 0.5795967499247667,
"repo_name": "jasonmit/ember.js",
"id": "25ca252f0b68cfa9dcce7ed2742ed0f1f9abac17",
"size": "3323",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "packages/internal-test-helpers/lib/ember-dev/method-call-tracker.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "8228"
},
{
"name": "JavaScript",
"bytes": "3405320"
},
{
"name": "Ruby",
"bytes": "1848"
},
{
"name": "Shell",
"bytes": "3466"
},
{
"name": "TypeScript",
"bytes": "249784"
}
],
"symlink_target": ""
} |
import { TextTracking24 } from "../../";
export = TextTracking24;
| {
"content_hash": "bca8c798cf05dd8b362c3afd16ff66c6",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 40,
"avg_line_length": 22.333333333333332,
"alnum_prop": 0.6567164179104478,
"repo_name": "markogresak/DefinitelyTyped",
"id": "918bbc60347443bfbd87fec4974055e62f3f0891",
"size": "67",
"binary": false,
"copies": "20",
"ref": "refs/heads/master",
"path": "types/carbon__icons-react/lib/text--tracking/24.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "15"
},
{
"name": "Protocol Buffer",
"bytes": "678"
},
{
"name": "TypeScript",
"bytes": "17426898"
}
],
"symlink_target": ""
} |
<h1>Create new kata</h1>
<!-- los campos comunes: nombre, descripción, código... que vayan ocupando todo el ancho; los de
entrada/salida que ocupen solo la mitad para ponerlos en paralelo -->
<!--
- write the description
- write the examples
- write the inputs / outputs
- write the tests
- select its state: enabled/disabled
-->
<div class="step">
<!-- Programming language selector -->
<div class="select-top-spacer">
<md-select class="full-width" [(ngModel)]="programmingLang" name="lang"
placeholder="Select the language of the kata"
(change)="onLanguageProgrammingChange($event)">
<md-option *ngFor="let lang of programmingLanguages" [value]="lang">{{ lang }}</md-option>
</md-select>
</div>
<!-- LearningPath selector -->
<div class="select-top-spacer2">
<md-select class="full-width" [(ngModel)]="learningPath" name="lp"
placeholder="Select the learning path which the kata belongs to">
<md-option *ngFor="let lp of learningPaths" [value]="lp">{{ lp }}</md-option>
</md-select>
</div>
<!-- Name / Function name (kata identifier) -->
<md-input-container class="full-width">
<input mdInput required [(ngModel)]="name"
placeholder="Write the name (unique identifier) for the kata">
</md-input-container>
<!-- Function signature -->
<div class="select-top-spacer">
<p>Write here the function signature (kata's name, params, ...)</p>
<p *ngIf="!showEditor" class="show-editor-warning">
To see the editor, please, select first a programming language!
</p>
<kata-editor class=""
*ngIf="showEditor"
[code]="code"
[kataEditorConfig]="config">
</kata-editor>
</div>
<!-- Kata description -->
<md-input-container class="full-width">
<textarea mdInput required [(ngModel)]="description"
placeholder="Write a description for the purpose of this kata">
</textarea>
</md-input-container>
<!-- Examples -->
<md-input-container class="full-width">
<input mdInput required [(ngModel)]="examples"
placeholder="Also, you can write a brief description">
</md-input-container>
<!-- Input/Outputs -->
<div class="select-top-spacer">
<p>Add the inputs and outputs needed for your kata, specifying</p>
</div>
<!-- Tests -->
<div class="select-top-spacer2">
<p>Add all tests that you desire or consider to assert the correctness of the user's implementation</p>
<button type="button" class="full-width" md-raised-button color="accent" (click)="addNewTestCase()">
Add new test case
</button>
<div class="flexibox-row padding-top-8" *ngFor="let testCase of tests; let i = index">
<div class="padding-right-6" style="flex-grow:1">
<md-input-container class="full-width">
<input mdInput required [(ngModel)]="testCase.input" placeholder="Write the input">
</md-input-container>
</div>
<div class="padding-right-6" style="flex-grow:1">
<md-input-container class="full-width">
<input mdInput required [(ngModel)]="testCase.output" placeholder="Write the output">
</md-input-container>
</div>
<div class="padding-top-8" style="flex-grow:0;">
<button md-mini-fab (click)="closeTestCase(i)"><md-icon>close</md-icon></button>
</div>
</div>
</div>
<!-- Enabled -->
<div class="select-top-spacer2">
<p>The kata has to be enabled?</p>
<md-slide-toggle [(ngModel)]="enabled" color="primary" checked="true">
{{ (enabled) ? 'Enabled kata' : 'Disabled kata' }}
</md-slide-toggle>
</div>
<!-- Buttons -->
<div class="padding-top-18">
<div class="flexibox-row">
<button type="button" md-raised-button color="primary" class="flex-grow-1" (click)="addKata()">
Add kata
</button>
<div style="padding:0 3px;"></div>
<button type="button" md-raised-button color="accent" class="flex-grow-1" (click)="cancel()">
Cancel
</button>
</div>
</div>
</div> | {
"content_hash": "8f76db101b581bf7a6baeb2c5d6f3640",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 111,
"avg_line_length": 40.13513513513514,
"alnum_prop": 0.571043771043771,
"repo_name": "semagarcia/javascript-kata-player",
"id": "8c7c44f0974e2dd4b691f013e47c6ac9046e005d",
"size": "4457",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/administration/kata/kata-form/kata-form.component.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8610"
},
{
"name": "HTML",
"bytes": "58949"
},
{
"name": "JavaScript",
"bytes": "1887"
},
{
"name": "TypeScript",
"bytes": "157658"
}
],
"symlink_target": ""
} |
package org.apache.jmeter.engine.util;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.jmeter.functions.Function;
import org.apache.jmeter.functions.InvalidVariableException;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;
import org.apache.jmeter.threads.JMeterContext;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.jorphan.reflect.ClassFinder;
import org.apache.log.Logger;
/**
* CompoundFunction.
*
*/
public class CompoundVariable implements Function {
private static final Logger log = LoggingManager.getLoggerForClass();
private String rawParameters;
private static final FunctionParser functionParser = new FunctionParser();
// Created during class init; not modified thereafter
private static final Map<String, Class<? extends Function>> functions =
new HashMap<String, Class<? extends Function>>();
private boolean hasFunction, isDynamic;
private String permanentResults;
private LinkedList<Object> compiledComponents = new LinkedList<Object>();
static {
try {
final String contain = // Classnames must contain this string [.functions.]
JMeterUtils.getProperty("classfinder.functions.contain"); // $NON-NLS-1$
final String notContain = // Classnames must not contain this string [.gui.]
JMeterUtils.getProperty("classfinder.functions.notContain"); // $NON-NLS-1$
if (contain!=null){
log.info("Note: Function class names must contain the string: '"+contain+"'");
}
if (notContain!=null){
log.info("Note: Function class names must not contain the string: '"+notContain+"'");
}
List<String> classes = ClassFinder.findClassesThatExtend(JMeterUtils.getSearchPaths(),
new Class[] { Function.class }, true, contain, notContain);
Iterator<String> iter = classes.iterator();
while (iter.hasNext()) {
Function tempFunc = (Function) Class.forName(iter.next()).newInstance();
String referenceKey = tempFunc.getReferenceKey();
if (referenceKey.length() > 0) { // ignore self
functions.put(referenceKey, tempFunc.getClass());
// Add alias for original StringFromFile name (had only one underscore)
if (referenceKey.equals("__StringFromFile")){//$NON-NLS-1$
functions.put("_StringFromFile", tempFunc.getClass());//$NON-NLS-1$
}
}
}
final int functionCount = functions.size();
if (functionCount == 0){
log.warn("Did not find any functions");
} else {
log.debug("Function count: "+functionCount);
}
} catch (Exception err) {
log.error("", err);
}
}
public CompoundVariable() {
hasFunction = false;
}
public CompoundVariable(String parameters) {
this();
try {
setParameters(parameters);
} catch (InvalidVariableException e) {
// TODO should level be more than debug ?
if(log.isDebugEnabled()) {
log.debug("Invalid variable:"+ parameters, e);
}
}
}
public String execute() {
if (isDynamic || permanentResults == null) {
JMeterContext context = JMeterContextService.getContext();
SampleResult previousResult = context.getPreviousResult();
Sampler currentSampler = context.getCurrentSampler();
return execute(previousResult, currentSampler);
}
return permanentResults; // $NON-NLS-1$
}
/**
* Allows the retrieval of the original String prior to it being compiled.
*
* @return String
*/
public String getRawParameters() {
return rawParameters;
}
/** {@inheritDoc} */
@Override
public String execute(SampleResult previousResult, Sampler currentSampler) {
if (compiledComponents == null || compiledComponents.size() == 0) {
return ""; // $NON-NLS-1$
}
StringBuilder results = new StringBuilder();
for (Object item : compiledComponents) {
if (item instanceof Function) {
try {
results.append(((Function) item).execute(previousResult, currentSampler));
} catch (InvalidVariableException e) {
// TODO should level be more than debug ?
if(log.isDebugEnabled()) {
log.debug("Invalid variable:"+item, e);
}
}
} else if (item instanceof SimpleVariable) {
results.append(((SimpleVariable) item).toString());
} else {
results.append(item);
}
}
if (!isDynamic) {
permanentResults = results.toString();
}
return results.toString();
}
@SuppressWarnings("unchecked") // clone will produce correct type
public CompoundVariable getFunction() {
CompoundVariable func = new CompoundVariable();
func.compiledComponents = (LinkedList<Object>) compiledComponents.clone();
func.rawParameters = rawParameters;
func.hasFunction = hasFunction;
func.isDynamic = isDynamic;
return func;
}
/** {@inheritDoc} */
@Override
public List<String> getArgumentDesc() {
return new LinkedList<String>();
}
public void clear() {
// TODO should this also clear isDynamic, rawParameters, permanentResults?
hasFunction = false;
compiledComponents.clear();
}
public void setParameters(String parameters) throws InvalidVariableException {
this.rawParameters = parameters;
if (parameters == null || parameters.length() == 0) {
return;
}
compiledComponents = functionParser.compileString(parameters);
if (compiledComponents.size() > 1 || !(compiledComponents.get(0) instanceof String)) {
hasFunction = true;
}
permanentResults = null; // To be calculated and cached on first execution
isDynamic = false;
for (Object item : compiledComponents) {
if (item instanceof Function || item instanceof SimpleVariable) {
isDynamic = true;
break;
}
}
}
static Object getNamedFunction(String functionName) throws InvalidVariableException {
if (functions.containsKey(functionName)) {
try {
return ((Class<?>) functions.get(functionName)).newInstance();
} catch (Exception e) {
log.error("", e); // $NON-NLS-1$
throw new InvalidVariableException(e);
}
}
return new SimpleVariable(functionName);
}
// For use by FunctionHelper
public static Class<? extends Function> getFunctionClass(String className) {
return functions.get(className);
}
// For use by FunctionHelper
public static String[] getFunctionNames() {
return functions.keySet().toArray(new String[functions.size()]);
}
public boolean hasFunction() {
return hasFunction;
}
// Dummy methods needed by Function interface
/** {@inheritDoc} */
@Override
public String getReferenceKey() {
return ""; // $NON-NLS-1$
}
/** {@inheritDoc} */
@Override
public void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException {
}
}
| {
"content_hash": "1d9841ebec1b839e6495c60c89efc765",
"timestamp": "",
"source": "github",
"line_count": 225,
"max_line_length": 104,
"avg_line_length": 36.404444444444444,
"alnum_prop": 0.5888169942619949,
"repo_name": "saketh7/Jmeter",
"id": "b57fdc7bace02bce8fe4ae2990c86f18aa712bb4",
"size": "9009",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/core/org/apache/jmeter/engine/util/CompoundVariable.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2796"
},
{
"name": "CSS",
"bytes": "1321"
},
{
"name": "HTML",
"bytes": "13278"
},
{
"name": "Java",
"bytes": "7233227"
},
{
"name": "Shell",
"bytes": "1873"
},
{
"name": "XSLT",
"bytes": "62457"
}
],
"symlink_target": ""
} |
<div>
Adding branches to this blacklist allows you to prevent pull requests for specific branches.<br/>
Supports regular expressions (e.g. 'master', 'feature-.*').
</div> | {
"content_hash": "55361de87e32688ba7e1993e9a0615e6",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 99,
"avg_line_length": 43.5,
"alnum_prop": 0.7298850574712644,
"repo_name": "DavidTanner/ghprb-plugin",
"id": "6c27da2f85e9afa875376979e172ebd1f3036f5e",
"size": "174",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/main/resources/org/jenkinsci/plugins/ghprb/GhprbTrigger/help-blackListTargetBranches.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Groovy",
"bytes": "8638"
},
{
"name": "HTML",
"bytes": "7181"
},
{
"name": "Java",
"bytes": "355069"
}
],
"symlink_target": ""
} |
package proxy
import (
"testing"
"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
)
func TestLoadBalanceValidateWorks(t *testing.T) {
loadBalancer := NewLoadBalancerRR()
if loadBalancer.isValid("") {
t.Errorf("Didn't fail for empty string")
}
if loadBalancer.isValid("foobar") {
t.Errorf("Didn't fail with no port")
}
if loadBalancer.isValid("foobar:-1") {
t.Errorf("Didn't fail with a negative port")
}
if !loadBalancer.isValid("foobar:8080") {
t.Errorf("Failed a valid config.")
}
}
func TestLoadBalanceFilterWorks(t *testing.T) {
loadBalancer := NewLoadBalancerRR()
endpoints := []string{"foobar:1", "foobar:2", "foobar:-1", "foobar:3", "foobar:-2"}
filtered := loadBalancer.filterValidEndpoints(endpoints)
if len(filtered) != 3 {
t.Errorf("Failed to filter to the correct size")
}
if filtered[0] != "foobar:1" {
t.Errorf("Index zero is not foobar:1")
}
if filtered[1] != "foobar:2" {
t.Errorf("Index one is not foobar:2")
}
if filtered[2] != "foobar:3" {
t.Errorf("Index two is not foobar:3")
}
}
func TestLoadBalanceFailsWithNoEndpoints(t *testing.T) {
loadBalancer := NewLoadBalancerRR()
var endpoints []api.Endpoints
loadBalancer.OnUpdate(endpoints)
endpoint, err := loadBalancer.LoadBalance("foo", nil)
if err == nil {
t.Errorf("Didn't fail with non-existent service")
}
if len(endpoint) != 0 {
t.Errorf("Got an endpoint")
}
}
func expectEndpoint(t *testing.T, loadBalancer *LoadBalancerRR, service string, expected string) {
endpoint, err := loadBalancer.LoadBalance(service, nil)
if err != nil {
t.Errorf("Didn't find a service for %s, expected %s, failed with: %v", service, expected, err)
}
if endpoint != expected {
t.Errorf("Didn't get expected endpoint for service %s, expected %s, got: %s", service, expected, endpoint)
}
}
func TestLoadBalanceWorksWithSingleEndpoint(t *testing.T) {
loadBalancer := NewLoadBalancerRR()
endpoint, err := loadBalancer.LoadBalance("foo", nil)
if err == nil || len(endpoint) != 0 {
t.Errorf("Didn't fail with non-existent service")
}
endpoints := make([]api.Endpoints, 1)
endpoints[0] = api.Endpoints{Name: "foo", Endpoints: []string{"endpoint1:40"}}
loadBalancer.OnUpdate(endpoints)
expectEndpoint(t, loadBalancer, "foo", "endpoint1:40")
expectEndpoint(t, loadBalancer, "foo", "endpoint1:40")
expectEndpoint(t, loadBalancer, "foo", "endpoint1:40")
expectEndpoint(t, loadBalancer, "foo", "endpoint1:40")
}
func TestLoadBalanceWorksWithMultipleEndpoints(t *testing.T) {
loadBalancer := NewLoadBalancerRR()
endpoint, err := loadBalancer.LoadBalance("foo", nil)
if err == nil || len(endpoint) != 0 {
t.Errorf("Didn't fail with non-existent service")
}
endpoints := make([]api.Endpoints, 1)
endpoints[0] = api.Endpoints{Name: "foo", Endpoints: []string{"endpoint:1", "endpoint:2", "endpoint:3"}}
loadBalancer.OnUpdate(endpoints)
expectEndpoint(t, loadBalancer, "foo", "endpoint:1")
expectEndpoint(t, loadBalancer, "foo", "endpoint:2")
expectEndpoint(t, loadBalancer, "foo", "endpoint:3")
expectEndpoint(t, loadBalancer, "foo", "endpoint:1")
}
func TestLoadBalanceWorksWithMultipleEndpointsAndUpdates(t *testing.T) {
loadBalancer := NewLoadBalancerRR()
endpoint, err := loadBalancer.LoadBalance("foo", nil)
if err == nil || len(endpoint) != 0 {
t.Errorf("Didn't fail with non-existent service")
}
endpoints := make([]api.Endpoints, 1)
endpoints[0] = api.Endpoints{Name: "foo", Endpoints: []string{"endpoint:1", "endpoint:2", "endpoint:3"}}
loadBalancer.OnUpdate(endpoints)
expectEndpoint(t, loadBalancer, "foo", "endpoint:1")
expectEndpoint(t, loadBalancer, "foo", "endpoint:2")
expectEndpoint(t, loadBalancer, "foo", "endpoint:3")
expectEndpoint(t, loadBalancer, "foo", "endpoint:1")
expectEndpoint(t, loadBalancer, "foo", "endpoint:2")
// Then update the configuration with one fewer endpoints, make sure
// we start in the beginning again
endpoints[0] = api.Endpoints{Name: "foo", Endpoints: []string{"endpoint:8", "endpoint:9"}}
loadBalancer.OnUpdate(endpoints)
expectEndpoint(t, loadBalancer, "foo", "endpoint:8")
expectEndpoint(t, loadBalancer, "foo", "endpoint:9")
expectEndpoint(t, loadBalancer, "foo", "endpoint:8")
expectEndpoint(t, loadBalancer, "foo", "endpoint:9")
// Clear endpoints
endpoints[0] = api.Endpoints{Name: "foo", Endpoints: []string{}}
loadBalancer.OnUpdate(endpoints)
endpoint, err = loadBalancer.LoadBalance("foo", nil)
if err == nil || len(endpoint) != 0 {
t.Errorf("Didn't fail with non-existent service")
}
}
func TestLoadBalanceWorksWithServiceRemoval(t *testing.T) {
loadBalancer := NewLoadBalancerRR()
endpoint, err := loadBalancer.LoadBalance("foo", nil)
if err == nil || len(endpoint) != 0 {
t.Errorf("Didn't fail with non-existent service")
}
endpoints := make([]api.Endpoints, 2)
endpoints[0] = api.Endpoints{Name: "foo", Endpoints: []string{"endpoint:1", "endpoint:2", "endpoint:3"}}
endpoints[1] = api.Endpoints{Name: "bar", Endpoints: []string{"endpoint:4", "endpoint:5"}}
loadBalancer.OnUpdate(endpoints)
expectEndpoint(t, loadBalancer, "foo", "endpoint:1")
expectEndpoint(t, loadBalancer, "foo", "endpoint:2")
expectEndpoint(t, loadBalancer, "foo", "endpoint:3")
expectEndpoint(t, loadBalancer, "foo", "endpoint:1")
expectEndpoint(t, loadBalancer, "foo", "endpoint:2")
expectEndpoint(t, loadBalancer, "bar", "endpoint:4")
expectEndpoint(t, loadBalancer, "bar", "endpoint:5")
expectEndpoint(t, loadBalancer, "bar", "endpoint:4")
expectEndpoint(t, loadBalancer, "bar", "endpoint:5")
expectEndpoint(t, loadBalancer, "bar", "endpoint:4")
// Then update the configuration by removing foo
loadBalancer.OnUpdate(endpoints[1:])
endpoint, err = loadBalancer.LoadBalance("foo", nil)
if err == nil || len(endpoint) != 0 {
t.Errorf("Didn't fail with non-existent service")
}
// but bar is still there, and we continue RR from where we left off.
expectEndpoint(t, loadBalancer, "bar", "endpoint:5")
expectEndpoint(t, loadBalancer, "bar", "endpoint:4")
expectEndpoint(t, loadBalancer, "bar", "endpoint:5")
expectEndpoint(t, loadBalancer, "bar", "endpoint:4")
}
| {
"content_hash": "a860d94db778fe30f359203e306915b0",
"timestamp": "",
"source": "github",
"line_count": 165,
"max_line_length": 108,
"avg_line_length": 36.95757575757576,
"alnum_prop": 0.7097408986552968,
"repo_name": "ryfow/kubernetes",
"id": "1112141de80f7c8dac2f5743721bfba28edef9f6",
"size": "6676",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "pkg/proxy/roundrobbin_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package auth
import (
"context"
"fmt"
"net/http"
"net/url"
"strings"
goauth "github.com/abbot/go-http-auth"
"github.com/opentracing/opentracing-go/ext"
"github.com/traefik/traefik/v2/pkg/config/dynamic"
"github.com/traefik/traefik/v2/pkg/log"
"github.com/traefik/traefik/v2/pkg/middlewares"
"github.com/traefik/traefik/v2/pkg/middlewares/accesslog"
"github.com/traefik/traefik/v2/pkg/tracing"
)
const (
digestTypeName = "digestAuth"
)
type digestAuth struct {
next http.Handler
auth *goauth.DigestAuth
users map[string]string
headerField string
removeHeader bool
name string
}
// NewDigest creates a digest auth middleware.
func NewDigest(ctx context.Context, next http.Handler, authConfig dynamic.DigestAuth, name string) (http.Handler, error) {
log.FromContext(middlewares.GetLoggerCtx(ctx, name, digestTypeName)).Debug("Creating middleware")
users, err := getUsers(authConfig.UsersFile, authConfig.Users, digestUserParser)
if err != nil {
return nil, err
}
da := &digestAuth{
next: next,
users: users,
headerField: authConfig.HeaderField,
removeHeader: authConfig.RemoveHeader,
name: name,
}
realm := defaultRealm
if len(authConfig.Realm) > 0 {
realm = authConfig.Realm
}
da.auth = goauth.NewDigestAuthenticator(realm, da.secretDigest)
return da, nil
}
func (d *digestAuth) GetTracingInformation() (string, ext.SpanKindEnum) {
return d.name, tracing.SpanKindNoneEnum
}
func (d *digestAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
logger := log.FromContext(middlewares.GetLoggerCtx(req.Context(), d.name, digestTypeName))
username, authinfo := d.auth.CheckAuth(req)
if username == "" {
headerField := d.headerField
if d.headerField == "" {
headerField = "Authorization"
}
auth := goauth.DigestAuthParams(req.Header.Get(headerField))
if auth["username"] != "" {
logData := accesslog.GetLogData(req)
if logData != nil {
logData.Core[accesslog.ClientUsername] = auth["username"]
}
}
if authinfo != nil && *authinfo == "stale" {
logger.Debug("Digest authentication failed, possibly because out of order requests")
tracing.SetErrorWithEvent(req, "Digest authentication failed, possibly because out of order requests")
d.auth.RequireAuthStale(rw, req)
return
}
logger.Debug("Digest authentication failed")
tracing.SetErrorWithEvent(req, "Digest authentication failed")
d.auth.RequireAuth(rw, req)
return
}
logger.Debug("Digest authentication succeeded")
req.URL.User = url.User(username)
logData := accesslog.GetLogData(req)
if logData != nil {
logData.Core[accesslog.ClientUsername] = username
}
if d.headerField != "" {
req.Header[d.headerField] = []string{username}
}
if d.removeHeader {
logger.Debug("Removing the Authorization header")
req.Header.Del(authorizationHeader)
}
d.next.ServeHTTP(rw, req)
}
func (d *digestAuth) secretDigest(user, realm string) string {
if secret, ok := d.users[user+":"+realm]; ok {
return secret
}
return ""
}
func digestUserParser(user string) (string, string, error) {
split := strings.Split(user, ":")
if len(split) != 3 {
return "", "", fmt.Errorf("error parsing DigestUser: %v", user)
}
return split[0] + ":" + split[1], split[2], nil
}
| {
"content_hash": "378b3ff6998d1da210cb4183890747e6",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 122,
"avg_line_length": 26.36,
"alnum_prop": 0.7077389984825493,
"repo_name": "mmatur/traefik",
"id": "454a972951f63bd42092e690ff27676210f6b2dc",
"size": "3295",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "pkg/middlewares/auth/digest_auth.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "4091"
},
{
"name": "Go",
"bytes": "3712135"
},
{
"name": "HTML",
"bytes": "1480"
},
{
"name": "JavaScript",
"bytes": "83425"
},
{
"name": "Makefile",
"bytes": "7174"
},
{
"name": "SCSS",
"bytes": "6743"
},
{
"name": "Shell",
"bytes": "10820"
},
{
"name": "Stylus",
"bytes": "665"
},
{
"name": "Vue",
"bytes": "175802"
}
],
"symlink_target": ""
} |
MAKEFLAGS=-r
# The source directory tree.
srcdir := ..
abs_srcdir := $(abspath $(srcdir))
# The name of the builddir.
builddir_name ?= .
# The V=1 flag on command line makes us verbosely print command lines.
ifdef V
quiet=
else
quiet=quiet_
endif
# Specify BUILDTYPE=Release on the command line for a release build.
BUILDTYPE ?= Release
# Directory all our build output goes into.
# Note that this must be two directories beneath src/ for unit tests to pass,
# as they reach into the src/ directory for data with relative paths.
builddir ?= $(builddir_name)/$(BUILDTYPE)
abs_builddir := $(abspath $(builddir))
depsdir := $(builddir)/.deps
# Object output directory.
obj := $(builddir)/obj
abs_obj := $(abspath $(obj))
# We build up a list of every single one of the targets so we can slurp in the
# generated dependency rule Makefiles in one pass.
all_deps :=
CC.target ?= $(CC)
CFLAGS.target ?= $(CFLAGS)
CXX.target ?= $(CXX)
CXXFLAGS.target ?= $(CXXFLAGS)
LINK.target ?= $(LINK)
LDFLAGS.target ?= $(LDFLAGS)
AR.target ?= $(AR)
# C++ apps need to be linked with g++.
LINK ?= $(CXX.target)
# TODO(evan): move all cross-compilation logic to gyp-time so we don't need
# to replicate this environment fallback in make as well.
CC.host ?= gcc
CFLAGS.host ?=
CXX.host ?= g++
CXXFLAGS.host ?=
LINK.host ?= $(CXX.host)
LDFLAGS.host ?=
AR.host ?= ar
# Define a dir function that can handle spaces.
# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions
# "leading spaces cannot appear in the text of the first argument as written.
# These characters can be put into the argument value by variable substitution."
empty :=
space := $(empty) $(empty)
# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces
replace_spaces = $(subst $(space),?,$1)
unreplace_spaces = $(subst ?,$(space),$1)
dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1)))
# Flags to make gcc output dependency info. Note that you need to be
# careful here to use the flags that ccache and distcc can understand.
# We write to a dep file on the side first and then rename at the end
# so we can't end up with a broken dep file.
depfile = $(depsdir)/$(call replace_spaces,$@).d
DEPFLAGS = -MMD -MF $(depfile).raw
# We have to fixup the deps output in a few ways.
# (1) the file output should mention the proper .o file.
# ccache or distcc lose the path to the target, so we convert a rule of
# the form:
# foobar.o: DEP1 DEP2
# into
# path/to/foobar.o: DEP1 DEP2
# (2) we want missing files not to cause us to fail to build.
# We want to rewrite
# foobar.o: DEP1 DEP2 \
# DEP3
# to
# DEP1:
# DEP2:
# DEP3:
# so if the files are missing, they're just considered phony rules.
# We have to do some pretty insane escaping to get those backslashes
# and dollar signs past make, the shell, and sed at the same time.
# Doesn't work with spaces, but that's fine: .d files have spaces in
# their names replaced with other characters.
define fixup_dep
# The depfile may not exist if the input file didn't have any #includes.
touch $(depfile).raw
# Fixup path as in (1).
sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile)
# Add extra rules as in (2).
# We remove slashes and replace spaces with new lines;
# remove blank lines;
# delete the first line and append a colon to the remaining lines.
sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\
grep -v '^$$' |\
sed -e 1d -e 's|$$|:|' \
>> $(depfile)
rm $(depfile).raw
endef
# Command definitions:
# - cmd_foo is the actual command to run;
# - quiet_cmd_foo is the brief-output summary of the command.
quiet_cmd_cc = CC($(TOOLSET)) $@
cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_cxx = CXX($(TOOLSET)) $@
cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_touch = TOUCH $@
cmd_touch = touch $@
quiet_cmd_copy = COPY $@
# send stderr to /dev/null to ignore messages when linking directories.
cmd_copy = rm -rf "$@" && cp -af "$<" "$@"
quiet_cmd_alink = AR($(TOOLSET)) $@
cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
quiet_cmd_alink_thin = AR($(TOOLSET)) $@
cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^)
# Due to circular dependencies between libraries :(, we wrap the
# special "figure out circular dependencies" flags around the entire
# input list during linking.
quiet_cmd_link = LINK($(TOOLSET)) $@
cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS)
# We support two kinds of shared objects (.so):
# 1) shared_library, which is just bundling together many dependent libraries
# into a link line.
# 2) loadable_module, which is generating a module intended for dlopen().
#
# They differ only slightly:
# In the former case, we want to package all dependent code into the .so.
# In the latter case, we want to package just the API exposed by the
# outermost module.
# This means shared_library uses --whole-archive, while loadable_module doesn't.
# (Note that --whole-archive is incompatible with the --start-group used in
# normal linking.)
# Other shared-object link notes:
# - Set SONAME to the library filename so our binaries don't reference
# the local, absolute paths used on the link command-line.
quiet_cmd_solink = SOLINK($(TOOLSET)) $@
cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS)
quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS)
# Define an escape_quotes function to escape single quotes.
# This allows us to handle quotes properly as long as we always use
# use single quotes and escape_quotes.
escape_quotes = $(subst ','\'',$(1))
# This comment is here just to include a ' to unconfuse syntax highlighting.
# Define an escape_vars function to escape '$' variable syntax.
# This allows us to read/write command lines with shell variables (e.g.
# $LD_LIBRARY_PATH), without triggering make substitution.
escape_vars = $(subst $$,$$$$,$(1))
# Helper that expands to a shell command to echo a string exactly as it is in
# make. This uses printf instead of echo because printf's behaviour with respect
# to escape sequences is more portable than echo's across different shells
# (e.g., dash, bash).
exact_echo = printf '%s\n' '$(call escape_quotes,$(1))'
# Helper to compare the command we're about to run against the command
# we logged the last time we ran the command. Produces an empty
# string (false) when the commands match.
# Tricky point: Make has no string-equality test function.
# The kernel uses the following, but it seems like it would have false
# positives, where one string reordered its arguments.
# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \
# $(filter-out $(cmd_$@), $(cmd_$(1))))
# We instead substitute each for the empty string into the other, and
# say they're equal if both substitutions produce the empty string.
# .d files contain ? instead of spaces, take that into account.
command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\
$(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1))))
# Helper that is non-empty when a prerequisite changes.
# Normally make does this implicitly, but we force rules to always run
# so we can check their command lines.
# $? -- new prerequisites
# $| -- order-only dependencies
prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?))
# Helper that executes all postbuilds until one fails.
define do_postbuilds
@E=0;\
for p in $(POSTBUILDS); do\
eval $$p;\
E=$$?;\
if [ $$E -ne 0 ]; then\
break;\
fi;\
done;\
if [ $$E -ne 0 ]; then\
rm -rf "$@";\
exit $$E;\
fi
endef
# do_cmd: run a command via the above cmd_foo names, if necessary.
# Should always run for a given target to handle command-line changes.
# Second argument, if non-zero, makes it do asm/C/C++ dependency munging.
# Third argument, if non-zero, makes it do POSTBUILDS processing.
# Note: We intentionally do NOT call dirx for depfile, since it contains ? for
# spaces already and dirx strips the ? characters.
define do_cmd
$(if $(or $(command_changed),$(prereq_changed)),
@$(call exact_echo, $($(quiet)cmd_$(1)))
@mkdir -p "$(call dirx,$@)" "$(dir $(depfile))"
$(if $(findstring flock,$(word 1,$(cmd_$1))),
@$(cmd_$(1))
@echo " $(quiet_cmd_$(1)): Finished",
@$(cmd_$(1))
)
@$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile)
@$(if $(2),$(fixup_dep))
$(if $(and $(3), $(POSTBUILDS)),
$(call do_postbuilds)
)
)
endef
# Declare the "all" target first so it is the default,
# even though we don't have the deps yet.
.PHONY: all
all:
# make looks for ways to re-generate included makefiles, but in our case, we
# don't have a direct way. Explicitly telling make that it has nothing to do
# for them makes it go faster.
%.d: ;
# Use FORCE_DO_CMD to force a target to run. Should be coupled with
# do_cmd.
.PHONY: FORCE_DO_CMD
FORCE_DO_CMD:
TOOLSET := target
# Suffix rules, putting all outputs into $(obj).
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
# Try building from generated source, too.
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
ifeq ($(strip $(foreach prefix,$(NO_LOAD),\
$(findstring $(join ^,$(prefix)),\
$(join ^,bufferutil.target.mk)))),)
include bufferutil.target.mk
endif
quiet_cmd_regen_makefile = ACTION Regenerating $@
cmd_regen_makefile = cd $(srcdir); /usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/home/brian/meanjs/node_modules/gulp-protractor/node_modules/protractor/node_modules/selenium-webdriver/node_modules/ws/node_modules/bufferutil/build/config.gypi -I/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/home/brian/.node-gyp/0.12.7/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/home/brian/.node-gyp/0.12.7" "-Dmodule_root_dir=/home/brian/meanjs/node_modules/gulp-protractor/node_modules/protractor/node_modules/selenium-webdriver/node_modules/ws/node_modules/bufferutil" binding.gyp
Makefile: $(srcdir)/../../../../../../../../../../../.node-gyp/0.12.7/common.gypi $(srcdir)/../../../../../../../../../../../../../usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp
$(call do_cmd,regen_makefile)
# "all" is a concatenation of the "all" targets from all the included
# sub-makefiles. This is just here to clarify.
all:
# Add in dependency-tracking rules. $(all_deps) is the list of every single
# target in our tree. Only consider the ones with .d (dependency) info:
d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d))
ifneq ($(d_files),)
include $(d_files)
endif
| {
"content_hash": "8f4c14b5ad46d1d2b8713ad1926c0de2",
"timestamp": "",
"source": "github",
"line_count": 318,
"max_line_length": 754,
"avg_line_length": 39.35849056603774,
"alnum_prop": 0.6633109619686801,
"repo_name": "BrianH2244/meansc",
"id": "c5e2597224e7f943a3d2a11ee316c8281ef6ad0c",
"size": "12846",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "node_modules/gulp-protractor/node_modules/protractor/node_modules/selenium-webdriver/node_modules/ws/node_modules/bufferutil/build/Makefile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2721"
},
{
"name": "CoffeeScript",
"bytes": "1656"
},
{
"name": "HTML",
"bytes": "70342"
},
{
"name": "JavaScript",
"bytes": "357757"
},
{
"name": "Makefile",
"bytes": "3906"
},
{
"name": "Shell",
"bytes": "685"
}
],
"symlink_target": ""
} |
class WXDLLIMPEXP_CORE wxMiniFrame: public wxFrame {
wxDECLARE_DYNAMIC_CLASS(wxMiniFrame);
public:
wxMiniFrame() {}
wxMiniFrame(wxWindow *parent,
wxWindowID id,
const wxString& title,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = wxCAPTION | wxRESIZE_BORDER | wxTINY_CAPTION,
const wxString& name = wxFrameNameStr)
{
// Use wxFrame constructor in absence of more specific code.
Create(parent, id, title, pos, size, style | wxFRAME_TOOL_WINDOW | wxFRAME_FLOAT_ON_PARENT , name);
}
virtual ~wxMiniFrame() {}
protected:
};
#endif
// _WX_MINIFRAM_H_
| {
"content_hash": "0ec93b41078bcf2fc35ce4a3fe3ef698",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 105,
"avg_line_length": 28.625,
"alnum_prop": 0.6506550218340611,
"repo_name": "fuzz-inc/wxump",
"id": "a4180f975e1354aa5e446d8957166c1856345613",
"size": "1273",
"binary": false,
"copies": "41",
"ref": "refs/heads/master",
"path": "external/mac/wxWidgets/include/wx-3.1/wx/osx/minifram.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C++",
"bytes": "190875"
},
{
"name": "Shell",
"bytes": "196"
}
],
"symlink_target": ""
} |
RAILS_GEM_VERSION = '2.3.9' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence those specified here
# Skip frameworks you're not going to use
# config.frameworks -= [ :action_web_service, :action_mailer ]
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Force all environments to use the same logger level
# (by default production uses :info, the others :debug)
# config.log_level = :debug
# Use the database for sessions instead of the file system
# (create the session table with 'rake create_sessions_table')
config.action_controller.session_store = :mem_cache_store
# Enable page/fragment caching by setting a file-based store
# (remember to create the caching directory and make it readable to the application)
# config.action_controller.fragment_cache_store = :file_store, "#{RAILS_ROOT}/cache"
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector
# Make Active Record use UTC-base instead of local time
# config.active_record.default_timezone = :utc
# Use Active Record's schema dumper instead of SQL when creating the test database
# (enables use of different database adapters for development and test environments)
# config.active_record.schema_format = :ruby
# See Rails::Configuration for more options
config.action_controller.session = { :key => "_my_openid_session", :secret => "264623e35408bffeda903507b309ba44" }
end
# Add new inflection rules using the following format
# (all these examples are active by default):
# Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
# Include your application configuration below
| {
"content_hash": "dbbbd575b6321db2fcb49fa933d17bac",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 116,
"avg_line_length": 41.1,
"alnum_prop": 0.7362530413625304,
"repo_name": "robinbortlik/ruby-mojeid",
"id": "fa21149c0f6b180442e24dbfb5c1cb9b20debd6d",
"size": "2284",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/rails_openid/config/environment.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "30664"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2014 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetLeft="@dimen/abc_edit_text_inset_horizontal_material"
android:insetRight="@dimen/abc_edit_text_inset_horizontal_material"
android:insetTop="@dimen/abc_edit_text_inset_top_material"
android:insetBottom="@dimen/abc_edit_text_inset_bottom_material">
<selector>
<item android:state_enabled="false" android:drawable="@drawable/abc_textfield_default_mtrl_alpha"/>
<item android:state_pressed="false" android:state_focused="false" android:drawable="@drawable/abc_textfield_default_mtrl_alpha"/>
<item android:drawable="@drawable/abc_textfield_activated_mtrl_alpha"/>
</selector>
</inset>
<!-- From: file:/usr/local/google/buildbot/repo_clients/https___googleplex-android.googlesource.com_a_platform_manifest.git/mnc-sdk-release/frameworks/support/v7/appcompat/res/drawable/abc_edit_text_material.xml --><!-- From: file:/Users/leland_richardson/code/react-native-maps/example/node_modules/react-native-maps/android/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.0.1/res/drawable/abc_edit_text_material.xml --> | {
"content_hash": "d0c39685c3287b479865447cf5434a45",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 442,
"avg_line_length": 61.166666666666664,
"alnum_prop": 0.7395095367847412,
"repo_name": "jasonlarue/react-native-flashcards",
"id": "6e7f450d1e68c75773ded4f4fd52dc513cc977be",
"size": "1835",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "node_modules/react-native-maps/lib/android/build/intermediates/res/merged/androidTest/debug/drawable/abc_edit_text_material.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "6931"
}
],
"symlink_target": ""
} |
<?php
namespace reinvently\ondemand\core\modules\settings\migrations;
use Yii;
use yii\db\Migration;
/**
* Class ExtraFeeTableMigration
* @package reinvently\ondemand\core\modules\settings\migrations
*/
class ExtraFeeTableMigration extends Migration
{
/**
*
*/
public function up()
{
$this->createTable('extra_fee', [
'id' => $this->primaryKey(),
'tariffId' => $this->integer()->notNull()->unsigned(),
'title' => $this->string(255),
'description' => $this->text(),
], 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci');
$this->createTable('extra_fee_time', [
'id' => $this->primaryKey(),
'extraFeeId' => $this->integer(10)->notNull(),
'timeStart' => $this->time()->notNull(),
'timeFinish' => $this->time()->notNull(),
]);
$this->createTable('extra_fee_day', [
'id' => $this->primaryKey(),
'extraFeeId' => $this->integer(10)->notNull(),
'day' => $this->integer(2)->notNull(),
]);
$this->createTable('extra_fee_month', [
'id' => $this->primaryKey(),
'extraFeeId' => $this->integer(10)->notNull(),
'month' => $this->integer(2)->notNull(),
]);
$this->createTable('extra_fee_year', [
'id' => $this->primaryKey(),
'extraFeeId' => $this->integer(10)->notNull(),
'year' => $this->integer(4)->notNull(),
]);
$this->createTable('extra_fee_weekday', [
'id' => $this->primaryKey(),
'extraFeeId' => $this->integer(10)->notNull(),
'weekday' => $this->integer(1)->notNull(),
]);
}
/**
* @return bool
*/
public function down()
{
$this->dropTable('extra_fee');
$this->dropTable('extra_fee_time');
$this->dropTable('extra_fee_day');
$this->dropTable('extra_fee_month');
$this->dropTable('extra_fee_year');
$this->dropTable('extra_fee_weekday');
return true;
}
}
| {
"content_hash": "02c362e2b10c113eeda2dfcf19d40274",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 73,
"avg_line_length": 28.56756756756757,
"alnum_prop": 0.511352885525071,
"repo_name": "Reinvently/On-Demand-Core",
"id": "aa1b658d0f9c4d0ace6b37572cdcf45b6f3abfd5",
"size": "2261",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/modules/settings/migrations/ExtraFeeTableMigration.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2919"
},
{
"name": "JavaScript",
"bytes": "156982"
},
{
"name": "PHP",
"bytes": "526157"
}
],
"symlink_target": ""
} |
/* ==========================================================================
* ./webpack.config.prod.js
*
* Webpack config for Production
* ========================================================================== */
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const WebpackOutputStatsPlugin = require('./utils/webpack-output-stats-plugin');
module.exports = {
devtool: 'source-map',
entry: [
'./src/client/index.js'
],
module: {
loaders: [
{
test: /\.(js|jsx)$/,
loaders: ['babel'],
exclude: /node_modules/,
include: __dirname
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract(
'style-loader',
'css-loader?minimize!postcss!sass-loader'
)
}
]
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new ExtractTextPlugin('style.css'),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
BROWSER: JSON.stringify(true),
GA_ID: JSON.stringify(process.env.GA_ID || 'UA-49527002-6')
}
}),
new webpack.optimize.UglifyJsPlugin({
minimize: true,
screw_ie8: false
}),
new WebpackOutputStatsPlugin()
]
};
| {
"content_hash": "f1ef0fa1a7b0c36c1153b7fe7368c679",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 80,
"avg_line_length": 26.612244897959183,
"alnum_prop": 0.5161042944785276,
"repo_name": "cle1994/personal-website",
"id": "865725e41ec87b6efe02d51b575fb68550b711a9",
"size": "1304",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "webpack.config.prod.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "16125"
},
{
"name": "HTML",
"bytes": "2225"
},
{
"name": "JavaScript",
"bytes": "83542"
},
{
"name": "Shell",
"bytes": "4468"
}
],
"symlink_target": ""
} |
"""
__LocalDef1orMoreDefPart2_Complete_MDL.py_____________________________________________________
Automatically generated AToM3 Model File (Do not modify directly)
Author: gehan
Modified: Mon Mar 2 14:57:51 2015
______________________________________________________________________________________________
"""
from stickylink import *
from widthXfillXdecoration import *
from LHS import *
from MT_pre__LocalDef import *
from MT_pre__directLink_T import *
from MT_pre__Def import *
from graph_MT_pre__Def import *
from graph_MT_pre__directLink_T import *
from graph_MT_pre__LocalDef import *
from graph_LHS import *
from ATOM3Enum import *
from ATOM3String import *
from ATOM3BottomType import *
from ATOM3Constraint import *
from ATOM3Attribute import *
from ATOM3Float import *
from ATOM3List import *
from ATOM3Link import *
from ATOM3Connection import *
from ATOM3Boolean import *
from ATOM3Appearance import *
from ATOM3Text import *
from ATOM3Action import *
from ATOM3Integer import *
from ATOM3Port import *
from ATOM3MSEnum import *
def LocalDef1orMoreDefPart2_Complete_MDL(self, rootNode, MT_pre__UMLRT2Kiltera_MMRootNode=None, MoTifRuleRootNode=None):
# --- Generating attributes code for ASG MT_pre__UMLRT2Kiltera_MM ---
if( MT_pre__UMLRT2Kiltera_MMRootNode ):
# author
MT_pre__UMLRT2Kiltera_MMRootNode.author.setValue('Annonymous')
# description
MT_pre__UMLRT2Kiltera_MMRootNode.description.setValue('\n')
MT_pre__UMLRT2Kiltera_MMRootNode.description.setHeight(15)
# name
MT_pre__UMLRT2Kiltera_MMRootNode.name.setValue('')
MT_pre__UMLRT2Kiltera_MMRootNode.name.setNone()
# --- ASG attributes over ---
# --- Generating attributes code for ASG MoTifRule ---
if( MoTifRuleRootNode ):
# author
MoTifRuleRootNode.author.setValue('Annonymous')
# description
MoTifRuleRootNode.description.setValue('\n')
MoTifRuleRootNode.description.setHeight(15)
# name
MoTifRuleRootNode.name.setValue('LocalDef1orMoreDefPart2_Complete')
# --- ASG attributes over ---
self.obj63227=LHS(self)
self.obj63227.isGraphObjectVisual = True
if(hasattr(self.obj63227, '_setHierarchicalLink')):
self.obj63227._setHierarchicalLink(False)
# constraint
self.obj63227.constraint.setValue('#===============================================================================\n# This code is executed after the nodes in the LHS have been matched.\n# You can access a matched node labelled n by: PreNode(\'n\').\n# To access attribute x of node n, use: PreNode(\'n\')[\'x\'].\n# The given constraint must evaluate to a boolean expression:\n# returning True enables the rule to be applied,\n# returning False forbids the rule from being applied.\n#===============================================================================\n\nreturn True\n')
self.obj63227.constraint.setHeight(15)
self.obj63227.graphClass_= graph_LHS
if self.genGraphics:
new_obj = graph_LHS(80.0,60.0,self.obj63227)
new_obj.DrawObject(self.UMLmodel)
self.UMLmodel.addtag_withtag("LHS", new_obj.tag)
new_obj.layConstraints = dict() # Graphical Layout Constraints
new_obj.layConstraints['scale'] = [1.0, 1.0]
else: new_obj = None
self.obj63227.graphObject_ = new_obj
# Add node to the root: rootNode
rootNode.addNode(self.obj63227)
self.globalAndLocalPostcondition(self.obj63227, rootNode)
self.obj63227.postAction( rootNode.CREATE )
self.obj63228=MT_pre__LocalDef(self)
self.obj63228.isGraphObjectVisual = True
if(hasattr(self.obj63228, '_setHierarchicalLink')):
self.obj63228._setHierarchicalLink(False)
# MT_label__
self.obj63228.MT_label__.setValue('1')
# MT_pivotOut__
self.obj63228.MT_pivotOut__.setValue('')
self.obj63228.MT_pivotOut__.setNone()
# MT_subtypeMatching__
self.obj63228.MT_subtypeMatching__.setValue(('True', 0))
self.obj63228.MT_subtypeMatching__.config = 0
# MT_pre__classtype
self.obj63228.MT_pre__classtype.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n')
self.obj63228.MT_pre__classtype.setHeight(15)
# MT_pre__cardinality
self.obj63228.MT_pre__cardinality.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n')
self.obj63228.MT_pre__cardinality.setHeight(15)
# MT_pre__name
self.obj63228.MT_pre__name.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n')
self.obj63228.MT_pre__name.setHeight(15)
# MT_pivotIn__
self.obj63228.MT_pivotIn__.setValue('element1')
self.obj63228.graphClass_= graph_MT_pre__LocalDef
if self.genGraphics:
new_obj = graph_MT_pre__LocalDef(140.0,100.0,self.obj63228)
new_obj.DrawObject(self.UMLmodel)
self.UMLmodel.addtag_withtag("MT_pre__LocalDef", new_obj.tag)
new_obj.layConstraints = dict() # Graphical Layout Constraints
new_obj.layConstraints['scale'] = [1.0, 1.0]
else: new_obj = None
self.obj63228.graphObject_ = new_obj
# Add node to the root: rootNode
rootNode.addNode(self.obj63228)
self.globalAndLocalPostcondition(self.obj63228, rootNode)
self.obj63228.postAction( rootNode.CREATE )
self.obj73750=MT_pre__directLink_T(self)
self.obj73750.isGraphObjectVisual = True
if(hasattr(self.obj73750, '_setHierarchicalLink')):
self.obj73750._setHierarchicalLink(False)
# MT_label__
self.obj73750.MT_label__.setValue('3')
# MT_pivotOut__
self.obj73750.MT_pivotOut__.setValue('')
self.obj73750.MT_pivotOut__.setNone()
# MT_subtypeMatching__
self.obj73750.MT_subtypeMatching__.setValue(('True', 0))
self.obj73750.MT_subtypeMatching__.config = 0
# MT_pivotIn__
self.obj73750.MT_pivotIn__.setValue('')
self.obj73750.MT_pivotIn__.setNone()
# MT_pre__associationType
self.obj73750.MT_pre__associationType.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n')
self.obj73750.MT_pre__associationType.setHeight(15)
self.obj73750.graphClass_= graph_MT_pre__directLink_T
if self.genGraphics:
new_obj = graph_MT_pre__directLink_T(397.0,281.0,self.obj73750)
new_obj.DrawObject(self.UMLmodel)
self.UMLmodel.addtag_withtag("MT_pre__directLink_T", new_obj.tag)
new_obj.layConstraints = dict() # Graphical Layout Constraints
else: new_obj = None
self.obj73750.graphObject_ = new_obj
# Add node to the root: rootNode
rootNode.addNode(self.obj73750)
self.globalAndLocalPostcondition(self.obj73750, rootNode)
self.obj73750.postAction( rootNode.CREATE )
self.obj73747=MT_pre__Def(self)
self.obj73747.isGraphObjectVisual = True
if(hasattr(self.obj73747, '_setHierarchicalLink')):
self.obj73747._setHierarchicalLink(False)
# MT_pivotOut__
self.obj73747.MT_pivotOut__.setValue('')
self.obj73747.MT_pivotOut__.setNone()
# MT_subtypeMatching__
self.obj73747.MT_subtypeMatching__.setValue(('True', 1))
self.obj73747.MT_subtypeMatching__.config = 0
# MT_pre__classtype
self.obj73747.MT_pre__classtype.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n')
self.obj73747.MT_pre__classtype.setHeight(15)
# MT_pivotIn__
self.obj73747.MT_pivotIn__.setValue('')
self.obj73747.MT_pivotIn__.setNone()
# MT_label__
self.obj73747.MT_label__.setValue('2')
# MT_pre__cardinality
self.obj73747.MT_pre__cardinality.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n')
self.obj73747.MT_pre__cardinality.setHeight(15)
# MT_pre__name
self.obj73747.MT_pre__name.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n')
self.obj73747.MT_pre__name.setHeight(15)
self.obj73747.graphClass_= graph_MT_pre__Def
if self.genGraphics:
new_obj = graph_MT_pre__Def(220.0,260.0,self.obj73747)
new_obj.DrawObject(self.UMLmodel)
self.UMLmodel.addtag_withtag("MT_pre__Def", new_obj.tag)
new_obj.layConstraints = dict() # Graphical Layout Constraints
new_obj.layConstraints['scale'] = [1.0, 1.0]
else: new_obj = None
self.obj73747.graphObject_ = new_obj
# Add node to the root: rootNode
rootNode.addNode(self.obj73747)
self.globalAndLocalPostcondition(self.obj73747, rootNode)
self.obj73747.postAction( rootNode.CREATE )
# Connections for obj63227 (graphObject_: Obj8) of type LHS
self.drawConnections(
)
# Connections for obj63228 (graphObject_: Obj9) of type MT_pre__LocalDef
self.drawConnections(
(self.obj63228,self.obj73750,[357.0, 201.0, 397.0, 281.0],"true", 2) )
# Connections for obj73750 (graphObject_: Obj11) of type MT_pre__directLink_T
self.drawConnections(
(self.obj73750,self.obj73747,[397.0, 281.0, 437.0, 361.0],"true", 2) )
# Connections for obj73747 (graphObject_: Obj10) of type MT_pre__Def
self.drawConnections(
)
newfunction = LocalDef1orMoreDefPart2_Complete_MDL
loadedMMName = ['MT_pre__UMLRT2Kiltera_MM_META', 'MoTifRule_META']
atom3version = '0.3'
| {
"content_hash": "51b3977653f00f383179ae682f556ff8",
"timestamp": "",
"source": "github",
"line_count": 243,
"max_line_length": 632,
"avg_line_length": 52.51851851851852,
"alnum_prop": 0.6347751136185551,
"repo_name": "levilucio/SyVOLT",
"id": "c9e16150a709f6fc935af11914172d71997266c5",
"size": "12762",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "UMLRT2Kiltera_MM/Properties/Multiplicity/models/LocalDef1orMoreDefPart2_Complete_MDL.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "166159"
},
{
"name": "Python",
"bytes": "34207588"
},
{
"name": "Shell",
"bytes": "1118"
}
],
"symlink_target": ""
} |
<ul{% if recent_posts_class %} class="{{ recent_posts_class }}"{% endif %}>
{% for post in recent_posts %}
{% load lang %}
<li><a href="{{ post.get_absolute_url }}">{% t post.title %}</a></li>
{% endfor %}
</ul>
| {
"content_hash": "b3b9d9b910cd65c22ae3feafdf6f832d",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 75,
"avg_line_length": 37.333333333333336,
"alnum_prop": 0.5357142857142857,
"repo_name": "rimbalinux/MSISDNArea",
"id": "685a9ad22a78ccf0f2d23ad4e80603f99a33ac79",
"size": "224",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "blog/templates/blog/recent_posts.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "118069"
},
{
"name": "Python",
"bytes": "7281875"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>elpi: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.15.1 / elpi - 1.2.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
elpi
<small>
1.2.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-04-01 06:07:12 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-04-01 06:07:12 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.15.1 Formal proof management system
dune 3.0.3 Fast, portable, and opinionated build system
ocaml 4.07.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.07.1 Official release 4.07.1
ocaml-config 1 OCaml Switch Configuration
ocaml-secondary-compiler 4.08.1-1 OCaml 4.08.1 Secondary Switch Compiler
ocamlfind 1.9.1 A library manager for OCaml
ocamlfind-secondary 1.9.1 Adds support for ocaml-secondary-compiler to ocamlfind
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
name: "coq-elpi"
maintainer: "Enrico Tassi <enrico.tassi@inria.fr>"
authors: [ "Enrico Tassi" ]
license: "LGPL 2.1"
homepage: "https://github.com/LPCIC/coq-elpi"
bug-reports: "https://github.com/LPCIC/coq-elpi/issues"
dev-repo: "git+https://github.com/LPCIC/coq-elpi"
build: [ make "COQBIN=%{bin}%/" "ELPIDIR=%{prefix}%/lib/elpi" ]
install: [ make "install" "COQBIN=%{bin}%/" "ELPIDIR=%{prefix}%/lib/elpi" ]
depends: [
"elpi" {>= "1.8.0" & < "1.9.0~"}
"coq" { (>= "8.10.0" & < "8.11~") | (= "8.10.dev") }
]
synopsis: "Elpi extension language for Coq"
description: """
Coq-elpi provides a Coq plugin that embeds ELPI.
It also provides a way to embed Coq's terms into λProlog using
the Higher-Order Abstract Syntax approach
and a way to read terms back. In addition to that it exports to ELPI a
set of Coq's primitives, e.g. printing a message, accessing the
environment of theorems and data types, defining a new constant and so on.
For convenience it also provides a quotation and anti-quotation for Coq's
syntax in λProlog. E.g. `{{nat}}` is expanded to the type name of natural
numbers, or `{{A -> B}}` to the representation of a product by unfolding
the `->` notation. Finally it provides a way to define new vernacular commands
and new tactics."""
url {
src: "https://github.com/LPCIC/coq-elpi/archive/v1.2.0.tar.gz"
checksum: "sha256=58aef9596e6ad74d9f230abc34171dafaa39da93a4f1bf6f07f69904360c2c9c"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-elpi.1.2.0 coq.8.15.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.15.1).
The following dependencies couldn't be met:
- coq-elpi -> coq = 8.10.dev -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-elpi.1.2.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "ff9a4a07705f3f542f12e07d791af9e0",
"timestamp": "",
"source": "github",
"line_count": 175,
"max_line_length": 159,
"avg_line_length": 44.23428571428571,
"alnum_prop": 0.5539336003100375,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "e6abb24e530c2ce79044daa7aba982e95cc89122",
"size": "7768",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.07.1-2.0.6/released/8.15.1/elpi/1.2.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>higman-nw: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.16.0 / higman-nw - 8.5.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
higman-nw
<small>
8.5.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-09-17 05:36:57 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-09-17 05:36:57 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.16.0 Formal proof management system
dune 3.4.1 Fast, portable, and opinionated build system
ocaml 4.10.2 The OCaml compiler (virtual package)
ocaml-base-compiler 4.10.2 Official release 4.10.2
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "matej.kosik@inria.fr"
homepage: "https://github.com/coq-contribs/higman-nw"
license: "LGPL 2"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/HigmanNW"]
depends: [
"ocaml"
"coq" {>= "8.5" & < "8.6~"}
]
tags: [
"keyword:A-translation"
"keyword:Higman's lemma"
"keyword:impredicativity"
"keyword:System F"
"keyword:extraction"
"category:Mathematics/Combinatorics and Graph Theory"
"category:Miscellaneous/Extracted Programs/Combinatorics"
]
authors: [ "Hugo Herbelin <>" ]
bug-reports: "https://github.com/coq-contribs/higman-nw/issues"
dev-repo: "git+https://github.com/coq-contribs/higman-nw.git"
synopsis: "A program from an A-translated impredicative proof of Higman's Lemma"
description: """
The file Higman.v formalizes an A-translated version of
Nash-Williams impredicative and classical proof of Higman's lemma
for a two-letter alphabet.
A constructive and impredicative program can be extracted from the proof."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/higman-nw/archive/v8.5.0.tar.gz"
checksum: "md5=9929b301e66933897c31c515a03a5c8f"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-higman-nw.8.5.0 coq.8.16.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.16.0).
The following dependencies couldn't be met:
- coq-higman-nw -> coq < 8.6~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-higman-nw.8.5.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "3e441f27bb731ddec9c03085362f4442",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 159,
"avg_line_length": 41.36206896551724,
"alnum_prop": 0.5505071557593442,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "af7663972cbe4803c3daa5685c89326a51babe4c",
"size": "7222",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.10.2-2.0.6/released/8.16.0/higman-nw/8.5.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<?php
namespace Symfony\Component\EventDispatcher\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
/**
* Compiler pass to register tagged services for an event dispatcher.
*/
class RegisterListenersPass implements CompilerPassInterface {
/**
* @var string
*/
protected $dispatcherService;
/**
* @var string
*/
protected $listenerTag;
/**
* @var string
*/
protected $subscriberTag;
/**
* Constructor.
*
* @param string $dispatcherService Service name of the event dispatcher in processed container
* @param string $listenerTag Tag name used for listener
* @param string $subscriberTag Tag name used for subscribers
*/
public function __construct($dispatcherService = 'event_dispatcher', $listenerTag = 'kernel.event_listener', $subscriberTag = 'kernel.event_subscriber') {
$this->dispatcherService = $dispatcherService;
$this->listenerTag = $listenerTag;
$this->subscriberTag = $subscriberTag;
}
public function process(ContainerBuilder $container) {
if (!$container->hasDefinition($this->dispatcherService) && !$container->hasAlias($this->dispatcherService)) {
return;
}
$definition = $container->findDefinition($this->dispatcherService);
foreach ($container->findTaggedServiceIds($this->listenerTag) as $id => $events) {
$def = $container->getDefinition($id);
if (!$def->isPublic()) {
throw new \InvalidArgumentException(sprintf('The service "%s" must be public as event listeners are lazy-loaded.', $id));
}
if ($def->isAbstract()) {
throw new \InvalidArgumentException(sprintf('The service "%s" must not be abstract as event listeners are lazy-loaded.', $id));
}
foreach ($events as $event) {
$priority = isset($event['priority']) ? $event['priority'] : 0;
if (!isset($event['event'])) {
throw new \InvalidArgumentException(sprintf('Service "%s" must define the "event" attribute on "%s" tags.', $id, $this->listenerTag));
}
if (!isset($event['method'])) {
$event['method'] = 'on' . preg_replace_callback(array(
'/(?<=\b)[a-z]/i',
'/[^a-z0-9]/i',
), function ($matches) {
return strtoupper($matches[0]);
}, $event['event']);
$event['method'] = preg_replace('/[^a-z0-9]/i', '', $event['method']);
}
$definition->addMethodCall('addListenerService', array($event['event'], array($id, $event['method']), $priority));
}
}
foreach ($container->findTaggedServiceIds($this->subscriberTag) as $id => $attributes) {
$def = $container->getDefinition($id);
if (!$def->isPublic()) {
throw new \InvalidArgumentException(sprintf('The service "%s" must be public as event subscribers are lazy-loaded.', $id));
}
if ($def->isAbstract()) {
throw new \InvalidArgumentException(sprintf('The service "%s" must not be abstract as event subscribers are lazy-loaded.', $id));
}
// We must assume that the class value has been correctly filled, even if the service is created by a factory
$class = $container->getParameterBag()->resolveValue($def->getClass());
$refClass = new \ReflectionClass($class);
$interface = 'Symfony\Component\EventDispatcher\EventSubscriberInterface';
if (!$refClass->implementsInterface($interface)) {
throw new \InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $id, $interface));
}
$definition->addMethodCall('addSubscriberService', array($id, $class));
}
}
}
| {
"content_hash": "168550267223d2f60b2976ab4e82f6e0",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 158,
"avg_line_length": 39.98076923076923,
"alnum_prop": 0.5808080808080808,
"repo_name": "Amaire/filmy",
"id": "01a6d016cbb6cc5b6ce03799d8742f53ae5832dc",
"size": "4387",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/symfony/event-dispatcher/Symfony/Component/EventDispatcher/DependencyInjection/RegisterListenersPass.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "356"
},
{
"name": "JavaScript",
"bytes": "504"
},
{
"name": "PHP",
"bytes": "105599"
}
],
"symlink_target": ""
} |
#ifndef GCC_GENSUPPORT_H
#define GCC_GENSUPPORT_H
struct obstack;
extern struct obstack *rtl_obstack;
extern const char *in_fname;
extern int init_md_reader_args_cb (int, char **, bool (*)(const char *));
extern int init_md_reader_args (int, char **);
extern rtx read_md_rtx (int *, int *);
extern void message_with_line (int, const char *, ...)
ATTRIBUTE_PRINTF_2;
/* Set this to 0 to disable automatic elision of insn patterns which
can never be used in this configuration. See genconditions.c.
Must be set before calling init_md_reader. */
extern int insn_elision;
/* If the C test passed as the argument can be evaluated at compile
time, return its truth value; else return -1. The test must have
appeared somewhere in the machine description when genconditions
was run. */
extern int maybe_eval_c_test (const char *);
/* Add an entry to the table of conditions. Used by genconditions and
by read-rtl.c. */
extern void add_c_test (const char *, int);
/* This structure is used internally by gensupport.c and genconditions.c. */
struct c_test
{
const char *expr;
int value;
};
#ifdef __HASHTAB_H__
extern hashval_t hash_c_test (const void *);
extern int cmp_c_test (const void *, const void *);
extern void traverse_c_tests (htab_trav, void *);
#endif
extern int n_comma_elts (const char *);
extern const char *scan_comma_elt (const char **);
/* Predicate handling: helper functions and data structures. */
struct pred_data
{
struct pred_data *next; /* for iterating over the set of all preds */
const char *name; /* predicate name */
bool special; /* special handling of modes? */
/* data used primarily by genpreds.c */
const char *c_block; /* C test block */
rtx exp; /* RTL test expression */
/* data used primarily by genrecog.c */
enum rtx_code singleton; /* if pred takes only one code, that code */
bool allows_non_lvalue; /* if pred allows non-lvalue expressions */
bool allows_non_const; /* if pred allows non-const expressions */
bool codes[NUM_RTX_CODE]; /* set of codes accepted */
};
extern struct pred_data *first_predicate;
extern struct pred_data *lookup_predicate (const char *);
extern void add_predicate (struct pred_data *);
#define FOR_ALL_PREDICATES(p) for (p = first_predicate; p; p = p->next)
/* This callback will be invoked whenever an rtl include directive is
processed. To be used for creation of the dependency file. */
extern void (*include_callback) (const char *);
#endif /* GCC_GENSUPPORT_H */
| {
"content_hash": "f68a795db5ff18a35ce2ec1d44cff0f2",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 78,
"avg_line_length": 34.15584415584416,
"alnum_prop": 0.6711026615969582,
"repo_name": "avaitla/Haskell-to-C---Bridge",
"id": "75899b1842476aa32931cb6d0456cbd755f259f9",
"size": "3446",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gccxml/GCC/gcc/gensupport.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "1194590"
},
{
"name": "C",
"bytes": "40073785"
},
{
"name": "C++",
"bytes": "2198628"
},
{
"name": "Haskell",
"bytes": "22377"
},
{
"name": "JavaScript",
"bytes": "10874"
},
{
"name": "Perl",
"bytes": "1373"
},
{
"name": "Python",
"bytes": "696243"
},
{
"name": "Shell",
"bytes": "1623468"
}
],
"symlink_target": ""
} |
'use strict';
const Filter = require('broccoli-persistent-filter');
const { stripIndent } = require('common-tags');
GlimmerTemplatePrecompiler.prototype = Object.create(Filter.prototype);
function GlimmerTemplatePrecompiler(inputTree, options) {
if (!(this instanceof GlimmerTemplatePrecompiler)) {
return new GlimmerTemplatePrecompiler(inputTree, options);
}
Filter.call(this, inputTree, {});
this.inputTree = inputTree;
if (!options.glimmer) {
throw new Error('No glimmer option provided!');
}
this.precompile = options.glimmer.precompile;
}
GlimmerTemplatePrecompiler.prototype.extensions = ['hbs'];
GlimmerTemplatePrecompiler.prototype.targetExtension = 'js';
GlimmerTemplatePrecompiler.prototype.baseDir = function() {
return __dirname;
};
GlimmerTemplatePrecompiler.prototype.processString = function(content, relativePath) {
var compiled = this.precompile(content, {
meta: { moduleName: relativePath },
});
return stripIndent`
import template from '../template';
export default template(${compiled});
`;
};
module.exports = GlimmerTemplatePrecompiler;
| {
"content_hash": "a9d453c0562148f4a22d2e81f758ca61",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 86,
"avg_line_length": 28.512820512820515,
"alnum_prop": 0.7473021582733813,
"repo_name": "thoov/ember.js",
"id": "51a7ba30473620a5efb0b8e2e4b62542d6afd082",
"size": "1112",
"binary": false,
"copies": "14",
"ref": "refs/heads/master",
"path": "broccoli/glimmer-template-compiler.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "9511"
},
{
"name": "JavaScript",
"bytes": "3522665"
},
{
"name": "Shell",
"bytes": "740"
},
{
"name": "TypeScript",
"bytes": "640084"
}
],
"symlink_target": ""
} |
package cn.jpush.im.android.demo.activity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.im.android.demo.R;
import cn.jpush.im.android.demo.Listener.OnChangedListener;
import cn.jpush.im.android.demo.view.SlipButton;
public class NotificationSettingActivity extends BaseActivity implements OnChangedListener{
private ImageButton mReturnBtn;
private TextView mTitle;
private ImageButton mMenuBtn;
SlipButton mNotificationBtn;
SlipButton mSoundBtn;
SlipButton mVibrateBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_setting);
mReturnBtn = (ImageButton) findViewById(R.id.return_btn);
mTitle = (TextView) findViewById(R.id.title);
mMenuBtn = (ImageButton) findViewById(R.id.right_btn);
mNotificationBtn = (SlipButton) findViewById(R.id.notification_switch);
mSoundBtn = (SlipButton) findViewById(R.id.sound_switch);
mVibrateBtn = (SlipButton) findViewById(R.id.vibrate_switch);
mReturnBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
mTitle.setText(this.getString(R.string.new_msg_remind_hit));
mMenuBtn.setVisibility(View.GONE);
mNotificationBtn.setOnChangedListener(R.id.notification_switch, this);
mNotificationBtn.setChecked(false);
mSoundBtn.setOnChangedListener(R.id.sound_switch, this);
mSoundBtn.setChecked(false);
mVibrateBtn.setOnChangedListener(R.id.vibrate_switch, this);
mVibrateBtn.setChecked(false);
}
@Override
public void OnChanged(int id, boolean CheckState) {
switch (id){
case R.id.notification_switch:
if(CheckState){
Toast.makeText(NotificationSettingActivity.this, "notification switch is open!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(NotificationSettingActivity.this, "notification switch is closed!", Toast.LENGTH_SHORT).show();
}
break;
case R.id.sound_switch:
if(CheckState){
Toast.makeText(NotificationSettingActivity.this, "sound switch is opened!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(NotificationSettingActivity.this, "sound switch is closed!", Toast.LENGTH_SHORT).show();
}
break;
case R.id.vibrate_switch:
if(CheckState){
Toast.makeText(NotificationSettingActivity.this, "vibrate switch is opened!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(NotificationSettingActivity.this, "vibrate switch is closed!", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
| {
"content_hash": "f6957fae548895b1d45d54bb0b3b36ca",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 130,
"avg_line_length": 37.857142857142854,
"alnum_prop": 0.6481132075471698,
"repo_name": "youirong/jchat-android-master",
"id": "0bd542361cfe993e4395132a83b1c0aa12ad709c",
"size": "3180",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "JMessageDemo/src/cn/jpush/im/android/demo/activity/NotificationSettingActivity.java",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "499248"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>Saltr iOS SDK: SLTBoardLayer Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">Saltr iOS SDK
 <span id="projectnumber">1.3.2</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.9.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-methods">Instance Methods</a> |
<a href="#properties">Properties</a> |
<a href="class_s_l_t_board_layer-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">SLTBoardLayer Class Reference</div> </div>
</div><!--header-->
<div class="contents">
<p>The <a class="el" href="interface_s_l_t_board_layer.html" title="The SLTBoardLayer class represents the game board's layer. ">SLTBoardLayer</a> class represents the game board's layer.
<a href="interface_s_l_t_board_layer.html#details">More...</a></p>
<p><code>#import <<a class="el" href="_s_l_t_board_layer_8h_source.html">SLTBoardLayer.h</a>></code></p>
<div class="dynheader">
Inheritance diagram for SLTBoardLayer:</div>
<div class="dyncontent">
<div class="center">
<img src="interface_s_l_t_board_layer.png" usemap="#SLTBoardLayer_map" alt=""/>
<map id="SLTBoardLayer_map" name="SLTBoardLayer_map">
<area href="interface_s_l_t2_d_board_layer.html" title="The SLT2DBoardLayer class represents the game 2D board's layer. " alt="SLT2DBoardLayer" shape="rect" coords="0,112,153,136"/>
<area href="interface_s_l_t_matching_board_layer.html" title="The SLTMatchingBoardLayer class represents the matching board. " alt="SLTMatchingBoardLayer" shape="rect" coords="163,112,316,136"/>
</map>
</div></div>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Instance Methods</h2></td></tr>
<tr class="memitem:a98070e01e36b88dd3423ec8539b65bac"><td class="memItemLeft" align="right" valign="top">(id) </td><td class="memItemRight" valign="bottom">- <a class="el" href="interface_s_l_t_board_layer.html#a98070e01e36b88dd3423ec8539b65bac">initWithToken:andLayerIndex:</a></td></tr>
<tr class="separator:a98070e01e36b88dd3423ec8539b65bac"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="properties"></a>
Properties</h2></td></tr>
<tr class="memitem:ab8816d81fe83a9e0330b0e50544e4f1c"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ab8816d81fe83a9e0330b0e50544e4f1c"></a>
NSString * </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_s_l_t_board_layer.html#ab8816d81fe83a9e0330b0e50544e4f1c">token</a></td></tr>
<tr class="memdesc:ab8816d81fe83a9e0330b0e50544e4f1c"><td class="mdescLeft"> </td><td class="mdescRight">The unique identifier of the layer. <br /></td></tr>
<tr class="separator:ab8816d81fe83a9e0330b0e50544e4f1c"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a21cd27f9d72048ac17628bff558feffb"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a21cd27f9d72048ac17628bff558feffb"></a>
NSInteger </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_s_l_t_board_layer.html#a21cd27f9d72048ac17628bff558feffb">index</a></td></tr>
<tr class="memdesc:a21cd27f9d72048ac17628bff558feffb"><td class="mdescLeft"> </td><td class="mdescRight">The layer's ordering index. <br /></td></tr>
<tr class="separator:a21cd27f9d72048ac17628bff558feffb"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>The <a class="el" href="interface_s_l_t_board_layer.html" title="The SLTBoardLayer class represents the game board's layer. ">SLTBoardLayer</a> class represents the game board's layer. </p>
</div><h2 class="groupheader">Method Documentation</h2>
<a class="anchor" id="a98070e01e36b88dd3423ec8539b65bac"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">- (id) initWithToken: </td>
<td></td>
<td class="paramtype">(NSString *) </td>
<td class="paramname"><em>theToken</em></td>
</tr>
<tr>
<td class="paramkey">andLayerIndex:</td>
<td></td>
<td class="paramtype">(NSInteger) </td>
<td class="paramname"><em>theLayerIndex</em> </td>
</tr>
<tr>
<td></td>
<td></td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Inits an instance of <b><a class="el" href="interface_s_l_t_board_layer.html" title="The SLTBoardLayer class represents the game board's layer. ">SLTBoardLayer</a></b> class with the given token and layer index. </p><dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">theToken</td><td>The unique identifier of the layer. </td></tr>
<tr><td class="paramname">theLayerIndex</td><td>The layer's ordering index. </td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>The instance of <b><a class="el" href="interface_s_l_t_board_layer.html" title="The SLTBoardLayer class represents the game board's layer. ">SLTBoardLayer</a></b> class. </dd></dl>
<p>Implemented in <a class="el" href="interface_s_l_t_matching_board_layer.html#a285f9b3227504cd9ea9d536215c598de">SLTMatchingBoardLayer</a>, and <a class="el" href="interface_s_l_t2_d_board_layer.html#a1b2f67d46a6967050957a6db7a46e5fd">SLT2DBoardLayer</a>.</p>
</div>
</div>
<hr/>The documentation for this class was generated from the following file:<ul>
<li>Saltr/game/<a class="el" href="_s_l_t_board_layer_8h_source.html">SLTBoardLayer.h</a></li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Wed Feb 4 2015 16:13:48 for Saltr iOS SDK by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.9.1
</small></address>
</body>
</html>
| {
"content_hash": "9a4154ecd7b9b3c85b4bf374f3cc8b15",
"timestamp": "",
"source": "github",
"line_count": 176,
"max_line_length": 293,
"avg_line_length": 52.89772727272727,
"alnum_prop": 0.672717508055854,
"repo_name": "SALTR/saltr-ios-sdk",
"id": "a6e4f801fc86206196930a34f0defc8fb5f4d39a",
"size": "9310",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "build/bin/Saltr.v.1.3.2/doc/com.mycompany.DoxygenExample.docset/Contents/Resources/Documents/interface_s_l_t_board_layer.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ActionScript",
"bytes": "5888"
},
{
"name": "CSS",
"bytes": "128540"
},
{
"name": "HTML",
"bytes": "6006084"
},
{
"name": "JavaScript",
"bytes": "352466"
},
{
"name": "Makefile",
"bytes": "2076"
},
{
"name": "Objective-C",
"bytes": "299702"
}
],
"symlink_target": ""
} |
namespace ChilliSource
{
//---------------------------------------------------------------
/// A system for managing all input gestures. All gestures must
/// be registered with this system before they will recieve input
/// events. Gesture collision resolution can also be handled
/// through this system.
///
/// @author Ian Copland
//---------------------------------------------------------------
class GestureSystem final : public StateSystem
{
public:
CS_DECLARE_NAMEDTYPE(GestureSystem);
//--------------------------------------------------------
/// An enum describing the possible results from a gesture
/// conflict.
///
/// @author Ian Copland
//--------------------------------------------------------
enum class ConflictResult
{
k_neitherGesture,
k_existingGesture,
k_newGesture,
k_bothGestures
};
//--------------------------------------------------------
/// A delegate which will be called when the activation of
/// a gesture conflicts with another. The delegate should
/// return a Conflict Result decribing which gesture
/// should continue/activate.
///
/// @author Ian Copland
///
/// @param The existing gesture that is already active.
/// @param The new gesture trying to activate.
///
/// @return The result of the collision. The value returned
/// should reflect which gestures will be allowed to start
/// or continue.
//---------------------------------------------------------
using ConflictResolutionDelegate = std::function<ConflictResult(const Gesture*, const Gesture*)>;
//--------------------------------------------------------
/// Queries whether or not this implements the interface
/// with the given Id. This is threadsafe.
///
/// @author Ian Copland
///
/// @param The interface Id.
///
/// @return Whether or not the inteface is implemented.
//---------------------------------------------------------
bool IsA(InterfaceIDType in_interfaceId) const override;
//--------------------------------------------------------
/// Adds a gesture to the gesture system. When added to the
/// system a gesture will receive input events. This is
/// threadsafe.
///
/// @author Ian Copland
///
/// @param The gesture to add to the system.
//---------------------------------------------------------
void AddGesture(const GestureSPtr& in_gesture);
//--------------------------------------------------------
/// Removes a gesture from the system. When removed from
/// the system a gesture will no longer recieve input
/// events. This is threadsafe.
///
/// @author Ian Copland
///
/// @param The gesture which should be removed from the
/// system.
//---------------------------------------------------------
void RemoveGesture(const Gesture* in_gesture);
//--------------------------------------------------------
/// Sets a delegate that should be used to handle gesture
/// conflict resolution. If two gestures are active at
/// the same time the delegate will be called. The conflict
/// result enum describes what the result of the conflict
/// should be. If no delegate is set both will always be
/// allowed. This is threadsafe.
///
/// @author Ian Copland
///
/// @param The delegate. Can be null.
//---------------------------------------------------------
void SetConflictResolutionDelegate(const ConflictResolutionDelegate& in_delegate);
private:
friend class State;
friend class Gesture;
//--------------------------------------------------------
/// Creates a new instance of this system. This shou
///
/// @author Ian Copland
///
/// @param The content downloader that should be used.
///
/// @return The new system instance.
//--------------------------------------------------------
static GestureSystemUPtr Create();
//--------------------------------------------------------
/// Default constructor. Declared private to force the use
/// of the factory method.
///
/// @author Ian Copland
//--------------------------------------------------------
GestureSystem() = default;
//--------------------------------------------------------
/// Process all deferred additions and removals to and
/// from the gesture list.
///
/// @author Ian Copland
//--------------------------------------------------------
void ProcessDeferredAddAndRemovals();
//--------------------------------------------------------
/// Performs conflict resolution on the gestures and
/// returns whether or not the given gesture can be activated.
/// Any gestures that are currently active which should end
/// on conflict with this gesture will have their Cancel()
/// method called.
///
/// @author Ian Copland
///
/// @param The gesture to perform conflict detection on.
///
/// @param Whether or not the gesture can activate.
//--------------------------------------------------------
bool ResolveConflicts(Gesture* in_gesture);
//--------------------------------------------------------
/// Resets all gestures.
///
/// @author Ian Copland
//--------------------------------------------------------
void ResetAll();
//--------------------------------------------------------
/// Called when the owning state is resumed. This
/// registers for the input events.
///
/// @author Ian Copland
//--------------------------------------------------------
void OnResume() override;
//--------------------------------------------------------
/// Called when the owning state is updated. This passes
/// the event onto all registered gestures.
///
/// @author Ian Copland
///
/// @param The delta time since the last update.
//--------------------------------------------------------
void OnUpdate(f32 in_deltaTime) override;
//--------------------------------------------------------
/// Called when a pointer down event is received from the
/// pointer system. This will be relayed onto each
/// active gesture in this gesture system.
///
/// @author Ian Copland
///
/// @param The pointer.
/// @param The timestamp of the event.
/// @param The press type.
/// @param The filter, allowing exclusion from the filtered
/// input event.
//--------------------------------------------------------
void OnPointerDown(const Pointer& in_pointer, f64 in_timestamp, Pointer::InputType in_inputType, InputFilter& in_filter);
//--------------------------------------------------------
/// Called when a pointer moved event is received from the
/// pointer system. This will be relayed onto each active
/// gesture in this gesture system.
///
/// @author Ian Copland
///
/// @param The pointer
/// @param The timestamp of the event.
//--------------------------------------------------------
void OnPointerMoved(const Pointer& in_pointer, f64 in_timestamp);
//--------------------------------------------------------
/// Called when a pointer up event is received from the
/// pointer system. This will be relayed onto each active
/// gesture in this system.
///
/// @author Ian Copland
///
/// @param The pointer
/// @param The timestamp of the event.
/// @param The press type.
//--------------------------------------------------------
void OnPointerUp(const Pointer& in_pointer, f64 in_timestamp, Pointer::InputType in_inputType);
//--------------------------------------------------------
/// Called when a pointer scrolled event is received from
/// the pointer system. This will be relayed onto each
/// active gesture in this system.
///
/// @author Ian Copland
///
/// @param The pointer
/// @param The timestamp of the event.
/// @param The scroll vector (x, y delta)
/// @param The filter, allowing exclusion from the filtered
/// input event.
//--------------------------------------------------------
void OnPointerScrolled(const Pointer& in_pointer, f64 in_timestamp, const Vector2& in_delta, InputFilter& in_filter);
//-------------------------------------------------------
/// A proxy method for calling GestureSystem::OnPointerDown()
/// using the old GUI consumption model. This simply relays
/// on the information to the new method with a unfiltered
/// filter.
///
/// @author Ian Copland
///
/// @param The pointer.
/// @param The timestamp of the event.
/// @param The press type.
//--------------------------------------------------------
void OnPointerDownLegacy(const Pointer& in_pointer, f64 in_timestamp, Pointer::InputType in_inputType);
//--------------------------------------------------------
/// Called when the owning state is suspeneded. This
/// de-registers all of the input events.
///
/// @author Ian Copland
//--------------------------------------------------------
void OnSuspend() override;
//--------------------------------------------------------
/// Called when the owning state is destroyed.
///
/// @author Ian Copland
//--------------------------------------------------------
void OnDestroy() override;
std::recursive_mutex m_mutex;
concurrent_vector<GestureSPtr> m_gestures;
ConflictResolutionDelegate m_conflictResolutionDelegate;
EventConnectionUPtr m_pointerDownConnection;
EventConnectionUPtr m_pointerMovedConnection;
EventConnectionUPtr m_pointerUpConnection;
EventConnectionUPtr m_pointerScrolledConnection;
};
}
#endif
| {
"content_hash": "ae4ca41e78e93e087279c56414869a9a",
"timestamp": "",
"source": "github",
"line_count": 243,
"max_line_length": 129,
"avg_line_length": 44.609053497942384,
"alnum_prop": 0.44031365313653137,
"repo_name": "ChilliWorks/ChilliSource",
"id": "31ae5bff6c89dbdf449e418a5b8a1f05ad89c8f3",
"size": "12476",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Source/ChilliSource/Input/Gesture/GestureSystem.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "9371694"
},
{
"name": "C++",
"bytes": "9942473"
},
{
"name": "Java",
"bytes": "1911615"
},
{
"name": "Makefile",
"bytes": "18869"
},
{
"name": "Objective-C",
"bytes": "210639"
},
{
"name": "Objective-C++",
"bytes": "280471"
},
{
"name": "Python",
"bytes": "53174"
}
],
"symlink_target": ""
} |
package org.immutables.generator;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import org.eclipse.jdt.internal.compiler.apt.model.ElementImpl;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
/**
* Utility that abstracts away hacks to retrieve elements in source order. Currently, Javac returns
* elements in proper source order, but EJC returns elements in alphabetical order.
* <ul>
* <li><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=300408">Bug 300408 -
* TypeElement.getEnclosedElements does not respect source order</a>
* <li><a href="http://bugs.sun.com/view_bug.do?bug_id=6884227">JDK-6884227 : Clarify ordering
* requirements of javax.lang.model.TypeElement.getEnclosedElements</a>
* </ul>
* <p>
* <em>Based on a workaround idea provided by Christian Humer</em>
*/
public final class SourceOrdering {
private SourceOrdering() {}
private interface OrderingProvider {
Ordering<Element> enclosedBy(Element element);
}
private static final OrderingProvider DEFAULT_PROVIDER = new OrderingProvider() {
// it's safe to cast ordering because it handles elements without regards of actual types.
@SuppressWarnings("unchecked")
@Override
public Ordering<Element> enclosedBy(Element element) {
return (Ordering<Element>) Ordering.explicit(element.getEnclosedElements());
}
};
private static final OrderingProvider PROVIDER = createProvider();
// it's safe to cast immutable list of <? extends Element> to a list of <Element>
@SuppressWarnings("unchecked")
public static ImmutableList<Element> getEnclosedElements(Element element) {
return (ImmutableList<Element>) enclosedBy(element).immutableSortedCopy(element.getEnclosedElements());
}
public static Ordering<Element> enclosedBy(Element element) {
return PROVIDER.enclosedBy(element);
}
private static OrderingProvider createProvider() {
try {
return new EclipseCompilerOrderingProvider();
} catch (Throwable ex) {
return DEFAULT_PROVIDER;
}
}
/**
* This inner static class will fail to load if Eclipse compliler classes will not be in
* classpath.
* If annotation processor is executed by Javac compiler in presence of ECJ classes, then
* instanceof checks will fail with fallback to defaults (Javac).
*/
private static class EclipseCompilerOrderingProvider
implements OrderingProvider, Function<Element, Object> {
// Triggers loading of class that may be absent in classpath
static {
ElementImpl.class.getCanonicalName();
}
@Override
public Object apply(Element input) {
return ((ElementImpl) input)._binding;
}
@Override
public Ordering<Element> enclosedBy(Element element) {
if (element instanceof ElementImpl &&
Iterables.all(element.getEnclosedElements(), Predicates.instanceOf(ElementImpl.class))) {
ElementImpl implementation = (ElementImpl) element;
if (implementation._binding instanceof SourceTypeBinding) {
SourceTypeBinding sourceBinding = (SourceTypeBinding) implementation._binding;
return Ordering.natural().onResultOf(
Functions.compose(bindingsToSourceOrder(sourceBinding), this));
}
}
return DEFAULT_PROVIDER.enclosedBy(element);
}
private Function<Object, Integer> bindingsToSourceOrder(SourceTypeBinding sourceBinding) {
IdentityHashMap<Object, Integer> bindings = Maps.newIdentityHashMap();
if (sourceBinding.scope.referenceContext.methods != null) {
for (AbstractMethodDeclaration declaration : sourceBinding.scope.referenceContext.methods) {
bindings.put(declaration.binding, declaration.declarationSourceStart);
}
}
if (sourceBinding.scope.referenceContext.fields != null) {
for (FieldDeclaration declaration : sourceBinding.scope.referenceContext.fields) {
bindings.put(declaration.binding, declaration.declarationSourceStart);
}
}
if (sourceBinding.scope.referenceContext.memberTypes != null) {
for (TypeDeclaration declaration : sourceBinding.scope.referenceContext.memberTypes) {
bindings.put(declaration.binding, declaration.declarationSourceStart);
}
}
return Functions.forMap(bindings);
}
}
/**
* While we have {@link SourceOrdering}, there's still a problem: We have inheritance hierarchy
* and
* we want to have all defined or inherited accessors returned as members of target type, like
* {@link Elements#getAllMembers(TypeElement)}, but we need to have them properly and stably
* sorted.
* This implementation doesn't try to correctly resolve order for accessors inherited from
* different supertypes(interfaces), just something that stable and reasonable wrt source ordering
* without handling complex cases.
* @param elements the elements utility
* @param types the types utility
* @param type the type to traverse
* @return all accessors in source order
*/
public static ImmutableList<ExecutableElement> getAllAccessors(
final Elements elements,
final Types types,
final TypeElement type) {
class CollectedOrdering
extends Ordering<Element> {
class Intratype {
Ordering<String> ordering;
int rank;
}
final Map<String, Intratype> accessorOrderings = Maps.newLinkedHashMap();
final List<TypeElement> linearizedTypes = Lists.newArrayList();
final Predicate<String> accessorNotYetInOrderings =
Predicates.not(Predicates.in(accessorOrderings.keySet()));
CollectedOrdering() {
traverse(type);
traverseObjectForInterface();
}
private void traverseObjectForInterface() {
if (type.getKind() == ElementKind.INTERFACE) {
traverse(elements.getTypeElement(Object.class.getName()));
}
}
void traverse(@Nullable TypeElement element) {
if (element == null) {
return;
}
collectEnclosing(element);
traverse(asTypeElement(element.getSuperclass()));
for (TypeMirror implementedInterface : element.getInterfaces()) {
traverse(asTypeElement(implementedInterface));
}
}
@Nullable
TypeElement asTypeElement(TypeMirror type) {
if (type.getKind() == TypeKind.DECLARED) {
return (TypeElement) ((DeclaredType) type).asElement();
}
return null;
}
void collectEnclosing(TypeElement type) {
List<String> accessors =
FluentIterable.from(SourceOrdering.getEnclosedElements(type))
.filter(IsAccessor.PREDICATE)
.transform(ToSimpleName.FUNCTION)
.filter(accessorNotYetInOrderings)
.toList();
Intratype intratype = new Intratype();
intratype.rank = linearizedTypes.size();
intratype.ordering = Ordering.explicit(accessors);
for (String name : accessors) {
accessorOrderings.put(name, intratype);
}
linearizedTypes.add(type);
}
@Override
public int compare(Element left, Element right) {
String leftKey = ToSimpleName.FUNCTION.apply(left);
String rightKey = ToSimpleName.FUNCTION.apply(right);
Intratype leftIntratype = accessorOrderings.get(leftKey);
Intratype rightIntratype = accessorOrderings.get(rightKey);
if (leftIntratype == null || rightIntratype == null) {
// FIXME figure out why it happens (null)
return Boolean.compare(leftIntratype == null, rightIntratype == null);
}
return leftIntratype == rightIntratype
? leftIntratype.ordering.compare(leftKey, rightKey)
: Integer.compare(leftIntratype.rank, rightIntratype.rank);
}
}
return FluentIterable.from(ElementFilter.methodsIn(elements.getAllMembers(type)))
.filter(IsAccessor.PREDICATE)
.toSortedList(new CollectedOrdering());
}
private enum ToSimpleName implements Function<Element, String> {
FUNCTION;
@Override
public String apply(Element input) {
return input.getSimpleName().toString();
}
}
private enum IsAccessor implements Predicate<Element> {
PREDICATE;
@Override
public boolean apply(Element input) {
if (input.getKind() != ElementKind.METHOD) {
return false;
}
ExecutableElement element = (ExecutableElement) input;
boolean parameterless = element.getParameters().isEmpty();
boolean nonstatic = !element.getModifiers().contains(Modifier.STATIC);
return parameterless && nonstatic;
}
}
}
| {
"content_hash": "c9aee622476a000df3612657c0e34435",
"timestamp": "",
"source": "github",
"line_count": 264,
"max_line_length": 107,
"avg_line_length": 37.28409090909091,
"alnum_prop": 0.7095397744590064,
"repo_name": "impraveen/immutables",
"id": "fe44b8aac99c8a9dfca42f84a2500e8f56449a77",
"size": "10456",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "generator/src/org/immutables/generator/SourceOrdering.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "955837"
}
],
"symlink_target": ""
} |
package org.ovirt.engine.core.dao;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.junit.Assert;
import org.junit.Test;
import org.ovirt.engine.core.common.businessentities.VmDevice;
import org.ovirt.engine.core.common.businessentities.VmDeviceGeneralType;
import org.ovirt.engine.core.common.businessentities.VmDeviceId;
import org.ovirt.engine.core.common.utils.VmDeviceType;
import org.ovirt.engine.core.compat.Guid;
/**
* Unit tests to validate {@link VmDeviceDao}.
*/
public class VmDeviceDaoTest extends BaseGenericDaoTestCase<VmDeviceId, VmDevice, VmDeviceDao> {
private static final Guid EXISTING_VM_ID = new Guid("77296e00-0cad-4e5a-9299-008a7b6f4355");
private static final Guid EXISTING_VM_ID_2 = new Guid("1b85420c-b84c-4f29-997e-0eb674b40b79");
private static final Guid EXISTING_VM_ID_3 = new Guid("77296e00-0cad-4e5a-9299-008a7b6f5002");
private static final Guid EXISTING_DEVICE_ID = new Guid("e14ed6f0-3b12-11e1-b614-63d00126418d");
private static final Guid NON_EXISTING_VM_ID = Guid.newGuid();
private static final int TOTAL_DEVICES = 15;
private static final int TOTAL_DISK_DEVICES_FOR_EXISTING_VM = 5;
private static final int TOTAL_HOST_DEVICES = 3;
private static final int TOTAL_DEVICES_FOR_EXISTING_VM = 8;
@Override
protected VmDeviceId generateNonExistingId() {
return new VmDeviceId(Guid.newGuid(), Guid.newGuid());
}
@Override
protected int getEneitiesTotalCount() {
return TOTAL_DEVICES;
}
@Override
protected VmDevice generateNewEntity() {
return createVmDevice(EXISTING_VM_ID);
}
@Override
protected void updateExistingEntity() {
existingEntity.setAddress("type:'drive', controller:'0', bus:'0', unit:'0'");
existingEntity.setLogicalName("testLogicalName");
}
@Override
protected VmDeviceDao prepareDao() {
return dbFacade.getVmDeviceDao();
}
@Override
protected VmDeviceId getExistingEntityId() {
return (new VmDeviceId(EXISTING_DEVICE_ID, EXISTING_VM_ID));
}
@Test
public void existsForExistingVmDevice() throws Exception {
assertTrue(dao.exists(new VmDeviceId(EXISTING_DEVICE_ID, EXISTING_VM_ID)));
}
@Test
public void existsForNonExistingVmDevice() throws Exception {
assertFalse(dao.exists(new VmDeviceId(Guid.newGuid(), Guid.newGuid())));
}
@Test
public void testGetVmDeviceByVmIdTypeAndDeviceNoFiltering() {
List<VmDevice> devices = dao.getVmDeviceByVmIdTypeAndDevice(EXISTING_VM_ID, VmDeviceGeneralType.DISK, "disk");
assertGetVMDeviceByIdTypeAndDeviceFullResult(devices);
}
@Test
public void testGetVmDeviceByVmIdTypeAndDeviceFilteringSetToFalse() {
List<VmDevice> devices =
dao.getVmDeviceByVmIdTypeAndDevice(EXISTING_VM_ID, VmDeviceGeneralType.DISK, "disk", null, false);
assertGetVMDeviceByIdTypeAndDeviceFullResult(devices);
}
@Test
public void testGetVmDeviceByVmIdTypeAndDeviceFilteringWithPermissions() {
List<VmDevice> devices =
dao.getVmDeviceByVmIdTypeAndDevice(EXISTING_VM_ID,
VmDeviceGeneralType.DISK,
"disk",
PRIVILEGED_USER_ID,
true);
assertGetVMDeviceByIdTypeAndDeviceFullResult(devices);
}
@Test
public void testGetVmDeviceByVmIdTypeAndDeviceFilteringWithoutPermissions() {
List<VmDevice> devices =
dao.getVmDeviceByVmIdTypeAndDevice(EXISTING_VM_ID,
VmDeviceGeneralType.DISK,
"disk",
UNPRIVILEGED_USER_ID,
true);
assertTrue("A user without any permissions should not see any devices", devices.isEmpty());
}
/**
* Asserts all the disk devices are present in a result of {@link VmDeviceDao#getVmDeviceByVmIdTypeAndDevice(Guid, String, String)
* @param devices The result to check
*/
private static void assertGetVMDeviceByIdTypeAndDeviceFullResult(List<VmDevice> devices) {
assertEquals("there should only be " + TOTAL_DISK_DEVICES_FOR_EXISTING_VM + " disks",
TOTAL_DISK_DEVICES_FOR_EXISTING_VM, devices.size());
}
/**
* Asserts all the devices are present in a result of {@link VmDeviceDao#getVmDeviceByVmId(Guid, String, String)
* @param devices The result to check
*/
private static void assertGetVMDeviceByIdResult(List<VmDevice> devices) {
assertEquals("there should only be " + TOTAL_DEVICES_FOR_EXISTING_VM + " devices",
TOTAL_DEVICES_FOR_EXISTING_VM, devices.size());
}
@Test
public void testGetVmDeviceByVmIdTypeAndDeviceFilteringWithPermissionsNoFiltering() {
List<VmDevice> devices =
dao.getVmDeviceByVmIdTypeAndDevice(EXISTING_VM_ID,
VmDeviceGeneralType.DISK,
"disk",
PRIVILEGED_USER_ID,
false);
assertGetVMDeviceByIdTypeAndDeviceFullResult(devices);
}
@Test
public void testGetUnmanagedDeviceByVmId() {
List<VmDevice> devices =
dao.getUnmanagedDevicesByVmId(EXISTING_VM_ID);
assertTrue(devices.isEmpty());
}
@Test
public void testIsBalloonEnabled() {
boolean queryRes = dao.isMemBalloonEnabled(EXISTING_VM_ID);
List<VmDevice> devices =
dao.getVmDeviceByVmIdTypeAndDevice(EXISTING_VM_ID,
VmDeviceGeneralType.BALLOON,
VmDeviceType.MEMBALLOON.getName());
assertTrue((queryRes && !devices.isEmpty()) || (!queryRes && devices.isEmpty()));
}
/**
* Test clearing a device address
* @param result
*/
@Test
public void clearDeviceAddress() {
// before: check we have a device with a non-blank address
VmDevice vmDevice = dao.get(getExistingEntityId());
Assert.assertTrue(StringUtils.isNotBlank(vmDevice.getAddress()));
// clear the address and check its really cleared
dao.clearDeviceAddress(getExistingEntityId().getDeviceId());
Assert.assertTrue(StringUtils.isBlank(dao.get(getExistingEntityId()).getAddress()));
}
@Test
public void testUpdateDeviceRuntimeInfo() {
VmDevice vmDevice = dao.get(getExistingEntityId());
Assert.assertTrue(StringUtils.isNotBlank(vmDevice.getAddress()));
String newAddressValue = "newaddr";
vmDevice.setAddress(newAddressValue);
String newAlias = "newalias";
vmDevice.setAlias(newAlias);
dao.updateRuntimeInfo(vmDevice);
dao.get(getExistingEntityId());
assertEquals(vmDevice.getAddress(), newAddressValue);
assertEquals(vmDevice.getAlias(), newAlias);
}
@Test
public void testUpdateHotPlugDisk() {
VmDevice vmDevice = dao.get(getExistingEntityId());
boolean newPluggedValue = !vmDevice.getIsPlugged();
Assert.assertTrue(StringUtils.isNotBlank(vmDevice.getAddress()));
vmDevice.setIsPlugged(newPluggedValue);
dao.updateHotPlugDisk(vmDevice);
dao.get(getExistingEntityId());
assertEquals(vmDevice.getIsPlugged(), newPluggedValue);
}
@Test
public void testUpdateBootOrder() {
VmDevice vmDevice = dao.get(getExistingEntityId());
int newBootOrderValue = vmDevice.getBootOrder() + 1;
Assert.assertTrue(StringUtils.isNotBlank(vmDevice.getAddress()));
vmDevice.setBootOrder(newBootOrderValue);
dao.updateBootOrder(vmDevice);
dao.get(getExistingEntityId());
assertEquals(vmDevice.getBootOrder(), newBootOrderValue);
}
@Test
public void testUpdateBootOrderInBatch() {
VmDevice vmDevice = dao.get(getExistingEntityId());
int newBootOrderValue = vmDevice.getBootOrder() + 1;
Assert.assertTrue(StringUtils.isNotBlank(vmDevice.getAddress()));
vmDevice.setBootOrder(newBootOrderValue);
dao.updateBootOrderInBatch(Arrays.asList(vmDevice));
dao.get(getExistingEntityId());
assertEquals(vmDevice.getBootOrder(), newBootOrderValue);
}
@Test
public void testExistsVmDeviceByVmIdAndType() {
assertTrue(dao.existsVmDeviceByVmIdAndType(EXISTING_VM_ID, VmDeviceGeneralType.HOSTDEV));
assertFalse(dao.existsVmDeviceByVmIdAndType(NON_EXISTING_VM_ID, VmDeviceGeneralType.HOSTDEV));
}
@Test
public void testGetVmDeviceByType() {
List<VmDevice> devices = dao.getVmDeviceByType(VmDeviceGeneralType.HOSTDEV);
assertEquals("Expected to retrieve " + TOTAL_HOST_DEVICES + " host devices.", TOTAL_HOST_DEVICES, devices.size());
Set<Guid> vmIds = new HashSet<>();
for (VmDevice device : devices) {
vmIds.add(device.getVmId());
}
assertTrue(vmIds.contains(EXISTING_VM_ID));
assertTrue(vmIds.contains(EXISTING_VM_ID_2));
assertTrue(vmIds.contains(EXISTING_VM_ID_3));
}
@Test
public void testRemoveVmDevicesByVmIdAndType() {
dao.removeVmDevicesByVmIdAndType(EXISTING_VM_ID, VmDeviceGeneralType.HOSTDEV);
assertFalse(dao.existsVmDeviceByVmIdAndType(EXISTING_VM_ID, VmDeviceGeneralType.HOSTDEV));
assertTrue(dao.existsVmDeviceByVmIdAndType(EXISTING_VM_ID_2, VmDeviceGeneralType.HOSTDEV));
}
public void testUpdateVmDeviceUsingScsiReservationProperty() {
VmDevice vmDevice = dao.get(getExistingEntityId());
boolean usingScsiReservation = !vmDevice.isUsingScsiReservation();
vmDevice.setUsingScsiReservation(usingScsiReservation);
dao.update(vmDevice);
dao.get(getExistingEntityId());
assertEquals(vmDevice.isUsingScsiReservation(), usingScsiReservation);
}
private VmDevice createVmDevice(Guid vmGuid) {
return new VmDevice(new VmDeviceId(Guid.newGuid(), vmGuid),
VmDeviceGeneralType.DISK,
"floppy",
"type:'drive', controller:'0', bus:'0', unit:'1'",
2,
new HashMap<String, Object>(),
true, false, false, "alias", Collections.singletonMap("prop1", "value1"), null, null);
}
@Test
public void testGetVmDeviceByVmIdFilteringSetToFalse() {
List<VmDevice> devices =
dao.getVmDeviceByVmId(EXISTING_VM_ID);
assertGetVMDeviceByIdResult(devices);
}
@Test
public void testGetVmDeviceByVmIdFilteringWithPermissions() {
List<VmDevice> devices =
dao.getVmDeviceByVmId(EXISTING_VM_ID,
PRIVILEGED_USER_ID,
true);
assertGetVMDeviceByIdResult(devices);
}
@Test
public void testGetVmDeviceByVmIdFilteringWithoutPermissions() {
List<VmDevice> devices =
dao.getVmDeviceByVmId(EXISTING_VM_ID,
UNPRIVILEGED_USER_ID,
true);
assertTrue("A user without any permissions should not see any devices", devices.isEmpty());
}
}
| {
"content_hash": "f324638853f45bae3f0fad286f57827d",
"timestamp": "",
"source": "github",
"line_count": 292,
"max_line_length": 134,
"avg_line_length": 39.178082191780824,
"alnum_prop": 0.6715034965034965,
"repo_name": "walteryang47/ovirt-engine",
"id": "061d84b119576eb3223fa2ff07c3e3fff0eeb65c",
"size": "11440",
"binary": false,
"copies": "6",
"ref": "refs/heads/eayunos-4.2",
"path": "backend/manager/modules/dal/src/test/java/org/ovirt/engine/core/dao/VmDeviceDaoTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "68312"
},
{
"name": "HTML",
"bytes": "16218"
},
{
"name": "Java",
"bytes": "35067647"
},
{
"name": "JavaScript",
"bytes": "69948"
},
{
"name": "Makefile",
"bytes": "24723"
},
{
"name": "PLSQL",
"bytes": "533"
},
{
"name": "PLpgSQL",
"bytes": "796728"
},
{
"name": "Python",
"bytes": "970860"
},
{
"name": "Roff",
"bytes": "10764"
},
{
"name": "Shell",
"bytes": "163853"
},
{
"name": "XSLT",
"bytes": "54683"
}
],
"symlink_target": ""
} |
// Copyright 2012 The Obvious Corporation.
/*
* This simply fetches the right version of phantom for the current platform.
*/
'use strict'
var requestProgress = require('request-progress')
var progress = require('progress')
var AdmZip = require('adm-zip')
var cp = require('child_process')
var fs = require('fs')
var helper = require('./lib/phantomjs')
var kew = require('kew')
var mkdirp = require('mkdirp')
var ncp = require('ncp')
var npmconf = require('npmconf')
var path = require('path')
var request = require('request')
var rimraf = require('rimraf')
var urlLib = require('url')
var util = require('util')
var which = require('which')
// allow to specify a completely custom download url
var customDownloadUrl = process.env.PHANTOMJS2_DOWNLOAD_URL || false
var url = process.platform === 'win32' ? 'https://github.com/gskachkov/phantomjs/releases/download/' : 'https://github.com/bprodoehl/phantomjs/releases/download/'
var systemPrefix = process.platform === 'win32' ? '-x86' : ''
var cdnUrl = process.env.PHANTOMJS_CDNURL || url
var phantomVersion = process.env.PHANTOMJS2_VERSION || helper.version
var downloadUrl = cdnUrl + phantomVersion + systemPrefix + '/phantomjs-' + phantomVersion + '-'
var originalPath = process.env.PATH
// If the process exits without going through exit(), then we did not complete.
var validExit = false
process.on('exit', function () {
if (!validExit) {
console.log('Install exited unexpectedly')
exit(1)
}
})
// NPM adds bin directories to the path, which will cause `which` to find the
// bin for this package not the actual phantomjs bin. Also help out people who
// put ./bin on their path
process.env.PATH = helper.cleanPath(originalPath)
var libPath = path.join(__dirname, 'lib')
var pkgPath = path.join(libPath, 'phantom')
var phantomPath = null
var tmpPath = null
// If the user manually installed PhantomJS, we want
// to use the existing version.
//
// Do not re-use a manually-installed PhantomJS with
// a different version.
//
// Do not re-use an npm-installed PhantomJS, because
// that can lead to weird circular dependencies between
// local versions and global versions.
// https://github.com/Obvious/phantomjs/issues/85
// https://github.com/Medium/phantomjs/pull/184
var whichDeferred = kew.defer()
which('phantomjs', whichDeferred.makeNodeResolver())
whichDeferred.promise
.then(function (result) {
phantomPath = result
// Horrible hack to avoid problems during global install. We check to see if
// the file `which` found is our own bin script.
if (phantomPath.indexOf(path.join('npm', 'phantomjs')) !== -1) {
console.log('Looks like an `npm install -g` on windows; unable to check for already installed version.')
throw new Error('Global install')
}
var contents = fs.readFileSync(phantomPath, 'utf8')
if (/NPM_INSTALL_MARKER/.test(contents)) {
console.log('Looks like an `npm install -g`; unable to check for already installed version.')
throw new Error('Global install')
} else {
var checkVersionDeferred = kew.defer()
cp.execFile(phantomPath, ['--version'], checkVersionDeferred.makeNodeResolver())
return checkVersionDeferred.promise
}
})
.then(function (stdout) {
var version = stdout.trim()
if (phantomVersion == version) {
writeLocationFile(phantomPath);
console.log('PhantomJS is already installed at', phantomPath + '.')
exit(0)
} else {
console.log('PhantomJS detected, but wrong version', stdout.trim(), '@', phantomPath + '.')
throw new Error('Wrong version')
}
})
.fail(function (err) {
// Trying to use a local file failed, so initiate download and install
// steps instead.
var npmconfDeferred = kew.defer()
npmconf.load(npmconfDeferred.makeNodeResolver())
return npmconfDeferred.promise
})
.then(function (conf) {
tmpPath = findSuitableTempDirectory(conf)
// Can't use a global version so start a download.
if (customDownloadUrl) {
downloadUrl = customDownloadUrl
} else if (process.platform === 'linux' && process.arch === 'x64') {
downloadUrl += 'u1404-x86_64.zip'
} else if (process.platform === 'darwin' || process.platform === 'openbsd' || process.platform === 'freebsd') {
downloadUrl += 'macosx.zip'
} else if (process.platform === 'win32') {
downloadUrl += 'win-x86.zip'
} else {
console.error('Unexpected platform or architecture:', process.platform, process.arch)
exit(1)
}
var fileName = downloadUrl.split('/').pop()
var downloadedFile = path.join(tmpPath, fileName)
// Start the install.
if (!fs.existsSync(downloadedFile)) {
console.log('Downloading', downloadUrl)
console.log('Saving to', downloadedFile)
return requestBinary(getRequestOptions(conf), downloadedFile)
} else {
console.log('Download already available at', downloadedFile)
return downloadedFile
}
})
.then(function (downloadedFile) {
return extractDownload(downloadedFile)
})
.then(function (extractedPath) {
return copyIntoPlace(extractedPath, pkgPath)
})
.then(function () {
var location = process.platform === 'win32' ?
path.join(pkgPath, 'phantomjs.exe') :
path.join(pkgPath, 'bin' ,'phantomjs')
var relativeLocation = path.relative(libPath, location)
writeLocationFile(relativeLocation)
// Ensure executable is executable by all users
fs.chmodSync(location, '755')
console.log('Done. Phantomjs binary available at', location)
exit(0)
})
.fail(function (err) {
console.error('Phantom installation failed', err, err.stack)
exit(1)
})
function writeLocationFile(location) {
console.log('Writing location.js file')
if (process.platform === 'win32') {
location = location.replace(/\\/g, '\\\\')
}
fs.writeFileSync(path.join(libPath, 'location.js'),
'module.exports.location = "' + location + '"')
}
function exit(code) {
validExit = true
process.env.PATH = originalPath
process.exit(code || 0)
}
function findSuitableTempDirectory(npmConf) {
var now = Date.now()
var candidateTmpDirs = [
process.env.TMPDIR || process.env.TEMP || npmConf.get('tmp'),
'/tmp',
path.join(process.cwd(), 'tmp')
]
for (var i = 0; i < candidateTmpDirs.length; i++) {
var candidatePath = path.join(candidateTmpDirs[i], 'phantomjs')
try {
mkdirp.sync(candidatePath, '0777')
// Make double sure we have 0777 permissions; some operating systems
// default umask does not allow write by default.
fs.chmodSync(candidatePath, '0777')
var testFile = path.join(candidatePath, now + '.tmp')
fs.writeFileSync(testFile, 'test')
fs.unlinkSync(testFile)
return candidatePath
} catch (e) {
console.log(candidatePath, 'is not writable:', e.message)
}
}
console.error('Can not find a writable tmp directory, please report issue ' +
'on https://github.com/Obvious/phantomjs/issues/59 with as much ' +
'information as possible.')
exit(1)
}
function getRequestOptions(conf) {
var options = {
uri: downloadUrl,
encoding: null, // Get response as a buffer
followRedirect: true, // The default download path redirects to a CDN URL.
headers: {},
strictSSL: conf.get('strict-ssl')
}
var proxyUrl = conf.get('https-proxy') || conf.get('http-proxy') || conf.get('proxy')
if (proxyUrl) {
// Print using proxy
var proxy = urlLib.parse(proxyUrl)
if (proxy.auth) {
// Mask password
proxy.auth = proxy.auth.replace(/:.*$/, ':******')
}
console.log('Using proxy ' + urlLib.format(proxy))
// Enable proxy
options.proxy = proxyUrl
// If going through proxy, spoof the User-Agent, since may commerical proxies block blank or unknown agents in headers
options.headers['User-Agent'] = 'curl/7.21.4 (universal-apple-darwin11.0) libcurl/7.21.4 OpenSSL/0.9.8r zlib/1.2.5'
}
return options
}
function requestBinary(requestOptions, filePath) {
var deferred = kew.defer()
var count = 0
var notifiedCount = 0
var writePath = filePath + '-download-' + Date.now()
var outFile = fs.openSync(writePath, 'w')
console.log('Receiving...')
var bar = null
requestProgress(request(requestOptions, function (error, response, body) {
console.log('');
if (!error && response.statusCode === 200) {
fs.writeFileSync(writePath, body)
console.log('Received ' + Math.floor(body.length / 1024) + 'K total.')
fs.renameSync(writePath, filePath)
deferred.resolve(filePath)
} else if (response) {
console.error('Error requesting archive.\n' +
'Status: ' + response.statusCode + '\n' +
'Request options: ' + JSON.stringify(requestOptions, null, 2) + '\n' +
'Response headers: ' + JSON.stringify(response.headers, null, 2) + '\n' +
'Make sure your network and proxy settings are correct.\n\n' +
'If you continue to have issues, please report this full log at ' +
'https://github.com/Medium/phantomjs')
exit(1)
} else if (error && error.stack && error.stack.indexOf('SELF_SIGNED_CERT_IN_CHAIN') != -1) {
console.error('Error making request, SELF_SIGNED_CERT_IN_CHAIN. Please read https://github.com/Medium/phantomjs#i-am-behind-a-corporate-proxy-that-uses-self-signed-ssl-certificates-to-intercept-encrypted-traffic')
exit(1)
} else if (error) {
console.error('Error making request.\n' + error.stack + '\n\n' +
'Please report this full log at https://github.com/Medium/phantomjs')
exit(1)
} else {
console.error('Something unexpected happened, please report this full ' +
'log at https://github.com/Medium/phantomjs')
exit(1)
}
})).on('progress', function (state) {
if (!bar) {
bar = new progress(' [:bar] :percent :etas', {total: state.total, width: 40})
}
bar.curr = state.received
bar.tick(0)
})
return deferred.promise
}
function extractDownload(filePath) {
var deferred = kew.defer()
// extract to a unique directory in case multiple processes are
// installing and extracting at once
var extractedPath = filePath + '-extract-' + Date.now()
var options = {cwd: extractedPath}
mkdirp.sync(extractedPath, '0777')
// Make double sure we have 0777 permissions; some operating systems
// default umask does not allow write by default.
fs.chmodSync(extractedPath, '0777')
if (filePath.substr(-4) === '.zip') {
console.log('Extracting zip contents')
try {
var zip = new AdmZip(filePath)
zip.extractAllTo(extractedPath, true)
deferred.resolve(extractedPath)
} catch (err) {
console.error('Error extracting zip')
deferred.reject(err)
}
} else {
console.log('Extracting tar contents (via spawned process)')
cp.execFile('tar', ['jxf', filePath], options, function (err, stdout, stderr) {
if (err) {
console.error('Error extracting archive')
deferred.reject(err)
} else {
deferred.resolve(extractedPath)
}
})
}
return deferred.promise
}
function copyIntoPlace(extractedPath, targetPath) {
console.log('Removing', targetPath)
return kew.nfcall(rimraf, targetPath).then(function () {
// Look for the extracted directory, so we can rename it.
var files = fs.readdirSync(extractedPath)
for (var i = 0; i < files.length; i++) {
var file = path.join(extractedPath, files[i])
if (fs.statSync(file).isDirectory() && file.indexOf(phantomVersion) != -1) {
console.log('Copying extracted folder', file, '->', targetPath)
return kew.nfcall(ncp, file, targetPath)
}
}
console.log('Could not find extracted file', files)
throw new Error('Could not find extracted file')
})
.then(function () {
// Cleanup extracted directory after it's been copied
console.log('Removing', extractedPath)
return kew.nfcall(rimraf, extractedPath).fail(function (e) {
// Swallow the error quietly.
console.warn(e)
console.warn('Unable to remove temporary files at "' + extractedPath +
'", see https://github.com/Obvious/phantomjs/issues/108 for details.')
})
})
}
| {
"content_hash": "b1b924c2aeb3fc63cc1b7be3b57c1be7",
"timestamp": "",
"source": "github",
"line_count": 360,
"max_line_length": 219,
"avg_line_length": 34.12222222222222,
"alnum_prop": 0.6663953109736243,
"repo_name": "diztinct-tim/BeautyBridge",
"id": "01a3f43cf413c1ba5713607dbb78b8ae5d17fd1c",
"size": "12285",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "node_modules/karma-phantomjs2-launcher/node_modules/phantomjs2-ext/install.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "432"
},
{
"name": "CSS",
"bytes": "1996798"
},
{
"name": "CoffeeScript",
"bytes": "36602"
},
{
"name": "HTML",
"bytes": "1316032"
},
{
"name": "JavaScript",
"bytes": "6730438"
},
{
"name": "LiveScript",
"bytes": "5561"
},
{
"name": "Makefile",
"bytes": "1424"
},
{
"name": "PHP",
"bytes": "93714"
},
{
"name": "Ruby",
"bytes": "1947"
},
{
"name": "Shell",
"bytes": "3494"
}
],
"symlink_target": ""
} |
<?php
namespace Zend\Authentication\Adapter\Exception;
use Zend\Authentication\Exception\ExceptionInterface as Exception;
interface ExceptionInterface extends Exception
{
}
| {
"content_hash": "3bd924d97eb7a7aeac1af96c723fee51",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 66,
"avg_line_length": 18.7,
"alnum_prop": 0.7914438502673797,
"repo_name": "wp-plugins/double-click",
"id": "22a0365a98742b9c30da3525044c4772cf9e0ef1",
"size": "495",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "vendor/zendframework/zendframework/library/Zend/Authentication/Adapter/Exception/ExceptionInterface.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "13825"
},
{
"name": "PHP",
"bytes": "19905"
},
{
"name": "Shell",
"bytes": "2037"
}
],
"symlink_target": ""
} |
#include "hfs_fs.h"
#include "btree.h"
/*
* hfs_lookup()
*/
static struct dentry *hfs_lookup(struct inode *dir, struct dentry *dentry,
struct nameidata *nd)
{
hfs_cat_rec rec;
struct hfs_find_data fd;
struct inode *inode = NULL;
int res;
hfs_find_init(HFS_SB(dir->i_sb)->cat_tree, &fd);
hfs_cat_build_key(dir->i_sb, fd.search_key, dir->i_ino, &dentry->d_name);
res = hfs_brec_read(&fd, &rec, sizeof(rec));
if (res) {
hfs_find_exit(&fd);
if (res == -ENOENT) {
/* No such entry */
inode = NULL;
goto done;
}
return ERR_PTR(res);
}
inode = hfs_iget(dir->i_sb, &fd.search_key->cat, &rec);
hfs_find_exit(&fd);
if (!inode)
return ERR_PTR(-EACCES);
done:
d_add(dentry, inode);
return NULL;
}
/*
* hfs_readdir
*/
static int hfs_readdir(struct file *filp, void *dirent, filldir_t filldir)
{
struct inode *inode = filp->f_path.dentry->d_inode;
struct super_block *sb = inode->i_sb;
int len, err;
char strbuf[HFS_MAX_NAMELEN];
union hfs_cat_rec entry;
struct hfs_find_data fd;
struct hfs_readdir_data *rd;
u16 type;
if (filp->f_pos >= inode->i_size)
return 0;
hfs_find_init(HFS_SB(sb)->cat_tree, &fd);
hfs_cat_build_key(sb, fd.search_key, inode->i_ino, NULL);
err = hfs_brec_find(&fd);
if (err)
goto out;
switch ((u32)filp->f_pos) {
case 0:
/* This is completely artificial... */
if (filldir(dirent, ".", 1, 0, inode->i_ino, DT_DIR))
goto out;
filp->f_pos++;
/* fall through */
case 1:
if (fd.entrylength > sizeof(entry) || fd.entrylength < 0) {
err = -EIO;
goto out;
}
hfs_bnode_read(fd.bnode, &entry, fd.entryoffset, fd.entrylength);
if (entry.type != HFS_CDR_THD) {
printk(KERN_ERR "hfs: bad catalog folder thread\n");
err = -EIO;
goto out;
}
//if (fd.entrylength < HFS_MIN_THREAD_SZ) {
// printk(KERN_ERR "hfs: truncated catalog thread\n");
// err = -EIO;
// goto out;
//}
if (filldir(dirent, "..", 2, 1,
be32_to_cpu(entry.thread.ParID), DT_DIR))
goto out;
filp->f_pos++;
/* fall through */
default:
if (filp->f_pos >= inode->i_size)
goto out;
err = hfs_brec_goto(&fd, filp->f_pos - 1);
if (err)
goto out;
}
for (;;) {
if (be32_to_cpu(fd.key->cat.ParID) != inode->i_ino) {
printk(KERN_ERR "hfs: walked past end of dir\n");
err = -EIO;
goto out;
}
if (fd.entrylength > sizeof(entry) || fd.entrylength < 0) {
err = -EIO;
goto out;
}
hfs_bnode_read(fd.bnode, &entry, fd.entryoffset, fd.entrylength);
type = entry.type;
len = hfs_mac2asc(sb, strbuf, &fd.key->cat.CName);
if (type == HFS_CDR_DIR) {
if (fd.entrylength < sizeof(struct hfs_cat_dir)) {
printk(KERN_ERR "hfs: small dir entry\n");
err = -EIO;
goto out;
}
if (filldir(dirent, strbuf, len, filp->f_pos,
be32_to_cpu(entry.dir.DirID), DT_DIR))
break;
} else if (type == HFS_CDR_FIL) {
if (fd.entrylength < sizeof(struct hfs_cat_file)) {
printk(KERN_ERR "hfs: small file entry\n");
err = -EIO;
goto out;
}
if (filldir(dirent, strbuf, len, filp->f_pos,
be32_to_cpu(entry.file.FlNum), DT_REG))
break;
} else {
printk(KERN_ERR "hfs: bad catalog entry type %d\n", type);
err = -EIO;
goto out;
}
filp->f_pos++;
if (filp->f_pos >= inode->i_size)
goto out;
err = hfs_brec_goto(&fd, 1);
if (err)
goto out;
}
rd = filp->private_data;
if (!rd) {
rd = kmalloc(sizeof(struct hfs_readdir_data), GFP_KERNEL);
if (!rd) {
err = -ENOMEM;
goto out;
}
filp->private_data = rd;
rd->file = filp;
list_add(&rd->list, &HFS_I(inode)->open_dir_list);
}
memcpy(&rd->key, &fd.key, sizeof(struct hfs_cat_key));
out:
hfs_find_exit(&fd);
return err;
}
static int hfs_dir_release(struct inode *inode, struct file *file)
{
struct hfs_readdir_data *rd = file->private_data;
if (rd) {
list_del(&rd->list);
kfree(rd);
}
return 0;
}
/*
* hfs_create()
*
* This is the create() entry in the inode_operations structure for
* regular HFS directories. The purpose is to create a new file in
* a directory and return a corresponding inode, given the inode for
* the directory and the name (and its length) of the new file.
*/
static int hfs_create(struct inode *dir, struct dentry *dentry, umode_t mode,
struct nameidata *nd)
{
struct inode *inode;
int res;
inode = hfs_new_inode(dir, &dentry->d_name, mode);
if (!inode)
return -ENOSPC;
res = hfs_cat_create(inode->i_ino, dir, &dentry->d_name, inode);
if (res) {
clear_nlink(inode);
hfs_delete_inode(inode);
iput(inode);
return res;
}
d_instantiate(dentry, inode);
mark_inode_dirty(inode);
return 0;
}
/*
* hfs_mkdir()
*
* This is the mkdir() entry in the inode_operations structure for
* regular HFS directories. The purpose is to create a new directory
* in a directory, given the inode for the parent directory and the
* name (and its length) of the new directory.
*/
static int hfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
{
struct inode *inode;
int res;
inode = hfs_new_inode(dir, &dentry->d_name, S_IFDIR | mode);
if (!inode)
return -ENOSPC;
res = hfs_cat_create(inode->i_ino, dir, &dentry->d_name, inode);
if (res) {
clear_nlink(inode);
hfs_delete_inode(inode);
iput(inode);
return res;
}
d_instantiate(dentry, inode);
mark_inode_dirty(inode);
return 0;
}
/*
* hfs_remove()
*
* This serves as both unlink() and rmdir() in the inode_operations
* structure for regular HFS directories. The purpose is to delete
* an existing child, given the inode for the parent directory and
* the name (and its length) of the existing directory.
*
* HFS does not have hardlinks, so both rmdir and unlink set the
* link count to 0. The only difference is the emptiness check.
*/
static int hfs_remove(struct inode *dir, struct dentry *dentry)
{
struct inode *inode = dentry->d_inode;
int res;
if (S_ISDIR(inode->i_mode) && inode->i_size != 2)
return -ENOTEMPTY;
res = hfs_cat_delete(inode->i_ino, dir, &dentry->d_name);
if (res)
return res;
clear_nlink(inode);
inode->i_ctime = CURRENT_TIME_SEC;
hfs_delete_inode(inode);
mark_inode_dirty(inode);
return 0;
}
/*
* hfs_rename()
*
* This is the rename() entry in the inode_operations structure for
* regular HFS directories. The purpose is to rename an existing
* file or directory, given the inode for the current directory and
* the name (and its length) of the existing file/directory and the
* inode for the new directory and the name (and its length) of the
* new file/directory.
* XXX: how do you handle must_be dir?
*/
static int hfs_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
int res;
/* Unlink destination if it already exists */
if (new_dentry->d_inode) {
res = hfs_remove(new_dir, new_dentry);
if (res)
return res;
}
res = hfs_cat_move(old_dentry->d_inode->i_ino,
old_dir, &old_dentry->d_name,
new_dir, &new_dentry->d_name);
if (!res)
hfs_cat_build_key(old_dir->i_sb,
(btree_key *)&HFS_I(old_dentry->d_inode)->cat_key,
new_dir->i_ino, &new_dentry->d_name);
return res;
}
const struct file_operations hfs_dir_operations = {
.read = generic_read_dir,
.readdir = hfs_readdir,
.llseek = generic_file_llseek,
.release = hfs_dir_release,
};
const struct inode_operations hfs_dir_inode_operations = {
.create = hfs_create,
.lookup = hfs_lookup,
.unlink = hfs_remove,
.mkdir = hfs_mkdir,
.rmdir = hfs_remove,
.rename = hfs_rename,
.setattr = hfs_inode_setattr,
};
| {
"content_hash": "b7282cb297c7a8bdd826974268ec0111",
"timestamp": "",
"source": "github",
"line_count": 305,
"max_line_length": 77,
"avg_line_length": 24.708196721311474,
"alnum_prop": 0.6403927813163482,
"repo_name": "wilseypa/odroidNetworking",
"id": "62fc14ea4b7387549d2f7017345070864a0d182d",
"size": "7943",
"binary": false,
"copies": "4930",
"ref": "refs/heads/master",
"path": "linux/fs/hfs/dir.c",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "4528"
},
{
"name": "Assembly",
"bytes": "8990744"
},
{
"name": "Awk",
"bytes": "22062"
},
{
"name": "C",
"bytes": "415046807"
},
{
"name": "C++",
"bytes": "5249015"
},
{
"name": "Erlang",
"bytes": "198341"
},
{
"name": "Groovy",
"bytes": "130"
},
{
"name": "JavaScript",
"bytes": "1816659"
},
{
"name": "Objective-C",
"bytes": "1375494"
},
{
"name": "Objective-C++",
"bytes": "10878"
},
{
"name": "PHP",
"bytes": "17120"
},
{
"name": "Perl",
"bytes": "6383015"
},
{
"name": "Python",
"bytes": "930668"
},
{
"name": "R",
"bytes": "98681"
},
{
"name": "Ruby",
"bytes": "9400"
},
{
"name": "Scala",
"bytes": "12158"
},
{
"name": "Scilab",
"bytes": "21433"
},
{
"name": "Shell",
"bytes": "2451055"
},
{
"name": "TeX",
"bytes": "51371"
},
{
"name": "UnrealScript",
"bytes": "20838"
},
{
"name": "VimL",
"bytes": "1355"
},
{
"name": "XSLT",
"bytes": "3937"
}
],
"symlink_target": ""
} |
id: tags-and-attributes
title: Tags and Attributes
permalink: tags-and-attributes.html
prev: component-specs.html
next: events.html
---
## Supported Tags
React attempts to support all common elements. If you need an element that isn't listed here, please file an issue.
### HTML Elements
The following HTML elements are supported:
```
a abbr address area article aside audio b base bdi bdo big blockquote body br
button canvas caption cite code col colgroup data datalist dd del details dfn
dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5
h6 head header hr html i iframe img input ins kbd keygen label legend li link
main map mark menu menuitem meta meter nav noscript object ol optgroup option
output p param picture pre progress q rp rt ruby s samp script section select
small source span strong style sub summary sup table tbody td textarea tfoot th
thead time title tr track u ul var video wbr
```
### SVG elements
The following SVG elements are supported:
```
circle clipPath defs ellipse g line linearGradient mask path pattern polygon polyline
radialGradient rect stop svg text tspan
```
You may also be interested in [react-art](https://github.com/facebook/react-art), a drawing library for React that can render to Canvas, SVG, or VML (for IE8).
## Supported Attributes
React supports all `data-*` and `aria-*` attributes as well as every attribute in the following lists.
> Note:
>
> All attributes are camel-cased and the attributes `class` and `for` are `className` and `htmlFor`, respectively, to match the DOM API specification.
For a list of events, see [Supported Events](/react/docs/events.html).
### HTML Attributes
These standard attributes are supported:
```
accept acceptCharset accessKey action allowFullScreen allowTransparency alt
async autoComplete autoFocus autoPlay cellPadding cellSpacing charSet checked
classID className colSpan cols content contentEditable contextMenu controls
coords crossOrigin data dateTime defer dir disabled download draggable encType
form formAction formEncType formMethod formNoValidate formTarget frameBorder
headers height hidden high href hrefLang htmlFor httpEquiv icon id label lang
list loop low manifest marginHeight marginWidth max maxLength media mediaGroup
method min multiple muted name noValidate open optimum pattern placeholder
poster preload radioGroup readOnly rel required role rowSpan rows sandbox scope
scoped scrolling seamless selected shape size sizes span spellCheck src srcDoc
srcSet start step style tabIndex target title type useMap value width wmode
```
In addition, the following non-standard attributes are supported:
- `autoCapitalize autoCorrect` for Mobile Safari.
- `property` for [Open Graph](http://ogp.me/) meta tags.
- `itemProp itemScope itemType itemRef itemID` for [HTML5 microdata](http://schema.org/docs/gs.html).
- `unselectable` for Internet Explorer.
There is also the React-specific attribute `dangerouslySetInnerHTML` ([more here](/react/docs/special-non-dom-attributes.html)), used for directly inserting HTML strings into a component.
### SVG Attributes
```
clipPath cx cy d dx dy fill fillOpacity fontFamily fontSize fx fy
gradientTransform gradientUnits markerEnd markerMid markerStart offset opacity
patternContentUnits patternUnits points preserveAspectRatio r rx ry
spreadMethod stopColor stopOpacity stroke strokeDasharray strokeLinecap
strokeOpacity strokeWidth textAnchor transform version viewBox x1 x2 x y1 y2 y
```
| {
"content_hash": "126ce9eb573e8902223b25f2be28f12d",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 187,
"avg_line_length": 41.476190476190474,
"alnum_prop": 0.8062571756601608,
"repo_name": "zenlambda/react",
"id": "4fef3b1368ca12e84b7b31bdc2c6cd7c33950a69",
"size": "3488",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "docs/docs/ref-04-tags-and-attributes.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "1625"
},
{
"name": "CoffeeScript",
"bytes": "11089"
},
{
"name": "HTML",
"bytes": "14894"
},
{
"name": "JavaScript",
"bytes": "1490052"
},
{
"name": "PHP",
"bytes": "1945"
},
{
"name": "Ruby",
"bytes": "851"
},
{
"name": "Shell",
"bytes": "416"
},
{
"name": "TypeScript",
"bytes": "14251"
}
],
"symlink_target": ""
} |
<?php
use Foolz\SphinxQL\Drivers\ConnectionInterface;
use Foolz\SphinxQL\Expression;
use Foolz\SphinxQL\Tests\TestUtil;
class ConnectionTest extends PHPUnit_Framework_TestCase
{
/**
* @var ConnectionInterface
*/
private $connection = null;
public function setUp()
{
$this->connection = TestUtil::getConnectionDriver();
$this->connection->setParams(array('host' => '127.0.0.1', 'port' => 9307));
$this->connection->silenceConnectionWarning(false);
}
public function tearDown()
{
$this->connection = null;
}
public function test()
{
TestUtil::getConnectionDriver();
}
public function testGetParams()
{
$this->assertSame(
array('host' => '127.0.0.1', 'port' => 9307, 'socket' => null),
$this->connection->getParams()
);
// create a new connection and get info
$this->connection->setParams(array('host' => '127.0.0.2'));
$this->connection->setParam('port', 9308);
$this->assertSame(
array('host' => '127.0.0.2', 'port' => 9308, 'socket' => null),
$this->connection->getParams()
);
$this->connection->setParam('host', 'localhost');
$this->assertSame(
array('host' => '127.0.0.1', 'port' => 9308, 'socket' => null),
$this->connection->getParams()
);
// create a unix socket connection with host param
$this->connection->setParam('host', 'unix:/var/run/sphinx.sock');
$this->assertSame(
array('host' => null, 'port' => 9308, 'socket' => '/var/run/sphinx.sock'),
$this->connection->getParams()
);
// create unix socket connection with socket param
$this->connection->setParam('host', '127.0.0.1');
$this->connection->setParam('socket', '/var/run/sphinx.sock');
$this->assertSame(
array('host' => null, 'port' => 9308, 'socket' => '/var/run/sphinx.sock'),
$this->connection->getParams()
);
}
public function testGetConnectionParams()
{
// verify that (deprecated) getConnectionParams continues to work
$this->assertSame(array('host' => '127.0.0.1', 'port' => 9307, 'socket' => null), $this->connection->getParams());
// create a new connection and get info
$this->connection->setParams(array('host' => '127.0.0.1', 'port' => 9308));
$this->assertSame(array('host' => '127.0.0.1', 'port' => 9308, 'socket' => null), $this->connection->getParams());
}
public function testGetConnection()
{
$this->connection->connect();
$this->assertNotNull($this->connection->getConnection());
}
/**
* @expectedException Foolz\SphinxQL\Exception\ConnectionException
*/
public function testGetConnectionThrowsException()
{
$this->connection->getConnection();
}
public function testConnect()
{
$this->connection->connect();
$this->connection->setParam('options', array(MYSQLI_OPT_CONNECT_TIMEOUT => 1));
$this->connection->connect();
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
*/
public function testConnectThrowsPHPException()
{
$this->connection->setParam('port', 9308);
$this->connection->connect();
}
/**
* @expectedException Foolz\SphinxQL\Exception\ConnectionException
*/
public function testConnectThrowsException()
{
$this->connection->setParam('port', 9308);
$this->connection->silenceConnectionWarning(true);
$this->connection->connect();
}
public function testPing()
{
$this->connection->connect();
$this->assertTrue($this->connection->ping());
}
/**
* @expectedException Foolz\SphinxQL\Exception\ConnectionException
*/
public function testClose()
{
$encoding = mb_internal_encoding();
$this->connection->connect();
if (method_exists($this->connection, 'getInternalEncoding')) {
$this->assertEquals($encoding, $this->connection->getInternalEncoding());
$this->assertEquals('UTF-8', mb_internal_encoding());
}
$this->connection->close();
$this->assertEquals($encoding, mb_internal_encoding());
$this->connection->getConnection();
}
public function testQuery()
{
$this->connection->connect();
$this->assertSame(array(
array('Variable_name' => 'total', 'Value' => '0'),
array('Variable_name' => 'total_found', 'Value' => '0'),
array('Variable_name' => 'time', 'Value' => '0.000'),
), $this->connection->query('SHOW META')->getStored());
}
public function testMultiQuery()
{
$this->connection->connect();
$query = $this->connection->multiQuery(array('SHOW META'));
$this->assertSame(array(
array('Variable_name' => 'total', 'Value' => '0'),
array('Variable_name' => 'total_found', 'Value' => '0'),
array('Variable_name' => 'time', 'Value' => '0.000'),
), $query->getNext()->fetchAllAssoc());
}
/**
* @expectedException Foolz\SphinxQL\Exception\SphinxQLException
* @expectedExceptionMessage The Queue is empty.
*/
public function testEmptyMultiQuery()
{
$this->connection->connect();
$this->connection->multiQuery(array());
}
/**
* @expectedException Foolz\SphinxQL\Exception\DatabaseException
*/
public function testMultiQueryThrowsException()
{
$this->connection->multiQuery(array('SHOW METAL'));
}
/**
* @expectedException Foolz\SphinxQL\Exception\DatabaseException
*/
public function testQueryThrowsException()
{
$this->connection->query('SHOW METAL');
}
public function testEscape()
{
$result = $this->connection->escape('\' "" \'\' ');
$this->assertEquals('\'\\\' \\"\\" \\\'\\\' \'', $result);
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
*/
public function testEscapeThrowsException()
{
// or we get the wrong error popping up
$this->connection->setParam('port', 9308);
$this->connection->connect();
$this->connection->escape('\' "" \'\' ');
}
public function testQuoteIdentifier()
{
// test *
$this->assertEquals('*', $this->connection->quoteIdentifier('*'));
// test a normal string
$this->assertEquals('`foo`.`bar`', $this->connection->quoteIdentifier('foo.bar'));
// test a SphinxQLExpression
$this->assertEquals('foo.bar', $this->connection->quoteIdentifier(new Expression('foo.bar')));
}
public function testQuoteIdentifierArr()
{
$this->assertSame(
array('*', '`foo`.`bar`', 'foo.bar'),
$this->connection->quoteIdentifierArr(array('*', 'foo.bar', new Expression('foo.bar')))
);
}
public function testQuote()
{
$this->connection->connect();
$this->assertEquals('null', $this->connection->quote(null));
$this->assertEquals("'1'", $this->connection->quote(true));
$this->assertEquals("'0'", $this->connection->quote(false));
$this->assertEquals("fo'o'bar", $this->connection->quote(new Expression("fo'o'bar")));
$this->assertEquals("123", $this->connection->quote(123));
$this->assertEquals("12.3", $this->connection->quote(12.3));
$this->assertEquals("'12.3'", $this->connection->quote('12.3'));
$this->assertEquals("'12'", $this->connection->quote('12'));
}
public function testQuoteArr()
{
$this->connection->connect();
$this->assertEquals(
array('null', "'1'", "'0'", "fo'o'bar", "123", "12.3", "'12.3'", "'12'"),
$this->connection->quoteArr(array(null, true, false, new Expression("fo'o'bar"), 123, 12.3, '12.3', '12'))
);
}
}
| {
"content_hash": "e00e2537f04c9efc7522f51f0d46cd48",
"timestamp": "",
"source": "github",
"line_count": 247,
"max_line_length": 122,
"avg_line_length": 32.56275303643725,
"alnum_prop": 0.5744125326370757,
"repo_name": "Full-Text-Search-System/IndexingModule",
"id": "8630f44c653b8a93a32fe9d97abf9f62311a908b",
"size": "8043",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "workspace/demo/vendor/foolz/sphinxql-query-builder/tests/SphinxQL/ConnectionTest.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "412"
},
{
"name": "CSS",
"bytes": "72"
},
{
"name": "JavaScript",
"bytes": "503"
},
{
"name": "PHP",
"bytes": "130478"
},
{
"name": "Python",
"bytes": "2540"
},
{
"name": "Shell",
"bytes": "194"
}
],
"symlink_target": ""
} |
const DrawCard = require('../../../drawcard.js');
class SerHobberRedwyne extends DrawCard {
setupCardAbilities() {
this.reaction({
when: {
onCardEntersPlay: event => event.card === this && event.playingType === 'marshal'
},
handler: () => {
this.game.promptForDeckSearch(this.controller, {
activePromptTitle: 'Select a card to add to your hand',
cardCondition: card => card.getType() === 'character' && card.hasTrait('Lady'),
onSelect: (player, card) => this.cardSelected(player, card),
onCancel: player => this.doneSelecting(player),
source: this
});
}
});
}
cardSelected(player, card) {
player.moveCard(card, 'hand');
this.game.addMessage('{0} uses {1} to reveal {2} and add it to their hand', player, this, card);
}
doneSelecting(player) {
this.game.addMessage('{0} does not use {1} to add a card to their hand', player, this);
}
}
SerHobberRedwyne.code = '02043';
module.exports = SerHobberRedwyne;
| {
"content_hash": "c6decd4aa0deea3ef623c14ae52c8fd8",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 104,
"avg_line_length": 35.39393939393939,
"alnum_prop": 0.5445205479452054,
"repo_name": "samuellinde/throneteki",
"id": "d2967de45fb7d1d8646dca035fb0a8015ca35e5c",
"size": "1168",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "server/game/cards/characters/02/serhobberredwyne.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "19566"
},
{
"name": "HTML",
"bytes": "1274"
},
{
"name": "JavaScript",
"bytes": "2005837"
}
],
"symlink_target": ""
} |
#pragma strict
var moveSpeed : float = 10.0;
private var player : GameObject;
private var moveRight : boolean = false;
private var moveLeft : boolean = false;
private var moveForward : boolean = false;
private var moveBackward : boolean = false;
function Start() {
player = GameObject.Find("Player");
}
function Update () {
if (Input.GetKeyUp(KeyCode.Escape)) {
// Application.LoadLevel("menu");
}
if (Input.GetKeyDown("d") || Input.GetKeyDown(KeyCode.RightArrow)) {
moveRight=true;
}
if (Input.GetKeyUp("d") || Input.GetKeyUp(KeyCode.RightArrow)) {
moveRight=false;
}
if (Input.GetKeyDown("a") || Input.GetKeyDown(KeyCode.LeftArrow)) {
moveLeft=true;
}
if (Input.GetKeyUp("a") || Input.GetKeyUp(KeyCode.LeftArrow)) {
moveLeft=false;
}
if (Input.GetKeyDown("w") || Input.GetKeyDown(KeyCode.UpArrow)) {
moveForward=true;
}
if (Input.GetKeyUp("w") || Input.GetKeyUp(KeyCode.UpArrow)) {
moveForward=false;
}
if (Input.GetKeyDown("s") || Input.GetKeyDown(KeyCode.DownArrow)) {
moveBackward=true;
}
if (Input.GetKeyUp("s") || Input.GetKeyUp(KeyCode.DownArrow)) {
moveBackward=false;
}
}
function FixedUpdate () {
if (moveRight) {
rigidbody.velocity.x = moveSpeed;
player.transform.rotation.eulerAngles.y = 0;
//player.transform.rotation.eulerAngles.z = -10;
} else if (moveLeft) {
rigidbody.velocity.x = 0-moveSpeed;
player.transform.rotation.eulerAngles.y = 180;
//player.transform.rotation.eulerAngles.z = 10;
}
if (!moveRight && !moveLeft) {
rigidbody.velocity.x = 0;
//player.transform.rotation.eulerAngles.z = 0;
}
if (moveForward) {
rigidbody.velocity.z = moveSpeed;
} else if (moveBackward) {
rigidbody.velocity.z = 0-moveSpeed;
}
if (!moveForward && !moveBackward) {
rigidbody.velocity.z = 0;
}
//if (go.NoControl) {
// rigidbody.velocity.x = 0;
// rigidbody.velocity.z = 0;
//}
if (transform.localPosition.x > 18.5) {
transform.localPosition.x = 18.5;
}
if (transform.localPosition.x < -14.5) {
transform.localPosition.x = -14.5;
}
/*
var go = GameObject.Find("State").GetComponent(State);
if (go.powerUp6 == true) {
fireRate = 0.3;
} else {
fireRate = 0.8;
}
if (go.powerUp1 == true) {
moveSpeed = 15.0;
} else {
moveSpeed = 10.0;
}
if (go.powerUp5 == true && shieldUp) {
shield.renderer.active = true;
} else {
shield.renderer.active = false;
}
*/
}
| {
"content_hash": "0cc53e915ccf6d5009331ad026fd90f5",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 69,
"avg_line_length": 22.9009009009009,
"alnum_prop": 0.6266719118804092,
"repo_name": "screwylightbulb/guitarzero",
"id": "9a1d41397438e959bafca5b4a21f3931d85f2f54",
"size": "2544",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "GuitarZero/Assets/Controller.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "237298"
},
{
"name": "C#",
"bytes": "32810"
},
{
"name": "GLSL",
"bytes": "318266"
},
{
"name": "JavaScript",
"bytes": "213604"
}
],
"symlink_target": ""
} |
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/route.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <unistd.h>
#else // Windows
#include <ws2tcpip.h>
// Tell linker to use these libraries
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
//=============================================================================
class WSA
//=============================================================================
// ONLY NEEDED IN MS-WINDOWS
//
// An instance of this class is created globally.
// So constructor is automatically called before main()
// and destructor is automatically called after main().
// Result: Windows Socket API is active when needed.
//=============================================================================
{
private:
WSADATA data;
public:
WSA()
{
int iResult = WSAStartup(MAKEWORD(2, 2), &data);
if (iResult != 0) {
std::cerr << "WSAStartup failed with error: " << iResult << '\n';
}
}
~WSA()
{
WSACleanup();
}
} wsa; // instance
#endif // Windows
#pragma mark Socket
Socket::Socket(SOCKET sock, const struct sockaddr& address)
: sock {sock}
{
switch (address.sa_family) {
case AF_INET: {
struct sockaddr_in* in_addr = reinterpret_cast<struct sockaddr_in*>(&addr);
const struct sockaddr_in* ipv4 = reinterpret_cast<const struct sockaddr_in*>(&address);
*in_addr = *ipv4;
break;
}
case AF_INET6: {
struct sockaddr_in6* in6_addr = reinterpret_cast<struct sockaddr_in6*>(&addr);
const struct sockaddr_in6* ipv6 = reinterpret_cast<const struct sockaddr_in6*>(&address);
*in6_addr = *ipv6;
break;
}
default: {
throw std::runtime_error("invalid type of socket address");
}
}
}
ssize_t Socket::read(char *buf, size_t maxlen)
{
ssize_t len = 0;
// might come in parts
while (ssize_t n = ::recv(sock, buf + len, int(maxlen - len), 0)) {
throw_if_min1((int)n);
len += n;
if (len >= maxlen) break;
}
return len;
}
std::string Socket::readline()
{
// read a line: ignore '\r', stop at '\n'
std::string line;
char c;
while (ssize_t n = ::recv(sock, &c, 1, 0)) {
throw_if_min1((int)n);
if (c == '\n') break;
if (c != '\r') line += c;
}
return line;
}
void Socket::writeline(const std::string &msg)
{
write(msg + "\r\n");
}
void Socket::clear()
{
write("\f");
}
void Socket::write(const std::string& msg)
{
write(msg.c_str(), msg.length());
}
void Socket::write(const char *buf, size_t len)
{
throw_if_min1((int)::send(sock, buf, (int)len, 0));
}
Socket::~Socket()
{
if (sock > 0) close();
}
void Socket::close()
{
std::cerr << "will close socket " << sock << std::endl;
#if defined(__APPLE__) || defined(__linux__)
throw_if_min1(::close(sock));
#else
::closesocket(sock);
#endif
sock = 0;
}
std::string Socket::get_dotted_ip() const
{
const char* result {nullptr};
char textbuf[INET6_ADDRSTRLEN]; // large enough for both IPv4 and IPv6 addresses
const struct sockaddr* addr_p = reinterpret_cast<const struct sockaddr*>(&addr);
switch (addr_p->sa_family) {
case AF_INET: {
const struct sockaddr_in* in_p = reinterpret_cast<const struct sockaddr_in*>(addr_p);
throw_if_null(result = ::inet_ntop(AF_INET, (void*)&in_p->sin_addr, textbuf, INET6_ADDRSTRLEN));
break;
}
case AF_INET6: {
const struct sockaddr_in6* in6_p = reinterpret_cast<const struct sockaddr_in6*>(addr_p);
throw_if_null(result = ::inet_ntop(AF_INET6, (void*)&in6_p->sin6_addr, textbuf, INET6_ADDRSTRLEN));
break;
}
default:
return "n/a";
}
return result;
}
#pragma mark ServerSocket
ServerSocket::ServerSocket(int port)
{
throw_if_min1(sock = ::socket(AF_INET, SOCK_STREAM, 0));
struct sockaddr_in saServer;
saServer.sin_family = AF_INET;
saServer.sin_addr.s_addr = INADDR_ANY;
saServer.sin_port = htons(port);
throw_if_min1(::bind(sock, (struct sockaddr*)&saServer, sizeof(struct sockaddr)));
throw_if_min1(::listen(sock, 100)); // the number of clients that can be queued
}
std::shared_ptr<Socket> ServerSocket::accept()
{
struct sockaddr client_addr;
client_addr.sa_family = AF_INET;
socklen_t len = sizeof(client_addr);
int fd;
throw_if_min1(fd = ::accept(sock, &client_addr, &len));
Socket* client = new Socket(fd, client_addr);
std::cerr << "Connection accepted from " << client->get_dotted_ip() << ", with socket " << fd << std::endl;
std::shared_ptr<Socket> my_ptr(client);
return my_ptr;
}
#pragma mark ClientSocket
ClientSocket::ClientSocket(const char *host, int port)
{
// construct network address for server
struct addrinfo hint;
std::memset(&hint, 0, sizeof(hint));
hint.ai_family = AF_INET;
hint.ai_socktype = SOCK_STREAM;
struct addrinfo* infolist {nullptr};
int gai_error = ::getaddrinfo(host, std::to_string(port).c_str(), &hint, &infolist);
if (gai_error) {
std::ostringstream oss;
oss << "getaddrinfo error " << gai_error << ": " << gai_strerror(gai_error) << " (" << __FILE__ << ":" << __LINE__ << ")";
throw std::runtime_error(oss.str());
}
// wrap our list pointer inside unique_ptr for auto cleanup
#if defined(__APPLE__) || defined(__linux__)
using cleanup_func = void(*)(struct addrinfo*);
std::unique_ptr<struct addrinfo, cleanup_func> list {infolist, ::freeaddrinfo};
#else // Windows
using cleanup_func = void(__stdcall*)(PADDRINFOA);
std::unique_ptr<struct addrinfo, cleanup_func> list(infolist, ::freeaddrinfo);
#endif
// create socket
throw_if_min1(sock = ::socket(list->ai_family, list->ai_socktype, list->ai_protocol));
// connect to server
throw_if_min1(::connect(sock, (struct sockaddr*)list->ai_addr, list->ai_addrlen));
}
| {
"content_hash": "6f37229188e8ad656514b6b302fc6c7f",
"timestamp": "",
"source": "github",
"line_count": 214,
"max_line_length": 130,
"avg_line_length": 28.364485981308412,
"alnum_prop": 0.5960461285008237,
"repo_name": "niekw91/Machiavelli",
"id": "875b75aab79c8801cf396d0b4a10d2a3bb83902b",
"size": "6614",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Machiavelli/Server/Socket.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "72"
},
{
"name": "C++",
"bytes": "86075"
}
],
"symlink_target": ""
} |
package org.w3c.dom;
import org.w3c.dom.Node;
public interface NodeList
{
Node item(int p0);
int getLength();
}
| {
"content_hash": "f93320cac65cfe88636f29a8f6fdf6a7",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 25,
"avg_line_length": 13.555555555555555,
"alnum_prop": 0.680327868852459,
"repo_name": "github/codeql",
"id": "63018fe44aed75dfbefa9a47db37440244ec287c",
"size": "197",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "java/ql/test/stubs/apache-commons-collections4-4.4/org/w3c/dom/NodeList.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP.NET",
"bytes": "3739"
},
{
"name": "Batchfile",
"bytes": "3534"
},
{
"name": "C",
"bytes": "410440"
},
{
"name": "C#",
"bytes": "21146000"
},
{
"name": "C++",
"bytes": "1352639"
},
{
"name": "CMake",
"bytes": "1809"
},
{
"name": "CodeQL",
"bytes": "32583145"
},
{
"name": "Dockerfile",
"bytes": "496"
},
{
"name": "EJS",
"bytes": "1478"
},
{
"name": "Emacs Lisp",
"bytes": "3445"
},
{
"name": "Go",
"bytes": "697562"
},
{
"name": "HTML",
"bytes": "58008"
},
{
"name": "Handlebars",
"bytes": "1000"
},
{
"name": "Java",
"bytes": "5417683"
},
{
"name": "JavaScript",
"bytes": "2432320"
},
{
"name": "Kotlin",
"bytes": "12163740"
},
{
"name": "Lua",
"bytes": "13113"
},
{
"name": "Makefile",
"bytes": "8631"
},
{
"name": "Mustache",
"bytes": "17025"
},
{
"name": "Nunjucks",
"bytes": "923"
},
{
"name": "Perl",
"bytes": "1941"
},
{
"name": "PowerShell",
"bytes": "1295"
},
{
"name": "Python",
"bytes": "1649035"
},
{
"name": "RAML",
"bytes": "2825"
},
{
"name": "Ruby",
"bytes": "299268"
},
{
"name": "Rust",
"bytes": "234024"
},
{
"name": "Shell",
"bytes": "23973"
},
{
"name": "Smalltalk",
"bytes": "23"
},
{
"name": "Starlark",
"bytes": "27062"
},
{
"name": "Swift",
"bytes": "204309"
},
{
"name": "Thrift",
"bytes": "3020"
},
{
"name": "TypeScript",
"bytes": "219623"
},
{
"name": "Vim Script",
"bytes": "1949"
},
{
"name": "Vue",
"bytes": "2881"
}
],
"symlink_target": ""
} |
<html>
<head>
<link rel="stylesheet" type="text/css" href="../css/desktop.css" />
<script type="text/javascript" src="../scripts/cards.js"></script>
</head>
<body>
<div id="flashcards"><script>initialize();</script></div>
<div class="footer">Desktop <a href="mobile.html">Mobile</a></div>
</body>
</html>
| {
"content_hash": "1837fe9d6ef3a4c7f789c1281633f3a9",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 105,
"avg_line_length": 38.63636363636363,
"alnum_prop": 0.5129411764705882,
"repo_name": "Harvard-ATG/HewbrewFlashcards",
"id": "985276dd2fd6c7fdc60f4602061a6463c6014463",
"size": "425",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hebrew/index.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "4154"
},
{
"name": "HTML",
"bytes": "992"
},
{
"name": "JavaScript",
"bytes": "94505"
},
{
"name": "PHP",
"bytes": "66725"
}
],
"symlink_target": ""
} |
void FileScan()
{
//Read file tags in Tags.txt
FileTags* filetags = FileBase_ReadTags();
//Read sub-tags in Sub.txt
FileSubs* filesubs = FileBase_ReadSubs();
//Get file list in current folder
FileName* filenames = FileBase_GetFileList();
//Set filename as default tag
TagBase_SetDefaultTag(filetags, filenames);
}
int main()
{
//Scan files for tags
FileScan();
//Tagging
while (1)
{
//Process initial screen
Screen_Initial();
//Process tagging screen
Screen_Tagging();
}
return 0;
}
| {
"content_hash": "6a9a16b7bbd39dbe8d04eb82c08de5ea",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 46,
"avg_line_length": 19.5,
"alnum_prop": 0.7001972386587771,
"repo_name": "tagging/Tagging",
"id": "edcd86ff6f3083127f9381490607a1aec79c2e07",
"size": "548",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Tagging/Main.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "4686"
},
{
"name": "Objective-C",
"bytes": "633"
}
],
"symlink_target": ""
} |
bower gulp + structure
tag
| {
"content_hash": "de7f76db656619edd85ccea53b87ddfc",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 22,
"avg_line_length": 13.5,
"alnum_prop": 0.7777777777777778,
"repo_name": "nuxia/js-tools",
"id": "bad39f6211b5d4fdbf2a7ded4288c09a63e1386e",
"size": "36",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" ?>
<!-- 2015-06-18 - ADDED xmlns:android so the Android properties can be extended -->
<!-- 2015-11-21 - Implemented http://phonegap.com/blog/2015/11/19/config_xml_changes_part_two/ -->
<widget xmlns = "http://www.w3.org/ns/widgets"
xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:gap = "http://phonegap.com/ns/1.0"
id = "com.bsdmasterindex.phonegapgeneric-boilerplate6"
version = "1.6.0"
versionCode = "10" >
<!-- versionCode is optional and Android only -->
<preference name='phonegap-version' value='cli-5.2.0' />
<name>Phonegap Generic Boilerplate #6</name>
<description>Phonegap Generic Boilerplate #6</description>
<author href="http://bsdmasterindex.com" email="jessemonroy650@yahoo.com">
Jesse Monroy
</author>
<!-- Target Platforms -->
<platform name="android" />
<platform name="ios" />
<platform name="windows" />
<!-- Android SECTION -->
<config-file platform="android" parent="/manifest/application" >
<!-- Add Android extensions here. SEE: http://docs.build.phonegap.com/en_US/configuring_config_file_element.md.html#Config%20File%20Elements -->
</config-file>
<!-- iOS SECTION -->
<config-file target="*-Info.plist" parent="CFBundleURLTypes">
<!-- Add iOS extensions here. SEE: http://docs.build.phonegap.com/en_US/configuring_config_file_element.md.html#Config%20File%20Elements -->
</config-file>
<!-- App requested permission -->
<preference name="permissions" value="none"/>
<!-- ANDROID * ANDROID * ANDROID -->
<!-- the subdirectory 'drawable' is somehow tie via the AndoidManifest.xml -->
<!-- according to: http://tekeye.biz/2013/android-icon-size -->
<!-- NOTE: This cause an error with the iOS icons as well. -->
<platform name="android" >
<!-- PREFERENCE * PREFERENCE * PREFERENCE -->
<preference name="SplashScreen" value="splash" />
<preference name="SplashScreenDelay" value="5000" />
<!-- ICON * ICON * ICON -->
<icon src="res/drawable-ldpi/icon_48x48_ldpi.png" gap:qualifier="ldpi" />
<icon src="res/drawable-mdpi/icon_48x48_mdpi.png" gap:qualifier="mdpi" />
<icon src="res/drawable-hdpi/icon_72x72_hdpi.png" gap:qualifier="hdpi" />
<icon src="res/drawable-xhdpi/icon_96x96_xhpdi.png" gap:qualifier="xhdpi" />
<!-- SPLASH * SPLASH * SPLASH -->
<splash src="splash.png" /> <!-- I have not found any documentation for this, but it appears deprecated -->
<splash src="res/android/splashscreen-200x320-ldpi.png" gap:qualifier="port-ldpi" />
<splash src="res/android/splashscreen-320x480-mdpi.png" gap:qualifier="port-mdpi" />
<splash src="res/android/splashscreen-480x800-hdpi.png" gap:qualifier="port-hdpi" />
<splash src="res/android/splashscreen-720x1280-xhdpi.png" gap:qualifier="port-xhdpi" />
</platform>
<!-- iOS * iOS * iOS -->
<platform name="ios" >
<!-- PREFERENCE * PREFERENCE * PREFERENCE -->
<preference name="auto-hide-splash-screen" value="false" /> <!-- iOS -->
<preference name="show-splash-screen-spinner" value="false" /> <!-- iOS -->
<!-- ICON * ICON * ICON -->
<icon src="res/ios/icon_57x57.png" width="57" height="57" />
<icon src="res/ios/icon_76x76.png" width="76" height="76" />
<icon src="res/ios/icon_120x120.png" width="120" height="120" />
<icon src="res/ios/icon_152x152.png" width="152" height="152" />
<icon src="res/ios/icon_180x180.png" width="180" height="180" />
<!-- SPLASH * SPLASH * SPLASH -->
<splash src="res/ios/splashscreen~iphone-320x480" width="320" height="480" />
<splash src="res/ios/splashscreen~iphone-640x960.png" width="640" height="960" />
<splash src="res/ios/splashscreen~iphone-640x1136.png" width="640" height="1136" />
<!-- landscape not supported at this time: 2015-06-07. Already reported see NOTES -->
<splash src="res/ios/splashscreen-landscape~iphone-1136x640.png" width="1136" height="640" />
<splash src="res/ios/splashscreen-portrait~ipad-768x1024.png" width="768" height="1024" />
<splash src="res/ios/splashscreen-landscape~ipad-1024x768.png" width="1024" height="768" />
</platform>
<!-- PLUGINS PLUGINS -->
<!-- spec="" follows the syntax of https://docs.npmjs.com/cli/install -->
<plugin name="cordova-plugin-battery-status" source="npm" spec="1.1.0" />
<plugin name="cordova-plugin-camera" source="npm" spec="1.2.0" />
<plugin name="cordova-plugin-console" source="npm" spec="1.0.1" />
<plugin name="cordova-plugin-contacts" source="npm" spec="1.1.0" />
<plugin name="cordova-plugin-device" source="npm" spec="1.0.1" />
<plugin name="cordova-plugin-device-motion" source="npm" spec="1.1.1" />
<plugin name="cordova-plugin-device-orientation" source="npm" spec="1.0.1" />
<plugin name="cordova-plugin-dialogs" source="npm" spec="1.1.1" />
<plugin name="cordova-plugin-file" source="npm" spec="3.0.0" />
<plugin name="cordova-plugin-file-transfer" source="npm" spec="1.3.0" />
<plugin name="cordova-plugin-geolocation" source="npm" spec="1.0.1" />
<plugin name="cordova-plugin-globalization" source="npm" spec="1.0.1" />
<plugin name="cordova-plugin-inappbrowser" source="npm" spec="1.0.1" />
<plugin name="cordova-plugin-legacy-whitelist" source="npm" spec="1.1.0" /> <!-- Deprecated -->
<plugin name="cordova-plugin-media" source="npm" spec="1.0.1" />
<plugin name="cordova-plugin-media-capture" source="npm" spec="1.0.1" />
<plugin name="cordova-plugin-network-information" source="npm" spec="1.0.1" />
<plugin name="cordova-plugin-splashscreen" source="npm" spec="2.1.0" />
<plugin name="cordova-plugin-statusbar" source="npm" spec="1.0.1" /> <!-- NEW -->
<plugin name="cordova-plugin-test-framework" source="npm" spec="1.0.1" /> <!-- NEW -->
<plugin name="cordova-plugin-vibration" source="npm" spec="1.2.0" />
<plugin name="cordova-plugin-whitelist" source="npm" spec="1.0.0" /> <!-- NEW -->
<!-- popular alternative to the google chrome webview -->
<!-- <plugin name='org.crosswalk.engine' version='1.3.0' source='pgb' /> -->
</widget>
| {
"content_hash": "7d2ff2793bdceba519390c762f6a0229",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 156,
"avg_line_length": 63.981308411214954,
"alnum_prop": 0.5907099035933392,
"repo_name": "jessemonroy650/Phonegap--Generic-Boilerplate6",
"id": "003d42324a789c2df0958ff7071686206f23224a",
"size": "6846",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config.xml",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "79626"
},
{
"name": "HTML",
"bytes": "2715"
},
{
"name": "JavaScript",
"bytes": "81925"
},
{
"name": "Shell",
"bytes": "516"
}
],
"symlink_target": ""
} |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Machinery to initialise interface prototype objects and interface objects.
use dom::bindings::codegen::Bindings::HTMLAnchorElementBinding;
use dom::bindings::codegen::Bindings::HTMLAreaElementBinding;
use dom::bindings::codegen::Bindings::HTMLAudioElementBinding;
use dom::bindings::codegen::Bindings::HTMLBRElementBinding;
use dom::bindings::codegen::Bindings::HTMLBaseElementBinding;
use dom::bindings::codegen::Bindings::HTMLBodyElementBinding;
use dom::bindings::codegen::Bindings::HTMLButtonElementBinding;
use dom::bindings::codegen::Bindings::HTMLCanvasElementBinding;
use dom::bindings::codegen::Bindings::HTMLDListElementBinding;
use dom::bindings::codegen::Bindings::HTMLDataElementBinding;
use dom::bindings::codegen::Bindings::HTMLDataListElementBinding;
use dom::bindings::codegen::Bindings::HTMLDetailsElementBinding;
use dom::bindings::codegen::Bindings::HTMLDialogElementBinding;
use dom::bindings::codegen::Bindings::HTMLDirectoryElementBinding;
use dom::bindings::codegen::Bindings::HTMLDivElementBinding;
use dom::bindings::codegen::Bindings::HTMLElementBinding;
use dom::bindings::codegen::Bindings::HTMLEmbedElementBinding;
use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding;
use dom::bindings::codegen::Bindings::HTMLFontElementBinding;
use dom::bindings::codegen::Bindings::HTMLFormElementBinding;
use dom::bindings::codegen::Bindings::HTMLFrameElementBinding;
use dom::bindings::codegen::Bindings::HTMLFrameSetElementBinding;
use dom::bindings::codegen::Bindings::HTMLHRElementBinding;
use dom::bindings::codegen::Bindings::HTMLHeadElementBinding;
use dom::bindings::codegen::Bindings::HTMLHeadingElementBinding;
use dom::bindings::codegen::Bindings::HTMLHtmlElementBinding;
use dom::bindings::codegen::Bindings::HTMLIFrameElementBinding;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding;
use dom::bindings::codegen::Bindings::HTMLInputElementBinding;
use dom::bindings::codegen::Bindings::HTMLLIElementBinding;
use dom::bindings::codegen::Bindings::HTMLLabelElementBinding;
use dom::bindings::codegen::Bindings::HTMLLegendElementBinding;
use dom::bindings::codegen::Bindings::HTMLLinkElementBinding;
use dom::bindings::codegen::Bindings::HTMLMapElementBinding;
use dom::bindings::codegen::Bindings::HTMLMetaElementBinding;
use dom::bindings::codegen::Bindings::HTMLMeterElementBinding;
use dom::bindings::codegen::Bindings::HTMLModElementBinding;
use dom::bindings::codegen::Bindings::HTMLOListElementBinding;
use dom::bindings::codegen::Bindings::HTMLObjectElementBinding;
use dom::bindings::codegen::Bindings::HTMLOptGroupElementBinding;
use dom::bindings::codegen::Bindings::HTMLOptionElementBinding;
use dom::bindings::codegen::Bindings::HTMLOutputElementBinding;
use dom::bindings::codegen::Bindings::HTMLParagraphElementBinding;
use dom::bindings::codegen::Bindings::HTMLParamElementBinding;
use dom::bindings::codegen::Bindings::HTMLPreElementBinding;
use dom::bindings::codegen::Bindings::HTMLProgressElementBinding;
use dom::bindings::codegen::Bindings::HTMLQuoteElementBinding;
use dom::bindings::codegen::Bindings::HTMLScriptElementBinding;
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding;
use dom::bindings::codegen::Bindings::HTMLSourceElementBinding;
use dom::bindings::codegen::Bindings::HTMLSpanElementBinding;
use dom::bindings::codegen::Bindings::HTMLStyleElementBinding;
use dom::bindings::codegen::Bindings::HTMLTableCaptionElementBinding;
use dom::bindings::codegen::Bindings::HTMLTableColElementBinding;
use dom::bindings::codegen::Bindings::HTMLTableDataCellElementBinding;
use dom::bindings::codegen::Bindings::HTMLTableElementBinding;
use dom::bindings::codegen::Bindings::HTMLTableHeaderCellElementBinding;
use dom::bindings::codegen::Bindings::HTMLTableRowElementBinding;
use dom::bindings::codegen::Bindings::HTMLTableSectionElementBinding;
use dom::bindings::codegen::Bindings::HTMLTemplateElementBinding;
use dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding;
use dom::bindings::codegen::Bindings::HTMLTimeElementBinding;
use dom::bindings::codegen::Bindings::HTMLTitleElementBinding;
use dom::bindings::codegen::Bindings::HTMLTrackElementBinding;
use dom::bindings::codegen::Bindings::HTMLUListElementBinding;
use dom::bindings::codegen::Bindings::HTMLVideoElementBinding;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::codegen::InterfaceObjectMap::Globals;
use dom::bindings::codegen::PrototypeList;
use dom::bindings::constant::{ConstantSpec, define_constants};
use dom::bindings::conversions::{DOM_OBJECT_SLOT, DerivedFrom, get_dom_class};
use dom::bindings::error::{Error, Fallible};
use dom::bindings::guard::Guard;
use dom::bindings::root::DomRoot;
use dom::bindings::utils::{DOM_PROTOTYPE_SLOT, ProtoOrIfaceArray, get_proto_or_iface_array};
use dom::create::create_native_html_element;
use dom::customelementregistry::ConstructionStackEntry;
use dom::element::{CustomElementState, Element, ElementCreator};
use dom::htmlelement::HTMLElement;
use dom::window::Window;
use html5ever::LocalName;
use html5ever::interface::QualName;
use js::error::throw_type_error;
use js::glue::{RUST_SYMBOL_TO_JSID, UncheckedUnwrapObject, UnwrapObject};
use js::jsapi::{CallArgs, Class, ClassOps, CompartmentOptions, CurrentGlobalOrNull};
use js::jsapi::{GetGlobalForObjectCrossCompartment, GetWellKnownSymbol, HandleObject, HandleValue};
use js::jsapi::{JSAutoCompartment, JSClass, JSContext, JSFUN_CONSTRUCTOR, JSFunctionSpec, JSObject};
use js::jsapi::{JSPROP_PERMANENT, JSPROP_READONLY, JSPROP_RESOLVING};
use js::jsapi::{JSPropertySpec, JSString, JSTracer, JSVersion, JS_AtomizeAndPinString};
use js::jsapi::{JS_DefineProperty, JS_DefineProperty1, JS_DefineProperty2};
use js::jsapi::{JS_DefineProperty4, JS_DefinePropertyById3, JS_FireOnNewGlobalObject};
use js::jsapi::{JS_GetFunctionObject, JS_GetPrototype};
use js::jsapi::{JS_LinkConstructorAndPrototype, JS_NewFunction, JS_NewGlobalObject};
use js::jsapi::{JS_NewObject, JS_NewObjectWithUniqueType, JS_NewPlainObject};
use js::jsapi::{JS_NewStringCopyN, JS_SetReservedSlot, MutableHandleObject};
use js::jsapi::{MutableHandleValue, ObjectOps, OnNewGlobalHookOption, SymbolCode};
use js::jsapi::{TrueHandleValue, Value};
use js::jsval::{JSVal, PrivateValue};
use js::rust::{define_methods, define_properties, get_object_class};
use libc;
use script_thread::ScriptThread;
use std::ptr;
/// The class of a non-callback interface object.
#[derive(Clone, Copy)]
pub struct NonCallbackInterfaceObjectClass {
/// The SpiderMonkey Class structure.
pub class: Class,
/// The prototype id of that interface, used in the hasInstance hook.
pub proto_id: PrototypeList::ID,
/// The prototype depth of that interface, used in the hasInstance hook.
pub proto_depth: u16,
/// The string representation of the object.
pub representation: &'static [u8],
}
unsafe impl Sync for NonCallbackInterfaceObjectClass {}
impl NonCallbackInterfaceObjectClass {
/// Create a new `NonCallbackInterfaceObjectClass` structure.
pub const fn new(constructor_behavior: &'static InterfaceConstructorBehavior,
string_rep: &'static [u8],
proto_id: PrototypeList::ID,
proto_depth: u16)
-> NonCallbackInterfaceObjectClass {
NonCallbackInterfaceObjectClass {
class: Class {
name: b"Function\0" as *const _ as *const libc::c_char,
flags: 0,
cOps: &constructor_behavior.0,
spec: ptr::null(),
ext: ptr::null(),
oOps: &OBJECT_OPS,
},
proto_id: proto_id,
proto_depth: proto_depth,
representation: string_rep,
}
}
/// cast own reference to `JSClass` reference
pub fn as_jsclass(&self) -> &JSClass {
unsafe {
&*(self as *const _ as *const JSClass)
}
}
}
/// A constructor class hook.
pub type ConstructorClassHook =
unsafe extern "C" fn(cx: *mut JSContext, argc: u32, vp: *mut Value) -> bool;
/// The constructor behavior of a non-callback interface object.
pub struct InterfaceConstructorBehavior(ClassOps);
impl InterfaceConstructorBehavior {
/// An interface constructor that unconditionally throws a type error.
pub const fn throw() -> Self {
InterfaceConstructorBehavior(ClassOps {
addProperty: None,
delProperty: None,
getProperty: None,
setProperty: None,
enumerate: None,
resolve: None,
mayResolve: None,
finalize: None,
call: Some(invalid_constructor),
construct: Some(invalid_constructor),
hasInstance: Some(has_instance_hook),
trace: None,
})
}
/// An interface constructor that calls a native Rust function.
pub const fn call(hook: ConstructorClassHook) -> Self {
InterfaceConstructorBehavior(ClassOps {
addProperty: None,
delProperty: None,
getProperty: None,
setProperty: None,
enumerate: None,
resolve: None,
mayResolve: None,
finalize: None,
call: Some(non_new_constructor),
construct: Some(hook),
hasInstance: Some(has_instance_hook),
trace: None,
})
}
}
/// A trace hook.
pub type TraceHook =
unsafe extern "C" fn(trc: *mut JSTracer, obj: *mut JSObject);
/// Create a global object with the given class.
pub unsafe fn create_global_object(
cx: *mut JSContext,
class: &'static JSClass,
private: *const libc::c_void,
trace: TraceHook,
rval: MutableHandleObject) {
assert!(rval.is_null());
let mut options = CompartmentOptions::default();
options.behaviors_.version_ = JSVersion::JSVERSION_ECMA_5;
options.creationOptions_.traceGlobal_ = Some(trace);
options.creationOptions_.sharedMemoryAndAtomics_ = true;
rval.set(JS_NewGlobalObject(cx,
class,
ptr::null_mut(),
OnNewGlobalHookOption::DontFireOnNewGlobalHook,
&options));
assert!(!rval.is_null());
// Initialize the reserved slots before doing anything that can GC, to
// avoid getting trace hooks called on a partially initialized object.
JS_SetReservedSlot(rval.get(), DOM_OBJECT_SLOT, PrivateValue(private));
let proto_array: Box<ProtoOrIfaceArray> =
box [0 as *mut JSObject; PrototypeList::PROTO_OR_IFACE_LENGTH];
JS_SetReservedSlot(rval.get(),
DOM_PROTOTYPE_SLOT,
PrivateValue(Box::into_raw(proto_array) as *const libc::c_void));
let _ac = JSAutoCompartment::new(cx, rval.get());
JS_FireOnNewGlobalObject(cx, rval.handle());
}
// https://html.spec.whatwg.org/multipage/#htmlconstructor
pub unsafe fn html_constructor<T>(window: &Window, call_args: &CallArgs) -> Fallible<DomRoot<T>>
where T: DerivedFrom<Element> {
let document = window.Document();
// Step 1
let registry = window.CustomElements();
// Step 2 is checked in the generated caller code
// Step 3
rooted!(in(window.get_cx()) let new_target = call_args.new_target().to_object());
let definition = match registry.lookup_definition_by_constructor(new_target.handle()) {
Some(definition) => definition,
None => return Err(Error::Type("No custom element definition found for new.target".to_owned())),
};
rooted!(in(window.get_cx()) let callee = UnwrapObject(call_args.callee(), 1));
if callee.is_null() {
return Err(Error::Security);
}
{
let _ac = JSAutoCompartment::new(window.get_cx(), callee.get());
rooted!(in(window.get_cx()) let mut constructor = ptr::null_mut());
rooted!(in(window.get_cx()) let global_object = CurrentGlobalOrNull(window.get_cx()));
if definition.is_autonomous() {
// Step 4
// Since this element is autonomous, its active function object must be the HTMLElement
// Retrieve the constructor object for HTMLElement
HTMLElementBinding::GetConstructorObject(window.get_cx(), global_object.handle(), constructor.handle_mut());
} else {
// Step 5
get_constructor_object_from_local_name(definition.local_name.clone(),
window.get_cx(),
global_object.handle(),
constructor.handle_mut());
}
// Callee must be the same as the element interface's constructor object.
if constructor.get() != callee.get() {
return Err(Error::Type("Custom element does not extend the proper interface".to_owned()));
}
}
let entry = definition.construction_stack.borrow().last().cloned();
match entry {
// Step 8
None => {
// Step 8.1
let name = QualName::new(None, ns!(html), definition.local_name.clone());
let element = if definition.is_autonomous() {
DomRoot::upcast(HTMLElement::new(name.local, None, &*document))
} else {
create_native_html_element(name, None, &*document, ElementCreator::ScriptCreated)
};
// Step 8.2 is performed in the generated caller code.
// Step 8.3
element.set_custom_element_state(CustomElementState::Custom);
// Step 8.4
element.set_custom_element_definition(definition.clone());
// Step 8.5
DomRoot::downcast(element).ok_or(Error::InvalidState)
},
// Step 9
Some(ConstructionStackEntry::Element(element)) => {
// Step 11 is performed in the generated caller code.
// Step 12
let mut construction_stack = definition.construction_stack.borrow_mut();
construction_stack.pop();
construction_stack.push(ConstructionStackEntry::AlreadyConstructedMarker);
// Step 13
DomRoot::downcast(element).ok_or(Error::InvalidState)
},
// Step 10
Some(ConstructionStackEntry::AlreadyConstructedMarker) => Err(Error::InvalidState),
}
}
pub fn push_new_element_queue() {
ScriptThread::push_new_element_queue();
}
pub fn pop_current_element_queue() {
ScriptThread::pop_current_element_queue();
}
/// Create and define the interface object of a callback interface.
pub unsafe fn create_callback_interface_object(
cx: *mut JSContext,
global: HandleObject,
constants: &[Guard<&[ConstantSpec]>],
name: &[u8],
rval: MutableHandleObject) {
assert!(!constants.is_empty());
rval.set(JS_NewObject(cx, ptr::null()));
assert!(!rval.ptr.is_null());
define_guarded_constants(cx, rval.handle(), constants);
define_name(cx, rval.handle(), name);
define_on_global_object(cx, global, name, rval.handle());
}
/// Create the interface prototype object of a non-callback interface.
pub unsafe fn create_interface_prototype_object(
cx: *mut JSContext,
proto: HandleObject,
class: &'static JSClass,
regular_methods: &[Guard<&'static [JSFunctionSpec]>],
regular_properties: &[Guard<&'static [JSPropertySpec]>],
constants: &[Guard<&[ConstantSpec]>],
unscopable_names: &[&[u8]],
rval: MutableHandleObject) {
create_object(cx, proto, class, regular_methods, regular_properties, constants, rval);
if !unscopable_names.is_empty() {
rooted!(in(cx) let mut unscopable_obj = ptr::null_mut());
create_unscopable_object(cx, unscopable_names, unscopable_obj.handle_mut());
let unscopable_symbol = GetWellKnownSymbol(cx, SymbolCode::unscopables);
assert!(!unscopable_symbol.is_null());
rooted!(in(cx) let unscopable_id = RUST_SYMBOL_TO_JSID(unscopable_symbol));
assert!(JS_DefinePropertyById3(
cx, rval.handle(), unscopable_id.handle(), unscopable_obj.handle(),
JSPROP_READONLY, None, None))
}
}
/// Create and define the interface object of a non-callback interface.
pub unsafe fn create_noncallback_interface_object(
cx: *mut JSContext,
global: HandleObject,
proto: HandleObject,
class: &'static NonCallbackInterfaceObjectClass,
static_methods: &[Guard<&'static [JSFunctionSpec]>],
static_properties: &[Guard<&'static [JSPropertySpec]>],
constants: &[Guard<&[ConstantSpec]>],
interface_prototype_object: HandleObject,
name: &[u8],
length: u32,
rval: MutableHandleObject) {
create_object(cx,
proto,
class.as_jsclass(),
static_methods,
static_properties,
constants,
rval);
assert!(JS_LinkConstructorAndPrototype(cx, rval.handle(), interface_prototype_object));
define_name(cx, rval.handle(), name);
define_length(cx, rval.handle(), length);
define_on_global_object(cx, global, name, rval.handle());
}
/// Create and define the named constructors of a non-callback interface.
pub unsafe fn create_named_constructors(
cx: *mut JSContext,
global: HandleObject,
named_constructors: &[(ConstructorClassHook, &[u8], u32)],
interface_prototype_object: HandleObject) {
rooted!(in(cx) let mut constructor = ptr::null_mut());
for &(native, name, arity) in named_constructors {
assert!(*name.last().unwrap() == b'\0');
let fun = JS_NewFunction(cx,
Some(native),
arity,
JSFUN_CONSTRUCTOR,
name.as_ptr() as *const libc::c_char);
assert!(!fun.is_null());
constructor.set(JS_GetFunctionObject(fun));
assert!(!constructor.is_null());
assert!(JS_DefineProperty1(cx,
constructor.handle(),
b"prototype\0".as_ptr() as *const libc::c_char,
interface_prototype_object,
JSPROP_PERMANENT | JSPROP_READONLY,
None,
None));
define_on_global_object(cx, global, name, constructor.handle());
}
}
/// Create a new object with a unique type.
pub unsafe fn create_object(
cx: *mut JSContext,
proto: HandleObject,
class: &'static JSClass,
methods: &[Guard<&'static [JSFunctionSpec]>],
properties: &[Guard<&'static [JSPropertySpec]>],
constants: &[Guard<&[ConstantSpec]>],
rval: MutableHandleObject) {
rval.set(JS_NewObjectWithUniqueType(cx, class, proto));
assert!(!rval.ptr.is_null());
define_guarded_methods(cx, rval.handle(), methods);
define_guarded_properties(cx, rval.handle(), properties);
define_guarded_constants(cx, rval.handle(), constants);
}
/// Conditionally define constants on an object.
pub unsafe fn define_guarded_constants(
cx: *mut JSContext,
obj: HandleObject,
constants: &[Guard<&[ConstantSpec]>]) {
for guard in constants {
if let Some(specs) = guard.expose(cx, obj) {
define_constants(cx, obj, specs);
}
}
}
/// Conditionally define methods on an object.
pub unsafe fn define_guarded_methods(
cx: *mut JSContext,
obj: HandleObject,
methods: &[Guard<&'static [JSFunctionSpec]>]) {
for guard in methods {
if let Some(specs) = guard.expose(cx, obj) {
define_methods(cx, obj, specs).unwrap();
}
}
}
/// Conditionally define properties on an object.
pub unsafe fn define_guarded_properties(
cx: *mut JSContext,
obj: HandleObject,
properties: &[Guard<&'static [JSPropertySpec]>]) {
for guard in properties {
if let Some(specs) = guard.expose(cx, obj) {
define_properties(cx, obj, specs).unwrap();
}
}
}
/// Returns whether an interface with exposure set given by `globals` should
/// be exposed in the global object `obj`.
pub unsafe fn is_exposed_in(object: HandleObject, globals: Globals) -> bool {
let unwrapped = UncheckedUnwrapObject(object.get(), /* stopAtWindowProxy = */ 0);
let dom_class = get_dom_class(unwrapped).unwrap();
globals.contains(dom_class.global)
}
/// Define a property with a given name on the global object. Should be called
/// through the resolve hook.
pub unsafe fn define_on_global_object(
cx: *mut JSContext,
global: HandleObject,
name: &[u8],
obj: HandleObject) {
assert!(*name.last().unwrap() == b'\0');
assert!(JS_DefineProperty1(cx,
global,
name.as_ptr() as *const libc::c_char,
obj,
JSPROP_RESOLVING,
None, None));
}
const OBJECT_OPS: ObjectOps = ObjectOps {
lookupProperty: None,
defineProperty: None,
hasProperty: None,
getProperty: None,
setProperty: None,
getOwnPropertyDescriptor: None,
deleteProperty: None,
watch: None,
unwatch: None,
getElements: None,
enumerate: None,
funToString: Some(fun_to_string_hook),
};
unsafe extern "C" fn fun_to_string_hook(cx: *mut JSContext,
obj: HandleObject,
_indent: u32)
-> *mut JSString {
let js_class = get_object_class(obj.get());
assert!(!js_class.is_null());
let repr = (*(js_class as *const NonCallbackInterfaceObjectClass)).representation;
assert!(!repr.is_empty());
let ret = JS_NewStringCopyN(cx, repr.as_ptr() as *const libc::c_char, repr.len());
assert!(!ret.is_null());
ret
}
/// Hook for instanceof on interface objects.
unsafe extern "C" fn has_instance_hook(cx: *mut JSContext,
obj: HandleObject,
value: MutableHandleValue,
rval: *mut bool) -> bool {
match has_instance(cx, obj, value.handle()) {
Ok(result) => {
*rval = result;
true
}
Err(()) => false,
}
}
/// Return whether a value is an instance of a given prototype.
/// http://heycam.github.io/webidl/#es-interface-hasinstance
unsafe fn has_instance(
cx: *mut JSContext,
interface_object: HandleObject,
value: HandleValue)
-> Result<bool, ()> {
if !value.is_object() {
// Step 1.
return Ok(false);
}
rooted!(in(cx) let mut value = value.to_object());
let js_class = get_object_class(interface_object.get());
let object_class = &*(js_class as *const NonCallbackInterfaceObjectClass);
if let Ok(dom_class) = get_dom_class(UncheckedUnwrapObject(value.get(),
/* stopAtWindowProxy = */ 0)) {
if dom_class.interface_chain[object_class.proto_depth as usize] == object_class.proto_id {
// Step 4.
return Ok(true);
}
}
// Step 2.
let global = GetGlobalForObjectCrossCompartment(interface_object.get());
assert!(!global.is_null());
let proto_or_iface_array = get_proto_or_iface_array(global);
rooted!(in(cx) let prototype = (*proto_or_iface_array)[object_class.proto_id as usize]);
assert!(!prototype.is_null());
// Step 3 only concern legacy callback interface objects (i.e. NodeFilter).
while JS_GetPrototype(cx, value.handle(), value.handle_mut()) {
if value.is_null() {
// Step 5.2.
return Ok(false);
} else if value.get() as *const _ == prototype.get() {
// Step 5.3.
return Ok(true);
}
}
// JS_GetPrototype threw an exception.
Err(())
}
unsafe fn create_unscopable_object(
cx: *mut JSContext,
names: &[&[u8]],
rval: MutableHandleObject) {
assert!(!names.is_empty());
assert!(rval.is_null());
rval.set(JS_NewPlainObject(cx));
assert!(!rval.ptr.is_null());
for &name in names {
assert!(*name.last().unwrap() == b'\0');
assert!(JS_DefineProperty(
cx, rval.handle(), name.as_ptr() as *const libc::c_char, TrueHandleValue,
JSPROP_READONLY, None, None));
}
}
unsafe fn define_name(cx: *mut JSContext, obj: HandleObject, name: &[u8]) {
assert!(*name.last().unwrap() == b'\0');
rooted!(in(cx) let name = JS_AtomizeAndPinString(cx, name.as_ptr() as *const libc::c_char));
assert!(!name.is_null());
assert!(JS_DefineProperty2(cx,
obj,
b"name\0".as_ptr() as *const libc::c_char,
name.handle(),
JSPROP_READONLY,
None, None));
}
unsafe fn define_length(cx: *mut JSContext, obj: HandleObject, length: u32) {
assert!(JS_DefineProperty4(cx,
obj,
b"length\0".as_ptr() as *const libc::c_char,
length,
JSPROP_READONLY,
None, None));
}
unsafe extern "C" fn invalid_constructor(
cx: *mut JSContext,
_argc: libc::c_uint,
_vp: *mut JSVal)
-> bool {
throw_type_error(cx, "Illegal constructor.");
false
}
unsafe extern "C" fn non_new_constructor(
cx: *mut JSContext,
_argc: libc::c_uint,
_vp: *mut JSVal)
-> bool {
throw_type_error(cx, "This constructor needs to be called with `new`.");
false
}
/// Returns the constructor object for the element associated with the given local name.
/// This list should only include elements marked with the [HTMLConstructor] extended attribute.
pub fn get_constructor_object_from_local_name(name: LocalName,
cx: *mut JSContext,
global: HandleObject,
rval: MutableHandleObject)
-> bool {
macro_rules! get_constructor(
($binding:ident) => ({
unsafe { $binding::GetConstructorObject(cx, global, rval); }
true
})
);
match name {
local_name!("a") => get_constructor!(HTMLAnchorElementBinding),
local_name!("abbr") => get_constructor!(HTMLElementBinding),
local_name!("acronym") => get_constructor!(HTMLElementBinding),
local_name!("address") => get_constructor!(HTMLElementBinding),
local_name!("area") => get_constructor!(HTMLAreaElementBinding),
local_name!("article") => get_constructor!(HTMLElementBinding),
local_name!("aside") => get_constructor!(HTMLElementBinding),
local_name!("audio") => get_constructor!(HTMLAudioElementBinding),
local_name!("b") => get_constructor!(HTMLElementBinding),
local_name!("base") => get_constructor!(HTMLBaseElementBinding),
local_name!("bdi") => get_constructor!(HTMLElementBinding),
local_name!("bdo") => get_constructor!(HTMLElementBinding),
local_name!("big") => get_constructor!(HTMLElementBinding),
local_name!("blockquote") => get_constructor!(HTMLQuoteElementBinding),
local_name!("body") => get_constructor!(HTMLBodyElementBinding),
local_name!("br") => get_constructor!(HTMLBRElementBinding),
local_name!("button") => get_constructor!(HTMLButtonElementBinding),
local_name!("canvas") => get_constructor!(HTMLCanvasElementBinding),
local_name!("caption") => get_constructor!(HTMLTableCaptionElementBinding),
local_name!("center") => get_constructor!(HTMLElementBinding),
local_name!("cite") => get_constructor!(HTMLElementBinding),
local_name!("code") => get_constructor!(HTMLElementBinding),
local_name!("col") => get_constructor!(HTMLTableColElementBinding),
local_name!("colgroup") => get_constructor!(HTMLTableColElementBinding),
local_name!("data") => get_constructor!(HTMLDataElementBinding),
local_name!("datalist") => get_constructor!(HTMLDataListElementBinding),
local_name!("dd") => get_constructor!(HTMLElementBinding),
local_name!("del") => get_constructor!(HTMLModElementBinding),
local_name!("details") => get_constructor!(HTMLDetailsElementBinding),
local_name!("dfn") => get_constructor!(HTMLElementBinding),
local_name!("dialog") => get_constructor!(HTMLDialogElementBinding),
local_name!("dir") => get_constructor!(HTMLDirectoryElementBinding),
local_name!("div") => get_constructor!(HTMLDivElementBinding),
local_name!("dl") => get_constructor!(HTMLDListElementBinding),
local_name!("dt") => get_constructor!(HTMLElementBinding),
local_name!("em") => get_constructor!(HTMLElementBinding),
local_name!("embed") => get_constructor!(HTMLEmbedElementBinding),
local_name!("fieldset") => get_constructor!(HTMLFieldSetElementBinding),
local_name!("figcaption") => get_constructor!(HTMLElementBinding),
local_name!("figure") => get_constructor!(HTMLElementBinding),
local_name!("font") => get_constructor!(HTMLFontElementBinding),
local_name!("footer") => get_constructor!(HTMLElementBinding),
local_name!("form") => get_constructor!(HTMLFormElementBinding),
local_name!("frame") => get_constructor!(HTMLFrameElementBinding),
local_name!("frameset") => get_constructor!(HTMLFrameSetElementBinding),
local_name!("h1") => get_constructor!(HTMLHeadingElementBinding),
local_name!("h2") => get_constructor!(HTMLHeadingElementBinding),
local_name!("h3") => get_constructor!(HTMLHeadingElementBinding),
local_name!("h4") => get_constructor!(HTMLHeadingElementBinding),
local_name!("h5") => get_constructor!(HTMLHeadingElementBinding),
local_name!("h6") => get_constructor!(HTMLHeadingElementBinding),
local_name!("head") => get_constructor!(HTMLHeadElementBinding),
local_name!("header") => get_constructor!(HTMLElementBinding),
local_name!("hgroup") => get_constructor!(HTMLElementBinding),
local_name!("hr") => get_constructor!(HTMLHRElementBinding),
local_name!("html") => get_constructor!(HTMLHtmlElementBinding),
local_name!("i") => get_constructor!(HTMLElementBinding),
local_name!("iframe") => get_constructor!(HTMLIFrameElementBinding),
local_name!("img") => get_constructor!(HTMLImageElementBinding),
local_name!("input") => get_constructor!(HTMLInputElementBinding),
local_name!("ins") => get_constructor!(HTMLModElementBinding),
local_name!("kbd") => get_constructor!(HTMLElementBinding),
local_name!("label") => get_constructor!(HTMLLabelElementBinding),
local_name!("legend") => get_constructor!(HTMLLegendElementBinding),
local_name!("li") => get_constructor!(HTMLLIElementBinding),
local_name!("link") => get_constructor!(HTMLLinkElementBinding),
local_name!("listing") => get_constructor!(HTMLPreElementBinding),
local_name!("main") => get_constructor!(HTMLElementBinding),
local_name!("map") => get_constructor!(HTMLMapElementBinding),
local_name!("mark") => get_constructor!(HTMLElementBinding),
local_name!("marquee") => get_constructor!(HTMLElementBinding),
local_name!("meta") => get_constructor!(HTMLMetaElementBinding),
local_name!("meter") => get_constructor!(HTMLMeterElementBinding),
local_name!("nav") => get_constructor!(HTMLElementBinding),
local_name!("nobr") => get_constructor!(HTMLElementBinding),
local_name!("noframes") => get_constructor!(HTMLElementBinding),
local_name!("noscript") => get_constructor!(HTMLElementBinding),
local_name!("object") => get_constructor!(HTMLObjectElementBinding),
local_name!("ol") => get_constructor!(HTMLOListElementBinding),
local_name!("optgroup") => get_constructor!(HTMLOptGroupElementBinding),
local_name!("option") => get_constructor!(HTMLOptionElementBinding),
local_name!("output") => get_constructor!(HTMLOutputElementBinding),
local_name!("p") => get_constructor!(HTMLParagraphElementBinding),
local_name!("param") => get_constructor!(HTMLParamElementBinding),
local_name!("plaintext") => get_constructor!(HTMLPreElementBinding),
local_name!("pre") => get_constructor!(HTMLPreElementBinding),
local_name!("progress") => get_constructor!(HTMLProgressElementBinding),
local_name!("q") => get_constructor!(HTMLQuoteElementBinding),
local_name!("rp") => get_constructor!(HTMLElementBinding),
local_name!("rt") => get_constructor!(HTMLElementBinding),
local_name!("ruby") => get_constructor!(HTMLElementBinding),
local_name!("s") => get_constructor!(HTMLElementBinding),
local_name!("samp") => get_constructor!(HTMLElementBinding),
local_name!("script") => get_constructor!(HTMLScriptElementBinding),
local_name!("section") => get_constructor!(HTMLElementBinding),
local_name!("select") => get_constructor!(HTMLSelectElementBinding),
local_name!("small") => get_constructor!(HTMLElementBinding),
local_name!("source") => get_constructor!(HTMLSourceElementBinding),
local_name!("span") => get_constructor!(HTMLSpanElementBinding),
local_name!("strike") => get_constructor!(HTMLElementBinding),
local_name!("strong") => get_constructor!(HTMLElementBinding),
local_name!("style") => get_constructor!(HTMLStyleElementBinding),
local_name!("sub") => get_constructor!(HTMLElementBinding),
local_name!("summary") => get_constructor!(HTMLElementBinding),
local_name!("sup") => get_constructor!(HTMLElementBinding),
local_name!("table") => get_constructor!(HTMLTableElementBinding),
local_name!("tbody") => get_constructor!(HTMLTableSectionElementBinding),
local_name!("td") => get_constructor!(HTMLTableDataCellElementBinding),
local_name!("template") => get_constructor!(HTMLTemplateElementBinding),
local_name!("textarea") => get_constructor!(HTMLTextAreaElementBinding),
local_name!("tfoot") => get_constructor!(HTMLTableSectionElementBinding),
local_name!("th") => get_constructor!(HTMLTableHeaderCellElementBinding),
local_name!("thead") => get_constructor!(HTMLTableSectionElementBinding),
local_name!("time") => get_constructor!(HTMLTimeElementBinding),
local_name!("title") => get_constructor!(HTMLTitleElementBinding),
local_name!("tr") => get_constructor!(HTMLTableRowElementBinding),
local_name!("tt") => get_constructor!(HTMLElementBinding),
local_name!("track") => get_constructor!(HTMLTrackElementBinding),
local_name!("u") => get_constructor!(HTMLElementBinding),
local_name!("ul") => get_constructor!(HTMLUListElementBinding),
local_name!("var") => get_constructor!(HTMLElementBinding),
local_name!("video") => get_constructor!(HTMLVideoElementBinding),
local_name!("wbr") => get_constructor!(HTMLElementBinding),
local_name!("xmp") => get_constructor!(HTMLPreElementBinding),
_ => false,
}
}
| {
"content_hash": "2264f4038fb3cce7403f880003c10971",
"timestamp": "",
"source": "github",
"line_count": 791,
"max_line_length": 120,
"avg_line_length": 46.49557522123894,
"alnum_prop": 0.6296699113600522,
"repo_name": "nrc/rustc-perf",
"id": "5604d33aa290d2dace725af514ae0d7747e602b5",
"size": "36778",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "collector/benchmarks/style-servo/components/script/dom/bindings/interface.rs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1954"
},
{
"name": "HTML",
"bytes": "26683"
},
{
"name": "JavaScript",
"bytes": "41635"
},
{
"name": "Shell",
"bytes": "114"
}
],
"symlink_target": ""
} |
<?php
/**
* Class for manage the database connection
*
* @property MySQLi $connection
*
*/
class Connection {
private $connection;
function __construct($host, $user, $pass, $dataBase) {
if ($dataBase == null) {
$this->connection = new mysqli($host, $user, $pass);
} else {
$this->connection = new mysqli($host, $user, $pass, $dataBase);
}
if ($this->connection->connect_errno) {
echo "Failed connection: " . $this->connection->connect_error;
exit();
}
}
function closeConnection() {
$this->connection->close();
}
function free($query) {
$query->free();
}
function query($query) {
return $this->connection->query($query);
}
function result($query) {
return $query->fetch_array(MYSQLI_ASSOC);
}
function getErrorNum() {
return $this->connection->errno;
}
function getError() {
return $this->connection->error;
}
function getConnection() {
return $this->connection;
}
}
?> | {
"content_hash": "ca7f173de11981f92a49ad0024aef2e5",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 79,
"avg_line_length": 22.946428571428573,
"alnum_prop": 0.4653696498054475,
"repo_name": "decalion/CISADNETWORK",
"id": "195eb1782d987737ce42eeebe788709427f6caf1",
"size": "1285",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "models/classes/Connection.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6256"
},
{
"name": "JavaScript",
"bytes": "6176"
},
{
"name": "PHP",
"bytes": "243645"
}
],
"symlink_target": ""
} |
package org.apache.rocketmq.connect.file;
public class FileConstants {
public static final String FILENAME_FIELD = "filename";
public static final String NEXT_POSITION = "nextPosition";
public static final String FILE_LINE_CONTENT = "fileLineContent";
public static final String LINE = "_line";
public static String getPartition(String filename) {
return filename;
}
}
| {
"content_hash": "4b7d6f03f3d5cbb92edd81b9dd5037ed",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 69,
"avg_line_length": 24,
"alnum_prop": 0.7156862745098039,
"repo_name": "StyleTang/incubator-rocketmq-externals",
"id": "55f6aa7542e704d55b37f4226745bb045a4ed9cf",
"size": "1209",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "rocketmq-connect/rocketmq-connect-sample/src/main/java/org/apache/rocketmq/connect/file/FileConstants.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "768"
},
{
"name": "C",
"bytes": "1804"
},
{
"name": "C++",
"bytes": "1075014"
},
{
"name": "CSS",
"bytes": "60479"
},
{
"name": "Go",
"bytes": "276304"
},
{
"name": "HTML",
"bytes": "86942"
},
{
"name": "Java",
"bytes": "554421"
},
{
"name": "JavaScript",
"bytes": "76515"
},
{
"name": "Makefile",
"bytes": "2349"
},
{
"name": "PHP",
"bytes": "29834"
},
{
"name": "Python",
"bytes": "17496"
},
{
"name": "Scala",
"bytes": "60754"
},
{
"name": "Shell",
"bytes": "2982"
}
],
"symlink_target": ""
} |
package cli
import (
"errors"
"flag"
"reflect"
"strings"
"syscall"
)
// Context is a type that is passed through to
// each Handler action in a cli application. Context
// can be used to retrieve context-specific Args and
// parsed command-line options.
type Context struct {
App *App
Command Command
shellComplete bool
flagSet *flag.FlagSet
setFlags map[string]bool
setArgs map[string]string
parentContext *Context
}
// NewContext creates a new context. For use in when invoking an App or Command action.
func NewContext(app *App, set *flag.FlagSet, parentCtx *Context) *Context {
c := &Context{App: app, flagSet: set, parentContext: parentCtx}
if parentCtx != nil {
c.shellComplete = parentCtx.shellComplete
}
return c
}
// NumFlags returns the number of flags set
func (c *Context) NumFlags() int {
return c.flagSet.NFlag()
}
// Set sets a context flag to a value.
func (c *Context) Set(name, value string) error {
return c.flagSet.Set(name, value)
}
// GlobalSet sets a context flag to a value on the global flagset
func (c *Context) GlobalSet(name, value string) error {
return globalContext(c).flagSet.Set(name, value)
}
// IsSet determines if the flag was actually set
func (c *Context) IsSet(name string) bool {
if c.setFlags == nil {
c.setFlags = make(map[string]bool)
c.flagSet.Visit(func(f *flag.Flag) {
c.setFlags[f.Name] = true
})
c.flagSet.VisitAll(func(f *flag.Flag) {
if _, ok := c.setFlags[f.Name]; ok {
return
}
c.setFlags[f.Name] = false
})
// XXX hack to support IsSet for flags with EnvVar
//
// There isn't an easy way to do this with the current implementation since
// whether a flag was set via an environment variable is very difficult to
// determine here. Instead, we intend to introduce a backwards incompatible
// change in version 2 to add `IsSet` to the Flag interface to push the
// responsibility closer to where the information required to determine
// whether a flag is set by non-standard means such as environment
// variables is avaliable.
//
// See https://github.com/urfave/cli/issues/294 for additional discussion
flags := c.Command.Flags
if c.Command.Name == "" { // cannot == Command{} since it contains slice types
if c.App != nil {
flags = c.App.Flags
}
}
for _, f := range flags {
eachName(f.GetName(), func(name string) {
if isSet, ok := c.setFlags[name]; isSet || !ok {
return
}
val := reflect.ValueOf(f)
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
envVarValue := val.FieldByName("EnvVar")
if !envVarValue.IsValid() {
return
}
eachName(envVarValue.String(), func(envVar string) {
envVar = strings.TrimSpace(envVar)
if _, ok := syscall.Getenv(envVar); ok {
c.setFlags[name] = true
return
}
})
})
}
}
return c.setFlags[name]
}
// GlobalIsSet determines if the global flag was actually set
func (c *Context) GlobalIsSet(name string) bool {
ctx := c
if ctx.parentContext != nil {
ctx = ctx.parentContext
}
for ; ctx != nil; ctx = ctx.parentContext {
if ctx.IsSet(name) {
return true
}
}
return false
}
// FlagNames returns a slice of flag names used in this context.
func (c *Context) FlagNames() (names []string) {
for _, flag := range c.Command.Flags {
name := strings.Split(flag.GetName(), ",")[0]
if name == "help" {
continue
}
names = append(names, name)
}
return
}
// GlobalFlagNames returns a slice of global flag names used by the app.
func (c *Context) GlobalFlagNames() (names []string) {
for _, flag := range c.App.Flags {
name := strings.Split(flag.GetName(), ",")[0]
if name == "help" || name == "version" {
continue
}
names = append(names, name)
}
return
}
// Returns a Named Argument by key
func (c *Context) NamedArg(k string) string {
arg := c.parentContext.setArgs[k]
return arg
}
// Parent returns the parent context, if any
func (c *Context) Parent() *Context {
return c.parentContext
}
// value returns the value of the flag coressponding to `name`
func (c *Context) value(name string) interface{} {
return c.flagSet.Lookup(name).Value.(flag.Getter).Get()
}
// Args contains apps console arguments
type Args []string
// Args returns the command line arguments associated with the context.
func (c *Context) Args() Args {
args := Args(c.flagSet.Args())
return args
}
// NArg returns the number of the command line arguments.
func (c *Context) NArg() int {
return len(c.Args())
}
// Get returns the nth argument, or else a blank string
func (a Args) Get(n int) string {
if len(a) > n {
return a[n]
}
return ""
}
// First returns the first argument, or else a blank string
func (a Args) First() string {
return a.Get(0)
}
// Tail returns the rest of the arguments (not the first one)
// or else an empty string slice
func (a Args) Tail() []string {
if len(a) >= 2 {
return []string(a)[1:]
}
return []string{}
}
// Present checks if there are any arguments present
func (a Args) Present() bool {
return len(a) != 0
}
// Swap swaps arguments at the given indexes
func (a Args) Swap(from, to int) error {
if from >= len(a) || to >= len(a) {
return errors.New("index out of range")
}
a[from], a[to] = a[to], a[from]
return nil
}
func globalContext(ctx *Context) *Context {
if ctx == nil {
return nil
}
for {
if ctx.parentContext == nil {
return ctx
}
ctx = ctx.parentContext
}
}
func lookupGlobalFlagSet(name string, ctx *Context) *flag.FlagSet {
if ctx.parentContext != nil {
ctx = ctx.parentContext
}
for ; ctx != nil; ctx = ctx.parentContext {
if f := ctx.flagSet.Lookup(name); f != nil {
return ctx.flagSet
}
}
return nil
}
func copyFlag(name string, ff *flag.Flag, set *flag.FlagSet) {
switch ff.Value.(type) {
case *StringSlice:
default:
set.Set(name, ff.Value.String())
}
}
func normalizeFlags(flags []Flag, set *flag.FlagSet) error {
visited := make(map[string]bool)
set.Visit(func(f *flag.Flag) {
visited[f.Name] = true
})
for _, f := range flags {
parts := strings.Split(f.GetName(), ",")
if len(parts) == 1 {
continue
}
var ff *flag.Flag
for _, name := range parts {
name = strings.Trim(name, " ")
if visited[name] {
if ff != nil {
return errors.New("Cannot use two forms of the same flag: " + name + " " + ff.Name)
}
ff = set.Lookup(name)
}
}
if ff == nil {
continue
}
for _, name := range parts {
name = strings.Trim(name, " ")
if !visited[name] {
copyFlag(name, ff, set)
}
}
}
return nil
}
| {
"content_hash": "be0874f5ce9b3820092b788629db96bf",
"timestamp": "",
"source": "github",
"line_count": 283,
"max_line_length": 88,
"avg_line_length": 23.300353356890458,
"alnum_prop": 0.6546860782529572,
"repo_name": "murdinc/cli",
"id": "8406b07bcd1732381ab6a683a2654b65dbfa38c7",
"size": "6594",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "context.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "226839"
},
{
"name": "Python",
"bytes": "11112"
},
{
"name": "Shell",
"bytes": "348"
}
],
"symlink_target": ""
} |
package com.siyeh.igtest.abstraction.declare_collection_as_interface;
import java.util.*;
public class DeclareCollectionsAsInterfaceInspection
{
private HashSet<String> m_setThree = new HashSet<String>(2);
private HashSet m_setOne = new HashSet(2);
private Set m_setTwo = new HashSet(2);
public DeclareCollectionsAsInterfaceInspection()
{
m_setOne.add("foo");
m_setTwo.add("bar");
}
public void fooBar()
{
final HashSet set1 = new HashSet(2);
final Set set2 = new HashSet(2);
set1.add("foo");
set2.add("bar");
}
public void fooBaz(TreeSet set1, Set set2)
{
set1.add("foo");
set2.add("bar");
}
public HashSet fooBaz()
{
return new HashSet();
}
void writeContent() {
final HashMap<String, Object> templateMap = new HashMap();
processTemplate(templateMap);
}
void processTemplate(Object o) {}
}
| {
"content_hash": "6efc4b0fffc833a174b8610d5cc39e13",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 69,
"avg_line_length": 22.857142857142858,
"alnum_prop": 0.6135416666666667,
"repo_name": "jexp/idea2",
"id": "efade503f3be25e7ff0baf341a15c96cca7d6fc6",
"size": "960",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "plugins/InspectionGadgets/test/com/siyeh/igtest/abstraction/declare_collection_as_interface/DeclareCollectionsAsInterfaceInspection.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "6350"
},
{
"name": "C#",
"bytes": "103"
},
{
"name": "C++",
"bytes": "30760"
},
{
"name": "Erlang",
"bytes": "10"
},
{
"name": "Java",
"bytes": "72888555"
},
{
"name": "JavaScript",
"bytes": "910"
},
{
"name": "PHP",
"bytes": "133"
},
{
"name": "Perl",
"bytes": "6523"
},
{
"name": "Shell",
"bytes": "4068"
}
],
"symlink_target": ""
} |
package org.mifos.application.accounts.util.helpers;
import org.mifos.application.accounts.business.AccountFeesEntity;
import org.mifos.framework.util.helpers.Money;
public class FeeInstallment {
private Short installmentId;
private Money accountFee;
private AccountFeesEntity accountFeesEntity = null;
public Money getAccountFee() {
return accountFee;
}
public void setAccountFee(Money accountFee) {
this.accountFee = accountFee;
}
public AccountFeesEntity getAccountFeesEntity() {
return accountFeesEntity;
}
public void setAccountFeesEntity(AccountFeesEntity accountFeesEntity) {
this.accountFeesEntity = accountFeesEntity;
}
public Short getInstallmentId() {
return installmentId;
}
public void setInstallmentId(Short installmentId) {
this.installmentId = installmentId;
}
}
| {
"content_hash": "45e98aa95926aa89865bef5be2bf1341",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 75,
"avg_line_length": 24.27027027027027,
"alnum_prop": 0.72271714922049,
"repo_name": "mifos/1.4.x",
"id": "13c2038bd230dcb1ed4b55e9ca7d911cb99d155b",
"size": "1659",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/src/main/java/org/mifos/application/accounts/util/helpers/FeeInstallment.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "12805638"
},
{
"name": "JavaScript",
"bytes": "430899"
},
{
"name": "Python",
"bytes": "45199"
},
{
"name": "Shell",
"bytes": "8682"
}
],
"symlink_target": ""
} |
namespace shaderc_util {
namespace {
// Given a message, deduces and returns its type. If the message type is
// recognized, advances *message past the prefix indicating the type. Otherwise,
// leaves *message unchanged and returns MessageType::Unknown.
MessageType DeduceMessageType(string_piece* message) {
static const char kErrorMessage[] = "ERROR: ";
static const char kWarningMessage[] = "WARNING: ";
static const char kGlobalWarningMessage[] = "Warning, ";
if (message->starts_with(kErrorMessage)) {
*message = message->substr(::strlen(kErrorMessage));
return MessageType::Error;
} else if (message->starts_with(kWarningMessage)) {
*message = message->substr(::strlen(kWarningMessage));
return MessageType::Warning;
} else if (message->starts_with(kGlobalWarningMessage)) {
*message = message->substr(::strlen(kGlobalWarningMessage));
return MessageType::GlobalWarning;
}
return MessageType::Unknown;
}
// Deduces a location specification from the given message. A location
// specification is of the form "<source-name>:<line-number>:". If the deduction
// is successful, returns true and updates source_name and line_number to the
// deduced source name and line numer respectively. The prefix standing for the
// location specification in message is skipped. Otherwise, returns false and
// keeps all parameters untouched.
bool DeduceLocationSpec(string_piece* message, string_piece* source_name,
string_piece* line_number) {
string_piece rest(*message);
const size_t first_colon_pos = rest.find_first_of(':');
if (first_colon_pos == string_piece::npos) return false;
const string_piece source = rest.substr(0, first_colon_pos);
rest = rest.substr(first_colon_pos + 1);
// TODO(antiagainst): we use ':' as a delimiter here. It may be a valid
// character in the filename. Also be aware of other special characters,
// for example, ' '.
const size_t second_colon_pos = rest.find_first_of(':');
if (second_colon_pos == string_piece::npos) return false;
const string_piece line = rest.substr(0, second_colon_pos);
if (!std::all_of(line.begin(), line.end(), ::isdigit)) return false;
*source_name = source;
*line_number = line;
*message = rest.substr(second_colon_pos + 1).strip_whitespace();
return true;
}
// Returns true if the given message is a summary message.
bool IsSummaryMessage(const string_piece& message) {
const size_t space_loc = message.find_first_of(' ');
if (space_loc == string_piece::npos) return false;
const string_piece number = message.substr(0, space_loc);
const string_piece rest = message.substr(space_loc + 1);
if (!std::all_of(number.begin(), number.end(), ::isdigit)) return false;
if (!rest.starts_with("compilation errors.")) return false;
return true;
}
} // anonymous namespace
MessageType ParseGlslangOutput(const string_piece& message,
bool warnings_as_errors, bool suppress_warnings,
string_piece* source_name,
string_piece* line_number, string_piece* rest) {
string_piece rest_of_message(message);
source_name->clear();
line_number->clear();
rest->clear();
// The glslang warning/error messages are typically of the following form:
// <message-type> <location-specification> <message-body>
//
// <message-type> can be "WARNING:", "ERROR:", or "Warning, ". "WARNING:"
// means a warning message for a certain line, while "Warning, " means a
// global one.
//
// <location-specification> is of the form:
// <filename-or-string-number>:<line-number>:
// It doesn't exist if the warning/error message is a global one.
bool is_error = false;
// Handle <message-type>.
switch (DeduceMessageType(&rest_of_message)) {
case MessageType::Warning:
if (suppress_warnings) return MessageType::Ignored;
break;
case MessageType::Error:
is_error = true;
break;
case MessageType::GlobalWarning:
if (suppress_warnings) return MessageType::Ignored;
*rest = rest_of_message;
return warnings_as_errors ? MessageType::GlobalError
: MessageType::GlobalWarning;
case MessageType::Unknown:
*rest = rest_of_message;
return MessageType::Unknown;
default:
break;
}
rest_of_message = rest_of_message.strip_whitespace();
if (rest_of_message.empty()) return MessageType::Unknown;
// Now we have stripped the <message-type>. Try to see if we can find
// a <location-specification>.
if (DeduceLocationSpec(&rest_of_message, source_name, line_number)) {
*rest = rest_of_message;
return (is_error || warnings_as_errors) ? MessageType::Error
: MessageType::Warning;
} else {
// No <location-specification>. This is a global warning/error message.
// A special kind of global message is summary message, which should
// start with a number.
*rest = rest_of_message;
if (IsSummaryMessage(rest_of_message)) {
return (is_error || warnings_as_errors) ? MessageType::ErrorSummary
: MessageType::WarningSummary;
}
return (is_error || warnings_as_errors) ? MessageType::GlobalError
: MessageType::GlobalWarning;
}
return MessageType::Unknown;
}
bool PrintFilteredErrors(const string_piece& file_name,
std::ostream* error_stream, bool warnings_as_errors,
bool suppress_warnings, const char* error_list,
size_t* total_warnings, size_t* total_errors) {
const char* ignored_error_strings[] = {
"Warning, version 310 is not yet complete; most version-specific "
"features are present, but some are missing.",
"Warning, version 400 is not yet complete; most version-specific "
"features are present, but some are missing.",
"Warning, version 410 is not yet complete; most version-specific "
"features are present, but some are missing.",
"Warning, version 420 is not yet complete; most version-specific "
"features are present, but some are missing.",
"Warning, version 430 is not yet complete; most version-specific "
"features are present, but some are missing.",
"Warning, version 440 is not yet complete; most version-specific "
"features are present, but some are missing.",
"Warning, version 450 is not yet complete; most version-specific "
"features are present, but some are missing.",
"Linked vertex stage:", "Linked fragment stage:",
"Linked tessellation control stage:",
"Linked tessellation evaluation stage:", "Linked geometry stage:",
"Linked compute stage:", ""};
size_t existing_total_errors = *total_errors;
string_piece error_messages(error_list);
for (const string_piece& message : error_messages.get_fields('\n')) {
if (std::find(std::begin(ignored_error_strings),
std::end(ignored_error_strings),
message) == std::end(ignored_error_strings)) {
string_piece source_name;
string_piece line_number;
string_piece rest;
const MessageType type =
ParseGlslangOutput(message, warnings_as_errors, suppress_warnings,
&source_name, &line_number, &rest);
string_piece name = file_name;
if (!source_name.empty()) {
// -1 is the string number for the preamble injected by us.
name = source_name == "-1" ? "<command line>" : source_name;
}
switch (type) {
case MessageType::Error:
case MessageType::Warning:
*error_stream << name << ":";
assert(!source_name.empty() && !line_number.empty() && !rest.empty());
*error_stream << line_number << ": "
<< (type == MessageType::Error ? "error: "
: "warning: ")
<< rest.strip_whitespace() << std::endl;
*total_errors += type == MessageType::Error;
*total_warnings += type == MessageType::Warning;
break;
case MessageType::ErrorSummary:
case MessageType::WarningSummary:
break;
case MessageType::GlobalError:
case MessageType::GlobalWarning:
assert(!rest.empty());
*total_errors += type == MessageType::GlobalError;
*total_warnings += type == MessageType::GlobalWarning;
*error_stream << name << ": "
<< (type == MessageType::GlobalError ? "error"
: "warning")
<< ": " << rest.strip_whitespace() << std::endl;
break;
case MessageType::Unknown:
*error_stream << name << ":";
*error_stream << " " << message << std::endl;
break;
case MessageType::Ignored:
break;
}
}
}
return (existing_total_errors == *total_errors);
}
// Outputs the number of warnings and errors if there are any.
void OutputMessages(std::ostream* error_stream, size_t total_warnings,
size_t total_errors) {
if (total_warnings > 0 || total_errors > 0) {
if (total_warnings > 0 && total_errors > 0) {
*error_stream << total_warnings << " warning"
<< (total_warnings > 1 ? "s" : "") << " and "
<< total_errors << " error" << (total_errors > 1 ? "s" : "")
<< " generated." << std::endl;
} else if (total_warnings > 0) {
*error_stream << total_warnings << " warning"
<< (total_warnings > 1 ? "s" : "") << " generated."
<< std::endl;
} else if (total_errors > 0) {
*error_stream << total_errors << " error" << (total_errors > 1 ? "s" : "")
<< " generated." << std::endl;
}
}
}
} // namespace glslc
| {
"content_hash": "02c40492b6ce32d1cbcfabedca9f7957",
"timestamp": "",
"source": "github",
"line_count": 231,
"max_line_length": 80,
"avg_line_length": 43.41991341991342,
"alnum_prop": 0.6139581256231306,
"repo_name": "davidlee80/shaderc",
"id": "5e7f2b8b0c1145a39e738ccb3987e23e52e7e0fc",
"size": "10768",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "libshaderc_util/src/message.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "8480"
},
{
"name": "C++",
"bytes": "178477"
},
{
"name": "CMake",
"bytes": "11433"
},
{
"name": "Groff",
"bytes": "43"
},
{
"name": "Python",
"bytes": "149345"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<!--
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.
-->
<metainfo>
<schemaVersion>2.0</schemaVersion>
<services>
<service>
<name>MAHOUT</name>
<extends>common-services/MAHOUT/1.0.0.2.3</extends>
</service>
</services>
</metainfo> | {
"content_hash": "66225e6faf9a4eae462e93d6724c9451",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 75,
"avg_line_length": 40.26923076923077,
"alnum_prop": 0.7125119388729704,
"repo_name": "zouzhberk/ambaridemo",
"id": "6c4ef96059187dd386f59af18f4b1729d25a1fe2",
"size": "1047",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "demo-server/src/main/resources/stacks/HDP/2.3.GlusterFS/services/MAHOUT/metainfo.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5982"
},
{
"name": "Groff",
"bytes": "13935"
},
{
"name": "HTML",
"bytes": "52"
},
{
"name": "Java",
"bytes": "8681846"
},
{
"name": "PLSQL",
"bytes": "2160"
},
{
"name": "PLpgSQL",
"bytes": "105599"
},
{
"name": "PowerShell",
"bytes": "43170"
},
{
"name": "Python",
"bytes": "2751909"
},
{
"name": "Ruby",
"bytes": "9652"
},
{
"name": "SQLPL",
"bytes": "2117"
},
{
"name": "Shell",
"bytes": "247846"
}
],
"symlink_target": ""
} |
package pdp
import (
"fmt"
)
type functionSetOfStringsLen struct {
e Expression
}
func makeFunctionSetOfStringsLen(e Expression) Expression {
return functionSetOfStringsLen{e: e}
}
func makeFunctionSetOfStringsLenAlt(args []Expression) Expression {
if len(args) != 1 {
panic(fmt.Errorf("function \"len\" for Set of Strings needs exactly one arguments but got %d", len(args)))
}
return makeFunctionSetOfStringsLen(args[0])
}
func (f functionSetOfStringsLen) GetResultType() Type {
return TypeInteger
}
func (f functionSetOfStringsLen) describe() string {
return "len"
}
// Calculate implements Expression interface and returns calculated value
func (f functionSetOfStringsLen) Calculate(ctx *Context) (AttributeValue, error) {
set, err := ctx.calculateSetOfStringsExpression(f.e)
if err != nil {
return UndefinedValue, bindError(bindError(err, "argument"), f.describe())
}
l := 0
for range set.Enumerate() {
l++
}
return MakeIntegerValue(int64(l)), nil
}
func functionSetOfStringsLenValidator(args []Expression) functionMaker {
if len(args) != 1 || args[0].GetResultType() != TypeSetOfStrings {
return nil
}
return makeFunctionSetOfStringsLenAlt
}
| {
"content_hash": "e5ab3642b2959d2581c1cbdf34ab545a",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 108,
"avg_line_length": 23.66,
"alnum_prop": 0.7489433643279797,
"repo_name": "vasili-v/themis",
"id": "7a4d6d7db4f31a34b085e29ef3e06d10e1444805",
"size": "1183",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "pdp/expr_stringset_len.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "2052861"
},
{
"name": "Makefile",
"bytes": "7892"
},
{
"name": "Shell",
"bytes": "46"
}
],
"symlink_target": ""
} |
Shindo.tests("Fog::Compute[:aws] | security_group", ['aws']) do
model_tests(Fog::Compute[:aws].security_groups, {:description => 'foggroupdescription', :name => 'foggroupname'}, true)
tests("authorize and revoke helpers") do
@group = Fog::Compute[:aws].security_groups.create(:name => "foggroup", :description => "fog group desc")
@other_group = Fog::Compute[:aws].security_groups.create(:name => 'fog other group', :description => 'another fog group')
@other_group.reload
@other_user_id = Fog::AWS::Mock.owner_id
@other_users_group_id = Fog::AWS::Mock.security_group_id
test("authorize access by another security group") do
@group.authorize_group_and_owner(@other_group.name)
@group.reload
@group.ip_permissions.size == 3
end
test("revoke access from another security group") do
@group.revoke_group_and_owner(@other_group.name)
@group.reload
@group.ip_permissions.empty?
end
test("authorize access to a port range") do
@group.authorize_port_range(5000..6000)
@group.reload
@group.ip_permissions.size == 1
end
test("revoke access to a port range") do
@group.revoke_port_range(5000..6000)
@group.reload
@group.ip_permissions.empty?
end
test("authorize access at a port range (egress rule)") do
@group.authorize_port_range(5000..6000, :direction => 'egress')
@group.reload
ip_permission_egress = @group.ip_permissions_egress.find do |permission|
permission['fromPort'] == 5000 &&
permission['toPort'] == 6000 &&
permission['ipProtocol'] == 'tcp' &&
permission['ipRanges'] == [{ 'cidrIp' => '0.0.0.0/0' }]
end
!ip_permission_egress.nil?
end
test("revoke access at a port range (egress rule)") do
@group.revoke_port_range(5000..6000, :direction => 'egress')
@group.reload
ip_permission_egress = @group.ip_permissions_egress.find do |permission|
permission['fromPort'] == 5000 &&
permission['toPort'] == 6000 &&
permission['ipProtocol'] == 'tcp' &&
permission['ipRanges'] == [{ 'cidrIp' => '0.0.0.0/0' }]
end
ip_permission_egress.nil?
end
group_forms = [
"#{@other_group.owner_id}:#{@other_group.group_id}", # deprecated form
@other_group.group_id,
{@other_group.owner_id => @other_group.group_id},
]
group_forms.each do |group_arg|
test("authorize port range access by another security group #{group_arg.inspect}") do
@other_group.reload
@group.authorize_port_range(5000..6000, {:group => group_arg})
@group.reload
@group.ip_permissions.size == 1
end
test("revoke port range access by another security group") do
@other_group.reload
@group.revoke_port_range(5000..6000, {:group => group_arg})
@group.reload
@group.ip_permissions.empty?
end
end
[
{ @other_user_id => @other_users_group_id }
].each do |group_arg|
test("does not authorize port range access by an invalid security group #{group_arg.inspect}") do
raises(Fog::Compute::AWS::NotFound, "The security group '#{@other_users_group_id}' does not exist") {
@other_group.reload
@group.authorize_port_range(5000..6000, {:group => group_arg})
}
end
end
@other_group.destroy
@group.destroy
end
end
| {
"content_hash": "a8bd182fe81ad6427600e1edbd1d4d77",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 125,
"avg_line_length": 35.08163265306123,
"alnum_prop": 0.6183827806864456,
"repo_name": "puneetloya/fog-aws",
"id": "8d31dfc758dc42459b72e675ec2eeee22b171971",
"size": "3438",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "tests/models/compute/security_group_tests.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Groff",
"bytes": "226"
},
{
"name": "JavaScript",
"bytes": "635"
},
{
"name": "Ruby",
"bytes": "3203234"
}
],
"symlink_target": ""
} |
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Holds the PhpMyAdmin\Controllers\Table\TableSearchController
*
* @package PhpMyAdmin\Controllers
*/
namespace PhpMyAdmin\Controllers\Table;
use PhpMyAdmin\Controllers\TableController;
use PhpMyAdmin\Core;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Relation;
use PhpMyAdmin\Sql;
use PhpMyAdmin\Template;
use PhpMyAdmin\Util;
/**
* Class TableSearchController
*
* @package PhpMyAdmin\Controllers
*/
class TableSearchController extends TableController
{
/**
* Normal search or Zoom search
*
* @access private
* @var string
*/
private $_searchType;
/**
* Names of columns
*
* @access private
* @var array
*/
private $_columnNames;
/**
* Types of columns
*
* @access private
* @var array
*/
private $_columnTypes;
/**
* Collations of columns
*
* @access private
* @var array
*/
private $_columnCollations;
/**
* Null Flags of columns
*
* @access private
* @var array
*/
private $_columnNullFlags;
/**
* Whether a geometry column is present
*
* @access private
* @var boolean
*/
private $_geomColumnFlag;
/**
* Foreign Keys
*
* @access private
* @var array
*/
private $_foreigners;
/**
* Connection charset
*
* @access private
* @var string
*/
private $_connectionCharSet;
protected $url_query;
/**
* @var Relation $relation
*/
private $relation;
/**
* Constructor
*
* @param string $searchType Search type
* @param string $url_query URL query
*/
public function __construct(
$response,
$dbi,
$db,
$table,
$searchType,
$url_query
) {
parent::__construct($response, $dbi, $db, $table);
$this->url_query = $url_query;
$this->_searchType = $searchType;
$this->_columnNames = array();
$this->_columnNullFlags = array();
$this->_columnTypes = array();
$this->_columnCollations = array();
$this->_geomColumnFlag = false;
$this->_foreigners = array();
$this->relation = new Relation();
// Loads table's information
$this->_loadTableInfo();
$this->_connectionCharSet = $this->dbi->fetchValue(
"SELECT @@character_set_connection"
);
}
/**
* Gets all the columns of a table along with their types, collations
* and whether null or not.
*
* @return void
*/
private function _loadTableInfo()
{
// Gets the list and number of columns
$columns = $this->dbi->getColumns(
$this->db, $this->table, null, true
);
// Get details about the geometry functions
$geom_types = Util::getGISDatatypes();
foreach ($columns as $row) {
// set column name
$this->_columnNames[] = $row['Field'];
$type = $row['Type'];
// check whether table contains geometric columns
if (in_array($type, $geom_types)) {
$this->_geomColumnFlag = true;
}
// reformat mysql query output
if (strncasecmp($type, 'set', 3) == 0
|| strncasecmp($type, 'enum', 4) == 0
) {
$type = str_replace(',', ', ', $type);
} else {
// strip the "BINARY" attribute, except if we find "BINARY(" because
// this would be a BINARY or VARBINARY column type
if (! preg_match('@BINARY[\(]@i', $type)) {
$type = preg_replace('@BINARY@i', '', $type);
}
$type = preg_replace('@ZEROFILL@i', '', $type);
$type = preg_replace('@UNSIGNED@i', '', $type);
$type = mb_strtolower($type);
}
if (empty($type)) {
$type = ' ';
}
$this->_columnTypes[] = $type;
$this->_columnNullFlags[] = $row['Null'];
$this->_columnCollations[]
= ! empty($row['Collation']) && $row['Collation'] != 'NULL'
? $row['Collation']
: '';
} // end for
// Retrieve foreign keys
$this->_foreigners = $this->relation->getForeigners($this->db, $this->table);
}
/**
* Index action
*
* @return void
*/
public function indexAction()
{
switch ($this->_searchType) {
case 'replace':
if (isset($_POST['find'])) {
$this->findAction();
return;
}
$this->response
->getHeader()
->getScripts()
->addFile('tbl_find_replace.js');
if (isset($_POST['replace'])) {
$this->replaceAction();
}
// Displays the find and replace form
$this->displaySelectionFormAction();
break;
case 'normal':
$this->response->getHeader()
->getScripts()
->addFiles(
array(
'makegrid.js',
'sql.js',
'tbl_select.js',
'tbl_change.js',
'vendor/jquery/jquery.uitablefilter.js',
'gis_data_editor.js',
)
);
if (isset($_POST['range_search'])) {
$this->rangeSearchAction();
return;
}
/**
* No selection criteria received -> display the selection form
*/
if (!isset($_POST['columnsToDisplay'])
&& !isset($_POST['displayAllColumns'])
) {
$this->displaySelectionFormAction();
} else {
$this->doSelectionAction();
}
break;
case 'zoom':
$this->response->getHeader()
->getScripts()
->addFiles(
array(
'makegrid.js',
'sql.js',
'vendor/jqplot/jquery.jqplot.js',
'vendor/jqplot/plugins/jqplot.canvasTextRenderer.js',
'vendor/jqplot/plugins/jqplot.canvasAxisLabelRenderer.js',
'vendor/jqplot/plugins/jqplot.dateAxisRenderer.js',
'vendor/jqplot/plugins/jqplot.highlighter.js',
'vendor/jqplot/plugins/jqplot.cursor.js',
'tbl_zoom_plot_jqplot.js',
'tbl_change.js',
)
);
/**
* Handle AJAX request for data row on point select
*
* @var boolean Object containing parameters for the POST request
*/
if (isset($_POST['get_data_row'])
&& $_POST['get_data_row'] == true
) {
$this->getDataRowAction();
return;
}
/**
* Handle AJAX request for changing field information
* (value,collation,operators,field values) in input form
*
* @var boolean Object containing parameters for the POST request
*/
if (isset($_POST['change_tbl_info'])
&& $_POST['change_tbl_info'] == true
) {
$this->changeTableInfoAction();
return;
}
//Set default datalabel if not selected
if (!isset($_POST['zoom_submit']) || $_POST['dataLabel'] == '') {
$dataLabel = $this->relation->getDisplayField($this->db, $this->table);
} else {
$dataLabel = $_POST['dataLabel'];
}
// Displays the zoom search form
$this->displaySelectionFormAction($dataLabel);
/*
* Handle the input criteria and generate the query result
* Form for displaying query results
*/
if (isset($_POST['zoom_submit'])
&& $_POST['criteriaColumnNames'][0] != 'pma_null'
&& $_POST['criteriaColumnNames'][1] != 'pma_null'
&& $_POST['criteriaColumnNames'][0] != $_POST['criteriaColumnNames'][1]
) {
if (! isset($goto)) {
$goto = Util::getScriptNameForOption(
$GLOBALS['cfg']['DefaultTabTable'], 'table'
);
}
$this->zoomSubmitAction($dataLabel, $goto);
}
break;
}
}
/**
* Zoom submit action
*
* @param string $dataLabel Data label
* @param string $goto Goto
*
* @return void
*/
public function zoomSubmitAction($dataLabel, $goto)
{
//Query generation part
$sql_query = $this->_buildSqlQuery();
$sql_query .= ' LIMIT ' . $_POST['maxPlotLimit'];
//Query execution part
$result = $this->dbi->query(
$sql_query . ";",
DatabaseInterface::CONNECT_USER,
DatabaseInterface::QUERY_STORE
);
$fields_meta = $this->dbi->getFieldsMeta($result);
$data = array();
while ($row = $this->dbi->fetchAssoc($result)) {
//Need a row with indexes as 0,1,2 for the getUniqueCondition
// hence using a temporary array
$tmpRow = array();
foreach ($row as $val) {
$tmpRow[] = $val;
}
//Get unique condition on each row (will be needed for row update)
$uniqueCondition = Util::getUniqueCondition(
$result, // handle
count($this->_columnNames), // fields_cnt
$fields_meta, // fields_meta
$tmpRow, // row
true, // force_unique
false, // restrict_to_table
null // analyzed_sql_results
);
//Append it to row array as where_clause
$row['where_clause'] = $uniqueCondition[0];
$row['where_clause_sign'] = Core::signSqlQuery($uniqueCondition[0]);
$tmpData = array(
$_POST['criteriaColumnNames'][0] =>
$row[$_POST['criteriaColumnNames'][0]],
$_POST['criteriaColumnNames'][1] =>
$row[$_POST['criteriaColumnNames'][1]],
'where_clause' => $uniqueCondition[0],
'where_clause_sign' => Core::signSqlQuery($uniqueCondition[0])
);
$tmpData[$dataLabel] = ($dataLabel) ? $row[$dataLabel] : '';
$data[] = $tmpData;
}
unset($tmpData);
//Displays form for point data and scatter plot
$titles = array(
'Browse' => Util::getIcon(
'b_browse',
__('Browse foreign values')
)
);
$this->response->addHTML(
Template::get('table/search/zoom_result_form')->render([
'db' => $this->db,
'table' => $this->table,
'column_names' => $this->_columnNames,
'foreigners' => $this->_foreigners,
'column_null_flags' => $this->_columnNullFlags,
'column_types' => $this->_columnTypes,
'titles' => $titles,
'goto' => $goto,
'data' => $data,
'data_json' => json_encode($data),
'zoom_submit' => isset($_POST['zoom_submit']),
'foreign_max_limit' => $GLOBALS['cfg']['ForeignKeyMaxLimit'],
])
);
}
/**
* Change table info action
*
* @return void
*/
public function changeTableInfoAction()
{
$field = $_POST['field'];
if ($field == 'pma_null') {
$this->response->addJSON('field_type', '');
$this->response->addJSON('field_collation', '');
$this->response->addJSON('field_operators', '');
$this->response->addJSON('field_value', '');
return;
}
$key = array_search($field, $this->_columnNames);
$search_index
= ((isset($_POST['it']) && is_numeric($_POST['it']))
? intval($_POST['it']) : 0);
$properties = $this->getColumnProperties($search_index, $key);
$this->response->addJSON(
'field_type', htmlspecialchars($properties['type'])
);
$this->response->addJSON('field_collation', $properties['collation']);
$this->response->addJSON('field_operators', $properties['func']);
$this->response->addJSON('field_value', $properties['value']);
}
/**
* Get data row action
*
* @return void
*/
public function getDataRowAction()
{
if (! Core::checkSqlQuerySignature($_POST['where_clause'], $_POST['where_clause_sign'])) {
return;
}
$extra_data = array();
$row_info_query = 'SELECT * FROM ' . Util::backquote($_POST['db']) . '.'
. Util::backquote($_POST['table']) . ' WHERE ' . $_POST['where_clause'];
$result = $this->dbi->query(
$row_info_query . ";",
DatabaseInterface::CONNECT_USER,
DatabaseInterface::QUERY_STORE
);
$fields_meta = $this->dbi->getFieldsMeta($result);
while ($row = $this->dbi->fetchAssoc($result)) {
// for bit fields we need to convert them to printable form
$i = 0;
foreach ($row as $col => $val) {
if ($fields_meta[$i]->type == 'bit') {
$row[$col] = Util::printableBitValue(
$val, $fields_meta[$i]->length
);
}
$i++;
}
$extra_data['row_info'] = $row;
}
$this->response->addJSON($extra_data);
}
/**
* Do selection action
*
* @return void
*/
public function doSelectionAction()
{
/**
* Selection criteria have been submitted -> do the work
*/
$sql_query = $this->_buildSqlQuery();
/**
* Add this to ensure following procedures included running correctly.
*/
$db = $this->db;
$sql = new Sql();
$sql->executeQueryAndSendQueryResponse(
null, // analyzed_sql_results
false, // is_gotofile
$this->db, // db
$this->table, // table
null, // find_real_end
null, // sql_query_for_bookmark
null, // extra_data
null, // message_to_show
null, // message
null, // sql_data
$GLOBALS['goto'], // goto
$GLOBALS['pmaThemeImage'], // pmaThemeImage
null, // disp_query
null, // disp_message
null, // query_type
$sql_query, // sql_query
null, // selectedTables
null // complete_query
);
}
/**
* Display selection form action
*
* @param string $dataLabel Data label
*
* @return void
*/
public function displaySelectionFormAction($dataLabel = null)
{
$this->url_query .= '&goto=tbl_select.php&back=tbl_select.php';
if (! isset($goto)) {
$goto = Util::getScriptNameForOption(
$GLOBALS['cfg']['DefaultTabTable'], 'table'
);
}
// Displays the table search form
$this->response->addHTML(
Template::get('secondary_tabs')
->render(
array(
'url_params' => array(
'db' => $this->db,
'table' => $this->table,
),
'sub_tabs' => $this->_getSubTabs(),
)
)
);
$this->response->addHTML(
Template::get('table/search/selection_form')->render(array(
'search_type' => $this->_searchType,
'db' => $this->db,
'table' => $this->table,
'goto' => $goto,
'self' => $this,
'geom_column_flag' => $this->_geomColumnFlag,
'column_names' => $this->_columnNames,
'column_types' => $this->_columnTypes,
'column_collations' => $this->_columnCollations,
'data_label' => $dataLabel,
'criteria_column_names' => isset($_POST['criteriaColumnNames']) ? $_POST['criteriaColumnNames'] : null,
'criteria_column_types' => isset($_POST['criteriaColumnTypes']) ? $_POST['criteriaColumnTypes'] : null,
'sql_types' => $GLOBALS['dbi']->types,
'max_rows' => intval($GLOBALS['cfg']['MaxRows']),
'max_plot_limit' => ((! empty($_POST['maxPlotLimit']))
? intval($_POST['maxPlotLimit'])
: intval($GLOBALS['cfg']['maxRowPlotLimit'])),
))
);
}
/**
* Range search action
*
* @return void
*/
public function rangeSearchAction()
{
$min_max = $this->getColumnMinMax($_POST['column']);
$this->response->addJSON('column_data', $min_max);
}
/**
* Find action
*
* @return void
*/
public function findAction()
{
$useRegex = array_key_exists('useRegex', $_POST)
&& $_POST['useRegex'] == 'on';
$preview = $this->getReplacePreview(
$_POST['columnIndex'],
$_POST['find'],
$_POST['replaceWith'],
$useRegex,
$this->_connectionCharSet
);
$this->response->addJSON('preview', $preview);
}
/**
* Replace action
*
* @return void
*/
public function replaceAction()
{
$this->replace(
$_POST['columnIndex'],
$_POST['findString'],
$_POST['replaceWith'],
$_POST['useRegex'],
$this->_connectionCharSet
);
$this->response->addHTML(
Util::getMessage(
__('Your SQL query has been executed successfully.'),
null, 'success'
)
);
}
/**
* Returns HTML for previewing strings found and their replacements
*
* @param int $columnIndex index of the column
* @param string $find string to find in the column
* @param string $replaceWith string to replace with
* @param boolean $useRegex to use Regex replace or not
* @param string $charSet character set of the connection
*
* @return string HTML for previewing strings found and their replacements
*/
function getReplacePreview(
$columnIndex, $find, $replaceWith, $useRegex, $charSet
) {
$column = $this->_columnNames[$columnIndex];
if ($useRegex) {
$result = $this->_getRegexReplaceRows(
$columnIndex, $find, $replaceWith, $charSet
);
} else {
$sql_query = "SELECT "
. Util::backquote($column) . ","
. " REPLACE("
. Util::backquote($column) . ", '" . $find . "', '"
. $replaceWith
. "'),"
. " COUNT(*)"
. " FROM " . Util::backquote($this->db)
. "." . Util::backquote($this->table)
. " WHERE " . Util::backquote($column)
. " LIKE '%" . $find . "%' COLLATE " . $charSet . "_bin"; // here we
// change the collation of the 2nd operand to a case sensitive
// binary collation to make sure that the comparison
// is case sensitive
$sql_query .= " GROUP BY " . Util::backquote($column)
. " ORDER BY " . Util::backquote($column) . " ASC";
$result = $this->dbi->fetchResult($sql_query, 0);
}
return Template::get('table/search/replace_preview')->render(
array(
'db' => $this->db,
'table' => $this->table,
'column_index' => $columnIndex,
'find' => $find,
'replace_with' => $replaceWith,
'use_regex' => $useRegex,
'result' => $result
)
);
}
/**
* Finds and returns Regex pattern and their replacements
*
* @param int $columnIndex index of the column
* @param string $find string to find in the column
* @param string $replaceWith string to replace with
* @param string $charSet character set of the connection
*
* @return array Array containing original values, replaced values and count
*/
private function _getRegexReplaceRows(
$columnIndex, $find, $replaceWith, $charSet
) {
$column = $this->_columnNames[$columnIndex];
$sql_query = "SELECT "
. Util::backquote($column) . ","
. " 1," // to add an extra column that will have replaced value
. " COUNT(*)"
. " FROM " . Util::backquote($this->db)
. "." . Util::backquote($this->table)
. " WHERE " . Util::backquote($column)
. " RLIKE '" . $GLOBALS['dbi']->escapeString($find) . "' COLLATE "
. $charSet . "_bin"; // here we
// change the collation of the 2nd operand to a case sensitive
// binary collation to make sure that the comparison is case sensitive
$sql_query .= " GROUP BY " . Util::backquote($column)
. " ORDER BY " . Util::backquote($column) . " ASC";
$result = $this->dbi->fetchResult($sql_query, 0);
if (is_array($result)) {
/* Iterate over possible delimiters to get one */
$delimiters = array('/', '@', '#', '~', '!', '$', '%', '^', '&', '_');
$found = false;
for ($i = 0, $l = count($delimiters); $i < $l; $i++) {
if (strpos($find, $delimiters[$i]) === false) {
$found = true;
break;
}
}
if (! $found) {
return false;
}
$find = $delimiters[$i] . $find . $delimiters[$i];
foreach ($result as $index=>$row) {
$result[$index][1] = preg_replace(
$find,
$replaceWith,
$row[0]
);
}
}
return $result;
}
/**
* Replaces a given string in a column with a give replacement
*
* @param int $columnIndex index of the column
* @param string $find string to find in the column
* @param string $replaceWith string to replace with
* @param boolean $useRegex to use Regex replace or not
* @param string $charSet character set of the connection
*
* @return void
*/
public function replace($columnIndex, $find, $replaceWith, $useRegex,
$charSet
) {
$column = $this->_columnNames[$columnIndex];
if ($useRegex) {
$toReplace = $this->_getRegexReplaceRows(
$columnIndex, $find, $replaceWith, $charSet
);
$sql_query = "UPDATE " . Util::backquote($this->table)
. " SET " . Util::backquote($column) . " = CASE";
if (is_array($toReplace)) {
foreach ($toReplace as $row) {
$sql_query .= "\n WHEN " . Util::backquote($column)
. " = '" . $GLOBALS['dbi']->escapeString($row[0])
. "' THEN '" . $GLOBALS['dbi']->escapeString($row[1]) . "'";
}
}
$sql_query .= " END"
. " WHERE " . Util::backquote($column)
. " RLIKE '" . $GLOBALS['dbi']->escapeString($find) . "' COLLATE "
. $charSet . "_bin"; // here we
// change the collation of the 2nd operand to a case sensitive
// binary collation to make sure that the comparison
// is case sensitive
} else {
$sql_query = "UPDATE " . Util::backquote($this->table)
. " SET " . Util::backquote($column) . " ="
. " REPLACE("
. Util::backquote($column) . ", '" . $find . "', '"
. $replaceWith
. "')"
. " WHERE " . Util::backquote($column)
. " LIKE '%" . $find . "%' COLLATE " . $charSet . "_bin"; // here we
// change the collation of the 2nd operand to a case sensitive
// binary collation to make sure that the comparison
// is case sensitive
}
$this->dbi->query(
$sql_query,
DatabaseInterface::CONNECT_USER,
DatabaseInterface::QUERY_STORE
);
$GLOBALS['sql_query'] = $sql_query;
}
/**
* Finds minimum and maximum value of a given column.
*
* @param string $column Column name
*
* @return array
*/
public function getColumnMinMax($column)
{
$sql_query = 'SELECT MIN(' . Util::backquote($column) . ') AS `min`, '
. 'MAX(' . Util::backquote($column) . ') AS `max` '
. 'FROM ' . Util::backquote($this->db) . '.'
. Util::backquote($this->table);
$result = $this->dbi->fetchSingleRow($sql_query);
return $result;
}
/**
* Returns an array with necessary configurations to create
* sub-tabs in the table_select page.
*
* @return array Array containing configuration (icon, text, link, id, args)
* of sub-tabs
*/
private function _getSubTabs()
{
$subtabs = array();
$subtabs['search']['icon'] = 'b_search';
$subtabs['search']['text'] = __('Table search');
$subtabs['search']['link'] = 'tbl_select.php';
$subtabs['search']['id'] = 'tbl_search_id';
$subtabs['search']['args']['pos'] = 0;
$subtabs['zoom']['icon'] = 'b_select';
$subtabs['zoom']['link'] = 'tbl_zoom_select.php';
$subtabs['zoom']['text'] = __('Zoom search');
$subtabs['zoom']['id'] = 'zoom_search_id';
$subtabs['replace']['icon'] = 'b_find_replace';
$subtabs['replace']['link'] = 'tbl_find_replace.php';
$subtabs['replace']['text'] = __('Find and replace');
$subtabs['replace']['id'] = 'find_replace_id';
return $subtabs;
}
/**
* Builds the sql search query from the post parameters
*
* @return string the generated SQL query
*/
private function _buildSqlQuery()
{
$sql_query = 'SELECT ';
// If only distinct values are needed
$is_distinct = (isset($_POST['distinct'])) ? 'true' : 'false';
if ($is_distinct == 'true') {
$sql_query .= 'DISTINCT ';
}
// if all column names were selected to display, we do a 'SELECT *'
// (more efficient and this helps prevent a problem in IE
// if one of the rows is edited and we come back to the Select results)
if (isset($_POST['zoom_submit']) || ! empty($_POST['displayAllColumns'])) {
$sql_query .= '* ';
} else {
$sql_query .= implode(
', ',
Util::backquote($_POST['columnsToDisplay'])
);
} // end if
$sql_query .= ' FROM '
. Util::backquote($_POST['table']);
$whereClause = $this->_generateWhereClause();
$sql_query .= $whereClause;
// if the search results are to be ordered
if (isset($_POST['orderByColumn']) && $_POST['orderByColumn'] != '--nil--') {
$sql_query .= ' ORDER BY '
. Util::backquote($_POST['orderByColumn'])
. ' ' . $_POST['order'];
} // end if
return $sql_query;
}
/**
* Provides a column's type, collation, operators list, and criteria value
* to display in table search form
*
* @param integer $search_index Row number in table search form
* @param integer $column_index Column index in ColumnNames array
*
* @return array Array containing column's properties
*/
public function getColumnProperties($search_index, $column_index)
{
$selected_operator = (isset($_POST['criteriaColumnOperators'][$search_index])
? $_POST['criteriaColumnOperators'][$search_index] : '');
$entered_value = (isset($_POST['criteriaValues'])
? $_POST['criteriaValues'] : '');
$titles = array(
'Browse' => Util::getIcon(
'b_browse', __('Browse foreign values')
)
);
//Gets column's type and collation
$type = $this->_columnTypes[$column_index];
$collation = $this->_columnCollations[$column_index];
//Gets column's comparison operators depending on column type
$typeOperators = $GLOBALS['dbi']->types->getTypeOperatorsHtml(
preg_replace('@\(.*@s', '', $this->_columnTypes[$column_index]),
$this->_columnNullFlags[$column_index], $selected_operator
);
$func = Template::get('table/search/column_comparison_operators')->render(
array(
'search_index' => $search_index,
'type_operators' => $typeOperators
)
);
//Gets link to browse foreign data(if any) and criteria inputbox
$foreignData = $this->relation->getForeignData(
$this->_foreigners, $this->_columnNames[$column_index], false, '', ''
);
$value = Template::get('table/search/input_box')->render(
array(
'str' => '',
'column_type' => (string) $type,
'column_id' => 'fieldID_',
'in_zoom_search_edit' => false,
'foreigners' => $this->_foreigners,
'column_name' => $this->_columnNames[$column_index],
'column_name_hash' => md5($this->_columnNames[$column_index]),
'foreign_data' => $foreignData,
'table' => $this->table,
'column_index' => $search_index,
'foreign_max_limit' => $GLOBALS['cfg']['ForeignKeyMaxLimit'],
'criteria_values' => $entered_value,
'db' => $this->db,
'titles' => $titles,
'in_fbs' => true
)
);
return array(
'type' => $type,
'collation' => $collation,
'func' => $func,
'value' => $value
);
}
/**
* Generates the where clause for the SQL search query to be executed
*
* @return string the generated where clause
*/
private function _generateWhereClause()
{
if (isset($_POST['customWhereClause'])
&& trim($_POST['customWhereClause']) != ''
) {
return ' WHERE ' . $_POST['customWhereClause'];
}
// If there are no search criteria set or no unary criteria operators,
// return
if (! isset($_POST['criteriaValues'])
&& ! isset($_POST['criteriaColumnOperators'])
&& ! isset($_POST['geom_func'])
) {
return '';
}
// else continue to form the where clause from column criteria values
$fullWhereClause = array();
foreach ($_POST['criteriaColumnOperators'] as $column_index => $operator) {
$unaryFlag = $GLOBALS['dbi']->types->isUnaryOperator($operator);
$tmp_geom_func = isset($_POST['geom_func'][$column_index])
? $_POST['geom_func'][$column_index] : null;
$whereClause = $this->_getWhereClause(
$_POST['criteriaValues'][$column_index],
$_POST['criteriaColumnNames'][$column_index],
$_POST['criteriaColumnTypes'][$column_index],
$operator,
$unaryFlag,
$tmp_geom_func
);
if ($whereClause) {
$fullWhereClause[] = $whereClause;
}
} // end foreach
if (!empty($fullWhereClause)) {
return ' WHERE ' . implode(' AND ', $fullWhereClause);
}
return '';
}
/**
* Return the where clause in case column's type is ENUM.
*
* @param mixed $criteriaValues Search criteria input
* @param string $func_type Search function/operator
*
* @return string part of where clause.
*/
private function _getEnumWhereClause($criteriaValues, $func_type)
{
if (! is_array($criteriaValues)) {
$criteriaValues = explode(',', $criteriaValues);
}
$enum_selected_count = count($criteriaValues);
if ($func_type == '=' && $enum_selected_count > 1) {
$func_type = 'IN';
$parens_open = '(';
$parens_close = ')';
} elseif ($func_type == '!=' && $enum_selected_count > 1) {
$func_type = 'NOT IN';
$parens_open = '(';
$parens_close = ')';
} else {
$parens_open = '';
$parens_close = '';
}
$enum_where = '\''
. $GLOBALS['dbi']->escapeString($criteriaValues[0]) . '\'';
for ($e = 1; $e < $enum_selected_count; $e++) {
$enum_where .= ', \''
. $GLOBALS['dbi']->escapeString($criteriaValues[$e]) . '\'';
}
return ' ' . $func_type . ' ' . $parens_open
. $enum_where . $parens_close;
}
/**
* Return the where clause for a geometrical column.
*
* @param mixed $criteriaValues Search criteria input
* @param string $names Name of the column on which search is submitted
* @param string $func_type Search function/operator
* @param string $types Type of the field
* @param bool $geom_func Whether geometry functions should be applied
*
* @return string part of where clause.
*/
private function _getGeomWhereClause($criteriaValues, $names,
$func_type, $types, $geom_func = null
) {
$geom_unary_functions = array(
'IsEmpty' => 1,
'IsSimple' => 1,
'IsRing' => 1,
'IsClosed' => 1,
);
$where = '';
// Get details about the geometry functions
$geom_funcs = Util::getGISFunctions($types, true, false);
// If the function takes multiple parameters
if(strpos($func_type, "IS NULL") !== false || strpos($func_type, "IS NOT NULL") !== false) {
$where = Util::backquote($names) . " " . $func_type;
return $where;
} elseif ($geom_funcs[$geom_func]['params'] > 1) {
// create gis data from the criteria input
$gis_data = Util::createGISData($criteriaValues, $this->dbi->getVersion());
$where = $geom_func . '(' . Util::backquote($names)
. ', ' . $gis_data . ')';
return $where;
}
// New output type is the output type of the function being applied
$type = $geom_funcs[$geom_func]['type'];
$geom_function_applied = $geom_func
. '(' . Util::backquote($names) . ')';
// If the where clause is something like 'IsEmpty(`spatial_col_name`)'
if (isset($geom_unary_functions[$geom_func])
&& trim($criteriaValues) == ''
) {
$where = $geom_function_applied;
} elseif (in_array($type, Util::getGISDatatypes())
&& ! empty($criteriaValues)
) {
// create gis data from the criteria input
$gis_data = Util::createGISData($criteriaValues, $this->dbi->getVersion());
$where = $geom_function_applied . " " . $func_type . " " . $gis_data;
} elseif (strlen($criteriaValues) > 0) {
$where = $geom_function_applied . " "
. $func_type . " '" . $criteriaValues . "'";
}
return $where;
}
/**
* Return the where clause for query generation based on the inputs provided.
*
* @param mixed $criteriaValues Search criteria input
* @param string $names Name of the column on which search is submitted
* @param string $types Type of the field
* @param string $func_type Search function/operator
* @param bool $unaryFlag Whether operator unary or not
* @param bool $geom_func Whether geometry functions should be applied
*
* @return string generated where clause.
*/
private function _getWhereClause($criteriaValues, $names, $types,
$func_type, $unaryFlag, $geom_func = null
) {
// If geometry function is set
if (! empty($geom_func)) {
return $this->_getGeomWhereClause(
$criteriaValues, $names, $func_type, $types, $geom_func
);
}
$backquoted_name = Util::backquote($names);
$where = '';
if ($unaryFlag) {
$where = $backquoted_name . ' ' . $func_type;
} elseif (strncasecmp($types, 'enum', 4) == 0 && (! empty($criteriaValues) || $criteriaValues[0] === '0')) {
$where = $backquoted_name;
$where .= $this->_getEnumWhereClause($criteriaValues, $func_type);
} elseif ($criteriaValues != '') {
// For these types we quote the value. Even if it's another type
// (like INT), for a LIKE we always quote the value. MySQL converts
// strings to numbers and numbers to strings as necessary
// during the comparison
if (preg_match('@char|binary|blob|text|set|date|time|year@i', $types)
|| mb_strpos(' ' . $func_type, 'LIKE')
) {
$quot = '\'';
} else {
$quot = '';
}
// LIKE %...%
if ($func_type == 'LIKE %...%') {
$func_type = 'LIKE';
$criteriaValues = '%' . $criteriaValues . '%';
}
if ($func_type == 'REGEXP ^...$') {
$func_type = 'REGEXP';
$criteriaValues = '^' . $criteriaValues . '$';
}
if ('IN (...)' != $func_type
&& 'NOT IN (...)' != $func_type
&& 'BETWEEN' != $func_type
&& 'NOT BETWEEN' != $func_type
) {
return $backquoted_name . ' ' . $func_type . ' ' . $quot
. $GLOBALS['dbi']->escapeString($criteriaValues) . $quot;
}
$func_type = str_replace(' (...)', '', $func_type);
//Don't explode if this is already an array
//(Case for (NOT) IN/BETWEEN.)
if (is_array($criteriaValues)) {
$values = $criteriaValues;
} else {
$values = explode(',', $criteriaValues);
}
// quote values one by one
$emptyKey = false;
foreach ($values as $key => &$value) {
if ('' === $value) {
$emptyKey = $key;
$value = 'NULL';
continue;
}
$value = $quot . $GLOBALS['dbi']->escapeString(trim($value))
. $quot;
}
if ('BETWEEN' == $func_type || 'NOT BETWEEN' == $func_type) {
$where = $backquoted_name . ' ' . $func_type . ' '
. (isset($values[0]) ? $values[0] : '')
. ' AND ' . (isset($values[1]) ? $values[1] : '');
} else { //[NOT] IN
if (false !== $emptyKey) {
unset($values[$emptyKey]);
}
$wheres = array();
if (!empty($values)) {
$wheres[] = $backquoted_name . ' ' . $func_type
. ' (' . implode(',', $values) . ')';
}
if (false !== $emptyKey) {
$wheres[] = $backquoted_name . ' IS NULL';
}
$where = implode(' OR ', $wheres);
if (1 < count($wheres)) {
$where = '(' . $where . ')';
}
}
} // end if
return $where;
}
}
| {
"content_hash": "ea9d8322d0f69d05c3f84391a02a0648",
"timestamp": "",
"source": "github",
"line_count": 1173,
"max_line_length": 119,
"avg_line_length": 34.87553282182438,
"alnum_prop": 0.4795521767826151,
"repo_name": "cytopia/devilbox",
"id": "e9f1e48e0561fac5d39b687aafb7749ed502db2d",
"size": "40909",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".devilbox/www/htdocs/vendor/phpmyadmin-4.9.7/libraries/classes/Controllers/Table/TableSearchController.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "86"
},
{
"name": "CSS",
"bytes": "3980"
},
{
"name": "JavaScript",
"bytes": "923"
},
{
"name": "Makefile",
"bytes": "4209"
},
{
"name": "PHP",
"bytes": "221096"
},
{
"name": "Shell",
"bytes": "204888"
}
],
"symlink_target": ""
} |
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HelloComponent } from "./hello/hello.component";
import { MasterComponent } from "./master/master.component";
import { NgClassComponent, NgforComponent, NgSwitchComponent, ViewChildComponent,ContentChildComponent } from './Controls/index';
import { ObservableComponent, HttpComponent, HttpSearchComponent, InjectableComponent } from './observables/index';
const routes: Routes = [
{ path: 'hello', component: HelloComponent },
{ path: 'master', component: MasterComponent },
{ path: 'ngClass' , component: NgClassComponent},
{ path: 'ngFor' , component: NgforComponent},
{ path: 'ngSwitch' , component: NgSwitchComponent},
{ path: 'viewChild' , component: ViewChildComponent},
{ path: 'contentChild' , component: ContentChildComponent},
{ path: 'observable' , component: ObservableComponent},
{ path: 'http' , component: HttpComponent},
{ path: 'httpsearch' , component: HttpSearchComponent},
{ path: 'injectable' , component: InjectableComponent},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { } | {
"content_hash": "9fbd3e894866423edffd5538545383ff",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 129,
"avg_line_length": 44.285714285714285,
"alnum_prop": 0.7104838709677419,
"repo_name": "imsangram/ng-course2",
"id": "bd8c375627f3dc5d3d63a520edfe98bbafef044b",
"size": "1242",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/app.routing.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "278"
},
{
"name": "CSS",
"bytes": "80"
},
{
"name": "HTML",
"bytes": "17878"
},
{
"name": "JavaScript",
"bytes": "1645"
},
{
"name": "Shell",
"bytes": "159"
},
{
"name": "TypeScript",
"bytes": "27945"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML>
<html lang={{ config.lang_code }} dir={{ lang_dir }}>
<head>
{% block head_extras %}{% endblock %}
<title>{{ config.strings.tooltitle }}</title>
<meta name="robots" content="nofollow, noodp, noindex">
<meta name="description" content="{{ config.strings.tooltitle }} - {{ config.strings.introduction }}">
<!-- Since the 404 handler can be invoked for arbitrarily broken URLs, let's
not bother requesting style.css using its relative path, but rather just
inline the relevant CSS. -->
<style>
body {
margin: 0;
padding: 10px 15px;
font-family: Helvetica, sans-serif;
font-size: medium;
background-color: #FCFCFC;
}
body * {
background-color: inherit;
}
h1 {
font-family: Georgia, serif;
font-size: xx-large;
}
</style>
</head>
<body>
<h1>{{ config.strings.page_not_found }}</h1>
<p>{{ config.strings.page_not_found_text }}</p>
{% block bottom_extras %}{% endblock %}
</body>
</html>
| {
"content_hash": "eb042ff654e23fa6855f2ef807fec420",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 106,
"avg_line_length": 30.833333333333332,
"alnum_prop": 0.5576576576576576,
"repo_name": "jhsoby/citationhunt",
"id": "1d015e1553d41429c144e57ab08415770831ae43",
"size": "1110",
"binary": false,
"copies": "1",
"ref": "refs/heads/patch-2",
"path": "templates/404.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5059"
},
{
"name": "HTML",
"bytes": "7677"
},
{
"name": "JavaScript",
"bytes": "3802"
},
{
"name": "Python",
"bytes": "104897"
},
{
"name": "Shell",
"bytes": "677"
}
],
"symlink_target": ""
} |
hetzner-zonefiles
=================
python script to handle hetzner zonefiles through their robot
Todo
----
* (H) implement upload feature
* (L) safe zonefiles in a folder in the format YYYYmmdd
* (L) make command line interface better (for example with optparser)
* (L) make install script general such that it can be used on more machines | {
"content_hash": "6c7177abdc71c86433d647aa1b34d0c4",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 75,
"avg_line_length": 28.583333333333332,
"alnum_prop": 0.7288629737609329,
"repo_name": "larsborn/hetzner-zonefiles",
"id": "0beb6a4213dc6de3330a1875d6d6a0dd35cef9d9",
"size": "343",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "2903"
},
{
"name": "Shell",
"bytes": "263"
}
],
"symlink_target": ""
} |
<?php
/**
* TRusted shops protection product manager.
*
*/
class oxTsProduct extends oxSuperCfg
{
/**
* Id of TS protection product
*
* @var string
*/
protected $_sTsId = null;
/**
* Amount of TS protection product
*
* @var integer
*/
protected $_iAmount = null;
/**
* Price of TS protection product
*
* @deprecated in v4.8/5.1 on 2013-10-14; for formatting use oxPrice smarty plugin
*
* @var float
*/
protected $_fPrice = null;
/**
* Price of TS protection netto product
*
* @deprecated in v4.8/5.1 on 2013-10-14; for formatting use oxPrice smarty plugin
*
* @var float
*/
protected $_fNettoPrice = null;
/**
* Price of TS protection vat value
*
* @deprecated in v4.8/5.1 on 2013-10-14; for formatting use oxPrice smarty plugin
*
* @var float
*/
protected $_fVatValue = null;
/**
* Price of TS protection product
*
* @var object
*/
protected $_oPrice = null;
/**
* Price of TS protection vat
*
* @var object
*/
protected $_dVat = null;
/**
* Buyer protection products
*
* @var array
*/
protected $_sTsProtectProducts = array("TS080501_500_30_EUR" => array("netto" => "0.82", "amount" => "500"),
"TS080501_1500_30_EUR" => array("netto" => "2.47", "amount" => "1500"),
"TS080501_2500_30_EUR" => array("netto" => "4.12", "amount" => "2500"),
"TS080501_5000_30_EUR" => array("netto" => "8.24", "amount" => "5000"),
"TS080501_10000_30_EUR" => array("netto" => "16.47", "amount" => "10000"),
"TS080501_20000_30_EUR" => array("netto" => "32.94", "amount" => "20000")
);
/**
* Return protection vat
*
* @return float
*/
public function getVat()
{
return $this->_dVat;
}
/**
* set protection vat
*
* @param float $dVat - vat
*/
public function setVat($dVat)
{
$this->_dVat = $dVat;
}
/**
* Returns id of TS protection product
*
* @return string
*/
public function getTsId()
{
return $this->_sTsId;
}
/**
* Sets id of TS protection product
*
* @param string $sTsId TS product id
*/
public function setTsId($sTsId)
{
$this->_sTsId = $sTsId;
}
/**
* Returns amount of TS protection product
*
* @return integer
*/
public function getAmount()
{
if ($this->_iAmount == null) {
if ($sTsId = $this->getTsId()) {
$aTsProducts = $this->getAllTsProducts();
if ($aTsProducts[$sTsId] && is_array($aTsProducts[$sTsId])) {
$this->_iAmount = $aTsProducts[$sTsId]['amount'];
}
}
}
return $this->_iAmount;
}
/**
* Returns formatted brutto price of TS protection product
*
* @deprecated in v4.8/5.1 on 2013-10-14; for formatting use oxPrice smarty plugin
*
* @return string
*/
public function getFPrice()
{
if ($this->_fPrice == null) {
if ($oPrice = $this->getPrice()) {
$this->_fPrice = oxRegistry::getLang()->formatCurrency($oPrice->getBruttoPrice());
}
}
return $this->_fPrice;
}
/**
* Returns formatted brutto price of TS protection product
*
* @deprecated in v4.8/5.1 on 2013-10-14; for formatting use oxPrice smarty plugin
*
* @return string
*/
public function getFNettoPrice()
{
if ($this->_fNettoPrice == null) {
if ($oPrice = $this->getPrice()) {
$this->_fNettoPrice = oxRegistry::getLang()->formatCurrency($oPrice->getNettoPrice());
}
}
return $this->_fNettoPrice;
}
/**
* Returns formatted brutto price of TS protection product
*
* @deprecated in v4.8/5.1 on 2013-10-14; for formatting use oxPrice smarty plugin
*
* @return string
*/
public function getFVatValue()
{
if ($this->_fVatValue == null) {
if ($oPrice = $this->getPrice()) {
$this->_fVatValue = oxRegistry::getLang()->formatCurrency($oPrice->getVatValue());
}
}
return $this->_fVatValue;
}
/**
* Returns price of TS protection product
*
* @return oxPrice
*/
public function getPrice()
{
if ($this->_oPrice == null) {
if ($sTsId = $this->getTsId()) {
$aTsProducts = $this->getAllTsProducts();
if ($aTsProducts[$sTsId] && is_array($aTsProducts[$sTsId])) {
$dPrice = $aTsProducts[$sTsId]['netto'];
$oPrice = oxNew('oxPrice');
$oPrice->setNettoPriceMode();
$oPrice->setPrice($dPrice);
$oPrice->setVat($this->getVat());
$this->_oPrice = $oPrice;
}
}
}
return $this->_oPrice;
}
/**
* Returns array of all TS protection products
*
* @return array
*/
public function getAllTsProducts()
{
return $this->_sTsProtectProducts;
}
}
| {
"content_hash": "427fc4d3eaff08c2f3d8e1c1b75252d1",
"timestamp": "",
"source": "github",
"line_count": 226,
"max_line_length": 117,
"avg_line_length": 24.446902654867255,
"alnum_prop": 0.48923076923076925,
"repo_name": "EllisV/oxid-standard",
"id": "a17ebc528c0de59eecbfeb5b599fd1c50fc1b377",
"size": "6398",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "web/application/models/oxtsproduct.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "2444"
},
{
"name": "CSS",
"bytes": "158741"
},
{
"name": "HTML",
"bytes": "9228"
},
{
"name": "JavaScript",
"bytes": "245692"
},
{
"name": "PHP",
"bytes": "10033058"
},
{
"name": "Smarty",
"bytes": "1867164"
}
],
"symlink_target": ""
} |
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.OData;
using Microsoft.Azure.Mobile.Server;
using ghostshockey.it.api.Models;
using System;
using System.Collections.Generic;
using Microsoft.Azure.Mobile.Server.Config;
using System.Web.Http.Results;
using System.Web.OData.Routing;
using System.Net;
using System.Web.Http.Cors;
namespace ghostshockey.it.api.Controllers
{
//[MobileAppController]
//[Authorize]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class PlayersController : ODataController
{
GhostsDbContext _ctx = new GhostsDbContext();
[EnableQuery]
public IHttpActionResult GetPlayers()
{
return Ok(_ctx.Players);
}
public IHttpActionResult GetPlayer([FromODataUri]int key)
{
var model = _ctx.Players.FirstOrDefault(p => p.PlayerID == key);
if (model != null)
return Ok(model);
else
return NotFound();
}
public IHttpActionResult Post(Player model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_ctx.Players.Add(model);
_ctx.SaveChanges();
return Created(model);
}
public IHttpActionResult Put([FromODataUri] int key, Player model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var current = _ctx.Players.FirstOrDefault(p => p.PlayerID == key);
if (current == null)
{
return NotFound();
}
model.PlayerID = current.PlayerID;
_ctx.Entry(current).CurrentValues.SetValues(model);
_ctx.SaveChanges();
return StatusCode(HttpStatusCode.NoContent);
}
public IHttpActionResult Patch([FromODataUri] int key, Delta<Player> patch)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var current = _ctx.Players.FirstOrDefault(p => p.PlayerID== key);
if (current == null)
{
return NotFound();
}
patch.Patch(current);
_ctx.SaveChanges();
return StatusCode(HttpStatusCode.NoContent);
}
public IHttpActionResult Delete([FromODataUri] int key)
{
var current = _ctx.Players.FirstOrDefault(p => p.PlayerID == key);
if (current == null)
{
return NotFound();
}
_ctx.Players.Remove(current);
_ctx.SaveChanges();
return StatusCode(HttpStatusCode.NoContent);
}
protected override void Dispose(bool disposing)
{
_ctx.Dispose();
base.Dispose(disposing);
}
}
} | {
"content_hash": "623e6b275d2c5b740dc060637fd54106",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 83,
"avg_line_length": 26.146551724137932,
"alnum_prop": 0.5446752390372568,
"repo_name": "mcampulla/Ghostshockey",
"id": "19429ae7022afdd12e7938d6ac269b41a1409a9a",
"size": "3035",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ghostshockey.it.api/Controllers/PlayersController.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "110"
},
{
"name": "C#",
"bytes": "293163"
},
{
"name": "CSS",
"bytes": "3810761"
},
{
"name": "HTML",
"bytes": "7968"
},
{
"name": "JavaScript",
"bytes": "15393127"
}
],
"symlink_target": ""
} |
"""
logbook.handlers
~~~~~~~~~~~~~~~~
The handler interface and builtin handlers.
:copyright: (c) 2010 by Armin Ronacher, Georg Brandl.
:license: BSD, see LICENSE for more details.
"""
import os
import re
import sys
import stat
import errno
import socket
try:
from hashlib import sha1
except ImportError:
from sha import new as sha1
import threading
import traceback
from datetime import datetime, timedelta
from threading import Lock
from collections import deque
from logbook.base import CRITICAL, ERROR, WARNING, NOTICE, INFO, DEBUG, \
NOTSET, level_name_property, _missing, lookup_level, \
Flags, ContextObject, ContextStackManager
from logbook.helpers import rename, b, _is_text_stream, is_unicode, PY2, \
zip, xrange, string_types, integer_types, reraise, u
DEFAULT_FORMAT_STRING = (
u('[{record.time:%Y-%m-%d %H:%M}] ') +
u('{record.level_name}: {record.channel}: {record.message}')
)
SYSLOG_FORMAT_STRING = u('{record.channel}: {record.message}')
NTLOG_FORMAT_STRING = u('''\
Message Level: {record.level_name}
Location: {record.filename}:{record.lineno}
Module: {record.module}
Function: {record.func_name}
Exact Time: {record.time:%Y-%m-%d %H:%M:%S}
Event provided Message:
{record.message}
''')
TEST_FORMAT_STRING = \
u('[{record.level_name}] {record.channel}: {record.message}')
MAIL_FORMAT_STRING = u('''\
Subject: {handler.subject}
Message type: {record.level_name}
Location: {record.filename}:{record.lineno}
Module: {record.module}
Function: {record.func_name}
Time: {record.time:%Y-%m-%d %H:%M:%S}
Message:
{record.message}
''')
MAIL_RELATED_FORMAT_STRING = u('''\
Message type: {record.level_name}
Location: {record.filename}:{record.lineno}
Module: {record.module}
Function: {record.func_name}
{record.message}
''')
SYSLOG_PORT = 514
REGTYPE = type(re.compile("I'm a regular expression!"))
def create_syshandler(application_name, level=NOTSET):
"""Creates the handler the operating system provides. On Unix systems
this creates a :class:`SyslogHandler`, on Windows sytems it will
create a :class:`NTEventLogHandler`.
"""
if os.name == 'nt':
return NTEventLogHandler(application_name, level=level)
return SyslogHandler(application_name, level=level)
class _HandlerType(type):
"""The metaclass of handlers injects a destructor if the class has an
overridden close method. This makes it possible that the default
handler class as well as all subclasses that don't need cleanup to be
collected with less overhead.
"""
def __new__(cls, name, bases, d):
# aha, that thing has a custom close method. We will need a magic
# __del__ for it to be called on cleanup.
if bases != (ContextObject,) and 'close' in d and '__del__' not in d \
and not any(hasattr(x, '__del__') for x in bases):
def _magic_del(self):
try:
self.close()
except Exception:
# del is also invoked when init fails, so we better just
# ignore any exception that might be raised here
pass
d['__del__'] = _magic_del
return type.__new__(cls, name, bases, d)
class Handler(ContextObject):
"""Handler instances dispatch logging events to specific destinations.
The base handler class. Acts as a placeholder which defines the Handler
interface. Handlers can optionally use Formatter instances to format
records as desired. By default, no formatter is specified; in this case,
the 'raw' message as determined by record.message is logged.
To bind a handler you can use the :meth:`push_application` and
:meth:`push_thread` methods. This will push the handler on a stack of
handlers. To undo this, use the :meth:`pop_application` and
:meth:`pop_thread` methods::
handler = MyHandler()
handler.push_application()
# all here goes to that handler
handler.pop_application()
By default messages sent to that handler will not go to a handler on
an outer level on the stack, if handled. This can be changed by
setting bubbling to `True`. This setup for example would not have
any effect::
handler = NullHandler(bubble=True)
handler.push_application()
Whereas this setup disables all logging for the application::
handler = NullHandler()
handler.push_application()
There are also context managers to setup the handler for the duration
of a `with`-block::
with handler.applicationbound():
...
with handler.threadbound():
...
Because `threadbound` is a common operation, it is aliased to a with
on the handler itself::
with handler:
...
"""
__metaclass__ = _HandlerType
stack_manager = ContextStackManager()
#: a flag for this handler that can be set to `True` for handlers that
#: are consuming log records but are not actually displaying it. This
#: flag is set for the :class:`NullHandler` for instance.
blackhole = False
def __init__(self, level=NOTSET, filter=None, bubble=False):
#: the level for the handler. Defaults to `NOTSET` which
#: consumes all entries.
self.level = lookup_level(level)
#: the formatter to be used on records. This is a function
#: that is passed a log record as first argument and the
#: handler as second and returns something formatted
#: (usually a unicode string)
self.formatter = None
#: the filter to be used with this handler
self.filter = filter
#: the bubble flag of this handler
self.bubble = bubble
level_name = level_name_property()
def format(self, record):
"""Formats a record with the given formatter. If no formatter
is set, the record message is returned. Generally speaking the
return value is most likely a unicode string, but nothing in
the handler interface requires a formatter to return a unicode
string.
The combination of a handler and formatter might have the
formatter return an XML element tree for example.
"""
if self.formatter is None:
return record.message
return self.formatter(record, self)
def should_handle(self, record):
"""Returns `True` if this handler wants to handle the record. The
default implementation checks the level.
"""
return record.level >= self.level
def handle(self, record):
"""Emits the record and falls back. It tries to :meth:`emit` the
record and if that fails, it will call into :meth:`handle_error` with
the record and traceback. This function itself will always emit
when called, even if the logger level is higher than the record's
level.
If this method returns `False` it signals to the calling function that
no recording took place in which case it will automatically bubble.
This should not be used to signal error situations. The default
implementation always returns `True`.
"""
try:
self.emit(record)
except Exception:
self.handle_error(record, sys.exc_info())
return True
def emit(self, record):
"""Emit the specified logging record. This should take the
record and deliver it to whereever the handler sends formatted
log records.
"""
def emit_batch(self, records, reason):
"""Some handlers may internally queue up records and want to forward
them at once to another handler. For example the
:class:`~logbook.FingersCrossedHandler` internally buffers
records until a level threshold is reached in which case the buffer
is sent to this method and not :meth:`emit` for each record.
The default behaviour is to call :meth:`emit` for each record in
the buffer, but handlers can use this to optimize log handling. For
instance the mail handler will try to batch up items into one mail
and not to emit mails for each record in the buffer.
Note that unlike :meth:`emit` there is no wrapper method like
:meth:`handle` that does error handling. The reason is that this
is intended to be used by other handlers which are already protected
against internal breakage.
`reason` is a string that specifies the rason why :meth:`emit_batch`
was called, and not :meth:`emit`. The following are valid values:
``'buffer'``
Records were buffered for performance reasons or because the
records were sent to another process and buffering was the only
possible way. For most handlers this should be equivalent to
calling :meth:`emit` for each record.
``'escalation'``
Escalation means that records were buffered in case the threshold
was exceeded. In this case, the last record in the iterable is the
record that triggered the call.
``'group'``
All the records in the iterable belong to the same logical
component and happened in the same process. For example there was
a long running computation and the handler is invoked with a bunch
of records that happened there. This is similar to the escalation
reason, just that the first one is the significant one, not the
last.
If a subclass overrides this and does not want to handle a specific
reason it must call into the superclass because more reasons might
appear in future releases.
Example implementation::
def emit_batch(self, records, reason):
if reason not in ('escalation', 'group'):
Handler.emit_batch(self, records, reason)
...
"""
for record in records:
self.emit(record)
def close(self):
"""Tidy up any resources used by the handler. This is automatically
called by the destructor of the class as well, but explicit calls are
encouraged. Make sure that multiple calls to close are possible.
"""
def handle_error(self, record, exc_info):
"""Handle errors which occur during an emit() call. The behaviour of
this function depends on the current `errors` setting.
Check :class:`Flags` for more information.
"""
try:
behaviour = Flags.get_flag('errors', 'print')
if behaviour == 'raise':
reraise(exc_info[0], exc_info[1], exc_info[2])
elif behaviour == 'print':
traceback.print_exception(*(exc_info + (None, sys.stderr)))
sys.stderr.write('Logged from file %s, line %s\n' % (
record.filename, record.lineno))
except IOError:
pass
class NullHandler(Handler):
"""A handler that does nothing, meant to be inserted in a handler chain
with ``bubble=False`` to stop further processing.
"""
blackhole = True
class WrapperHandler(Handler):
"""A class that can wrap another handler and redirect all calls to the
wrapped handler::
handler = WrapperHandler(other_handler)
Subclasses should override the :attr:`_direct_attrs` attribute as
necessary.
"""
#: a set of direct attributes that are not forwarded to the inner
#: handler. This has to be extended as necessary.
_direct_attrs = frozenset(['handler'])
def __init__(self, handler):
self.handler = handler
def __getattr__(self, name):
return getattr(self.handler, name)
def __setattr__(self, name, value):
if name in self._direct_attrs:
return Handler.__setattr__(self, name, value)
setattr(self.handler, name, value)
class StringFormatter(object):
"""Many handlers format the log entries to text format. This is done
by a callable that is passed a log record and returns an unicode
string. The default formatter for this is implemented as a class so
that it becomes possible to hook into every aspect of the formatting
process.
"""
def __init__(self, format_string):
self.format_string = format_string
def _get_format_string(self):
return self._format_string
def _set_format_string(self, value):
self._format_string = value
self._formatter = value
format_string = property(_get_format_string, _set_format_string)
del _get_format_string, _set_format_string
def format_record(self, record, handler):
try:
return self._formatter.format(record=record, handler=handler)
except UnicodeEncodeError:
# self._formatter is a str, but some of the record items
# are unicode
fmt = self._formatter.decode('ascii', 'replace')
return fmt.format(record=record, handler=handler)
except UnicodeDecodeError:
# self._formatter is unicode, but some of the record items
# are non-ascii str
fmt = self._formatter.encode('ascii', 'replace')
return fmt.format(record=record, handler=handler)
def format_exception(self, record):
return record.formatted_exception
def __call__(self, record, handler):
line = self.format_record(record, handler)
exc = self.format_exception(record)
if exc:
line += u('\n') + exc
return line
class StringFormatterHandlerMixin(object):
"""A mixin for handlers that provides a default integration for the
:class:`~logbook.StringFormatter` class. This is used for all handlers
by default that log text to a destination.
"""
#: a class attribute for the default format string to use if the
#: constructor was invoked with `None`.
default_format_string = DEFAULT_FORMAT_STRING
#: the class to be used for string formatting
formatter_class = StringFormatter
def __init__(self, format_string):
if format_string is None:
format_string = self.default_format_string
#: the currently attached format string as new-style format
#: string.
self.format_string = format_string
def _get_format_string(self):
if isinstance(self.formatter, StringFormatter):
return self.formatter.format_string
def _set_format_string(self, value):
if value is None:
self.formatter = None
else:
self.formatter = self.formatter_class(value)
format_string = property(_get_format_string, _set_format_string)
del _get_format_string, _set_format_string
class HashingHandlerMixin(object):
"""Mixin class for handlers that are hashing records."""
def hash_record_raw(self, record):
"""Returns a hashlib object with the hash of the record."""
hash = sha1()
hash.update(('%d\x00' % record.level).encode('ascii'))
hash.update((record.channel or u('')).encode('utf-8') + b('\x00'))
hash.update(record.filename.encode('utf-8') + b('\x00'))
hash.update(b(str(record.lineno)))
return hash
def hash_record(self, record):
"""Returns a hash for a record to keep it apart from other records.
This is used for the `record_limit` feature. By default
The level, channel, filename and location are hashed.
Calls into :meth:`hash_record_raw`.
"""
return self.hash_record_raw(record).hexdigest()
_NUMBER_TYPES = integer_types + (float,)
class LimitingHandlerMixin(HashingHandlerMixin):
"""Mixin class for handlers that want to limit emitting records.
In the default setting it delivers all log records but it can be set up
to not send more than n mails for the same record each hour to not
overload an inbox and the network in case a message is triggered multiple
times a minute. The following example limits it to 60 mails an hour::
from datetime import timedelta
handler = MailHandler(record_limit=1,
record_delta=timedelta(minutes=1))
"""
def __init__(self, record_limit, record_delta):
self.record_limit = record_limit
self._limit_lock = Lock()
self._record_limits = {}
if record_delta is None:
record_delta = timedelta(seconds=60)
elif isinstance(record_delta, _NUMBER_TYPES):
record_delta = timedelta(seconds=record_delta)
self.record_delta = record_delta
def check_delivery(self, record):
"""Helper function to check if data should be delivered by this
handler. It returns a tuple in the form ``(suppression_count,
allow)``. The first one is the number of items that were not delivered
so far, the second is a boolean flag if a delivery should happen now.
"""
if self.record_limit is None:
return 0, True
hash = self.hash_record(record)
self._limit_lock.acquire()
try:
allow_delivery = None
suppression_count = old_count = 0
first_count = now = datetime.utcnow()
if hash in self._record_limits:
last_count, suppression_count = self._record_limits[hash]
if last_count + self.record_delta < now:
allow_delivery = True
else:
first_count = last_count
old_count = suppression_count
if not suppression_count and \
len(self._record_limits) >= self.max_record_cache:
cache_items = self._record_limits.items()
cache_items.sort()
del cache_items[:int(self._record_limits) \
* self.record_cache_prune]
self._record_limits = dict(cache_items)
self._record_limits[hash] = (first_count, old_count + 1)
if allow_delivery is None:
allow_delivery = old_count < self.record_limit
return suppression_count, allow_delivery
finally:
self._limit_lock.release()
class StreamHandler(Handler, StringFormatterHandlerMixin):
"""a handler class which writes logging records, appropriately formatted,
to a stream. note that this class does not close the stream, as sys.stdout
or sys.stderr may be used.
If a stream handler is used in a `with` statement directly it will
:meth:`close` on exit to support this pattern::
with StreamHandler(my_stream):
pass
.. admonition:: Notes on the encoding
On Python 3, the encoding parameter is only used if a stream was
passed that was opened in binary mode.
"""
def __init__(self, stream, level=NOTSET, format_string=None,
encoding=None, filter=None, bubble=False):
Handler.__init__(self, level, filter, bubble)
StringFormatterHandlerMixin.__init__(self, format_string)
self.encoding = encoding
self.lock = threading.Lock()
if stream is not _missing:
self.stream = stream
def __enter__(self):
return Handler.__enter__(self)
def __exit__(self, exc_type, exc_value, tb):
self.close()
return Handler.__exit__(self, exc_type, exc_value, tb)
def close(self):
"""The default stream handler implementation is not to close
the wrapped stream but to flush it.
"""
self.flush()
def flush(self):
"""Flushes the inner stream."""
if self.stream is not None and hasattr(self.stream, 'flush'):
self.stream.flush()
def format_and_encode(self, record):
"""Formats the record and encodes it to the stream encoding."""
stream = self.stream
rv = self.format(record) + '\n'
if (PY2 and is_unicode(rv)) or \
not (PY2 or is_unicode(rv) or _is_text_stream(stream)):
enc = self.encoding
if enc is None:
enc = getattr(stream, 'encoding', None) or 'utf-8'
rv = rv.encode(enc, 'replace')
return rv
def write(self, item):
"""Writes a bytestring to the stream."""
self.stream.write(item)
def emit(self, record):
self.lock.acquire()
try:
self.write(self.format_and_encode(record))
self.flush()
finally:
self.lock.release()
class FileHandler(StreamHandler):
"""A handler that does the task of opening and closing files for you.
By default the file is opened right away, but you can also `delay`
the open to the point where the first message is written.
This is useful when the handler is used with a
:class:`~logbook.FingersCrossedHandler` or something similar.
"""
def __init__(self, filename, mode='a', encoding=None, level=NOTSET,
format_string=None, delay=False, filter=None, bubble=False):
if encoding is None:
encoding = 'utf-8'
StreamHandler.__init__(self, None, level, format_string,
encoding, filter, bubble)
self._filename = filename
self._mode = mode
if delay:
self.stream = None
else:
self._open()
def _open(self, mode=None):
if mode is None:
mode = self._mode
self.stream = open(self._filename, mode)
def write(self, item):
if self.stream is None:
self._open()
if not PY2 and isinstance(item, bytes):
self.stream.buffer.write(item)
else:
self.stream.write(item)
def close(self):
if self.stream is not None:
self.flush()
self.stream.close()
self.stream = None
def format_and_encode(self, record):
# encodes based on the stream settings, so the stream has to be
# open at the time this function is called.
if self.stream is None:
self._open()
return StreamHandler.format_and_encode(self, record)
def emit(self, record):
if self.stream is None:
self._open()
StreamHandler.emit(self, record)
class MonitoringFileHandler(FileHandler):
"""A file handler that will check if the file was moved while it was
open. This might happen on POSIX systems if an application like
logrotate moves the logfile over.
Because of different IO concepts on Windows, this handler will not
work on a windows system.
"""
def __init__(self, filename, mode='a', encoding='utf-8', level=NOTSET,
format_string=None, delay=False, filter=None, bubble=False):
FileHandler.__init__(self, filename, mode, encoding, level,
format_string, delay, filter, bubble)
if os.name == 'nt':
raise RuntimeError('MonitoringFileHandler '
'does not support Windows')
self._query_fd()
def _query_fd(self):
if self.stream is None:
self._last_stat = None, None
else:
try:
st = os.stat(self._filename)
except OSError:
e = sys.exc_info()[1]
if e.errno != 2:
raise
self._last_stat = None, None
else:
self._last_stat = st[stat.ST_DEV], st[stat.ST_INO]
def emit(self, record):
last_stat = self._last_stat
self._query_fd()
if last_stat != self._last_stat:
self.close()
FileHandler.emit(self, record)
self._query_fd()
class StderrHandler(StreamHandler):
"""A handler that writes to what is currently at stderr. At the first
glace this appears to just be a :class:`StreamHandler` with the stream
set to :data:`sys.stderr` but there is a difference: if the handler is
created globally and :data:`sys.stderr` changes later, this handler will
point to the current `stderr`, whereas a stream handler would still
point to the old one.
"""
def __init__(self, level=NOTSET, format_string=None, filter=None,
bubble=False):
StreamHandler.__init__(self, _missing, level, format_string,
None, filter, bubble)
@property
def stream(self):
return sys.stderr
class RotatingFileHandlerBase(FileHandler):
"""Baseclass for rotating file handlers.
.. versionchanged:: 0.3
This class was deprecated because the interface is not flexible
enough to implement proper file rotations. The former builtin
subclasses no longer use this baseclass.
"""
def __init__(self, *args, **kwargs):
from warnings import warn
warn(DeprecationWarning('This class is deprecated'))
FileHandler.__init__(self, *args, **kwargs)
def emit(self, record):
self.lock.acquire()
try:
msg = self.format_and_encode(record)
if self.should_rollover(record, msg):
self.perform_rollover()
self.write(msg)
self.flush()
finally:
self.lock.release()
def should_rollover(self, record, formatted_record):
"""Called with the log record and the return value of the
:meth:`format_and_encode` method. The method has then to
return `True` if a rollover should happen or `False`
otherwise.
.. versionchanged:: 0.3
Previously this method was called with the number of bytes
returned by :meth:`format_and_encode`
"""
return False
def perform_rollover(self):
"""Called if :meth:`should_rollover` returns `True` and has
to perform the actual rollover.
"""
class RotatingFileHandler(FileHandler):
"""This handler rotates based on file size. Once the maximum size
is reached it will reopen the file and start with an empty file
again. The old file is moved into a backup copy (named like the
file, but with a ``.backupnumber`` appended to the file. So if
you are logging to ``mail`` the first backup copy is called
``mail.1``.)
The default number of backups is 5. Unlike a similar logger from
the logging package, the backup count is mandatory because just
reopening the file is dangerous as it deletes the log without
asking on rollover.
"""
def __init__(self, filename, mode='a', encoding='utf-8', level=NOTSET,
format_string=None, delay=False, max_size=1024 * 1024,
backup_count=5, filter=None, bubble=False):
FileHandler.__init__(self, filename, mode, encoding, level,
format_string, delay, filter, bubble)
self.max_size = max_size
self.backup_count = backup_count
assert backup_count > 0, 'at least one backup file has to be ' \
'specified'
def should_rollover(self, record, bytes):
self.stream.seek(0, 2)
return self.stream.tell() + bytes >= self.max_size
def perform_rollover(self):
self.stream.close()
for x in xrange(self.backup_count - 1, 0, -1):
src = '%s.%d' % (self._filename, x)
dst = '%s.%d' % (self._filename, x + 1)
try:
rename(src, dst)
except OSError:
e = sys.exc_info()[1]
if e.errno != errno.ENOENT:
raise
rename(self._filename, self._filename + '.1')
self._open('w')
def emit(self, record):
self.lock.acquire()
try:
msg = self.format_and_encode(record)
if self.should_rollover(record, len(msg)):
self.perform_rollover()
self.write(msg)
self.flush()
finally:
self.lock.release()
class TimedRotatingFileHandler(FileHandler):
"""This handler rotates based on dates. It will name the file
after the filename you specify and the `date_format` pattern.
So for example if you configure your handler like this::
handler = TimedRotatingFileHandler('/var/log/foo.log',
date_format='%Y-%m-%d')
The filenames for the logfiles will look like this::
/var/log/foo-2010-01-10.log
/var/log/foo-2010-01-11.log
...
By default it will keep all these files around, if you want to limit
them, you can specify a `backup_count`.
"""
def __init__(self, filename, mode='a', encoding='utf-8', level=NOTSET,
format_string=None, date_format='%Y-%m-%d',
backup_count=0, filter=None, bubble=False):
FileHandler.__init__(self, filename, mode, encoding, level,
format_string, True, filter, bubble)
self.date_format = date_format
self.backup_count = backup_count
self._fn_parts = os.path.splitext(os.path.abspath(filename))
self._filename = None
def _get_timed_filename(self, datetime):
return datetime.strftime('-' + self.date_format) \
.join(self._fn_parts)
def should_rollover(self, record):
fn = self._get_timed_filename(record.time)
rv = self._filename is not None and self._filename != fn
# remember the current filename. In case rv is True, the rollover
# performing function will already have the new filename
self._filename = fn
return rv
def files_to_delete(self):
"""Returns a list with the files that have to be deleted when
a rollover occours.
"""
directory = os.path.dirname(self._filename)
files = []
for filename in os.listdir(directory):
filename = os.path.join(directory, filename)
if filename.startswith(self._fn_parts[0] + '-') and \
filename.endswith(self._fn_parts[1]):
files.append((os.path.getmtime(filename), filename))
files.sort()
return files[:-self.backup_count + 1]
def perform_rollover(self):
self.stream.close()
if self.backup_count > 0:
for time, filename in self.files_to_delete():
os.remove(filename)
self._open('w')
def emit(self, record):
self.lock.acquire()
try:
if self.should_rollover(record):
self.perform_rollover()
self.write(self.format_and_encode(record))
self.flush()
finally:
self.lock.release()
class TestHandler(Handler, StringFormatterHandlerMixin):
"""Like a stream handler but keeps the values in memory. This
logger provides some ways to test for the records in memory.
Example usage::
def my_test():
with logbook.TestHandler() as handler:
logger.warn('A warning')
assert logger.has_warning('A warning')
...
"""
default_format_string = TEST_FORMAT_STRING
def __init__(self, level=NOTSET, format_string=None, filter=None,
bubble=False):
Handler.__init__(self, level, filter, bubble)
StringFormatterHandlerMixin.__init__(self, format_string)
#: captures the :class:`LogRecord`\s as instances
self.records = []
self._formatted_records = []
self._formatted_record_cache = []
def close(self):
"""Close all records down when the handler is closed."""
for record in self.records:
record.close()
def emit(self, record):
# keep records open because we will want to examine them after the
# call to the emit function. If we don't do that, the traceback
# attribute and other things will already be removed.
record.keep_open = True
self.records.append(record)
@property
def formatted_records(self):
"""Captures the formatted log records as unicode strings."""
if len(self._formatted_record_cache) != len(self.records) or \
any(r1 != r2 for r1, r2 in
zip(self.records, self._formatted_record_cache)):
self._formatted_records = [self.format(r) for r in self.records]
self._formatted_record_cache = list(self.records)
return self._formatted_records
@property
def has_criticals(self):
"""`True` if any :data:`CRITICAL` records were found."""
return any(r.level == CRITICAL for r in self.records)
@property
def has_errors(self):
"""`True` if any :data:`ERROR` records were found."""
return any(r.level == ERROR for r in self.records)
@property
def has_warnings(self):
"""`True` if any :data:`WARNING` records were found."""
return any(r.level == WARNING for r in self.records)
@property
def has_notices(self):
"""`True` if any :data:`NOTICE` records were found."""
return any(r.level == NOTICE for r in self.records)
@property
def has_infos(self):
"""`True` if any :data:`INFO` records were found."""
return any(r.level == INFO for r in self.records)
@property
def has_debugs(self):
"""`True` if any :data:`DEBUG` records were found."""
return any(r.level == DEBUG for r in self.records)
def has_critical(self, *args, **kwargs):
"""`True` if a specific :data:`CRITICAL` log record exists.
See :ref:`probe-log-records` for more information.
"""
kwargs['level'] = CRITICAL
return self._test_for(*args, **kwargs)
def has_error(self, *args, **kwargs):
"""`True` if a specific :data:`ERROR` log record exists.
See :ref:`probe-log-records` for more information.
"""
kwargs['level'] = ERROR
return self._test_for(*args, **kwargs)
def has_warning(self, *args, **kwargs):
"""`True` if a specific :data:`WARNING` log record exists.
See :ref:`probe-log-records` for more information.
"""
kwargs['level'] = WARNING
return self._test_for(*args, **kwargs)
def has_notice(self, *args, **kwargs):
"""`True` if a specific :data:`NOTICE` log record exists.
See :ref:`probe-log-records` for more information.
"""
kwargs['level'] = NOTICE
return self._test_for(*args, **kwargs)
def has_info(self, *args, **kwargs):
"""`True` if a specific :data:`INFO` log record exists.
See :ref:`probe-log-records` for more information.
"""
kwargs['level'] = INFO
return self._test_for(*args, **kwargs)
def has_debug(self, *args, **kwargs):
"""`True` if a specific :data:`DEBUG` log record exists.
See :ref:`probe-log-records` for more information.
"""
kwargs['level'] = DEBUG
return self._test_for(*args, **kwargs)
def _test_for(self, message=None, channel=None, level=None):
def _match(needle, haystack):
"Matches both compiled regular expressions and strings"
if isinstance(needle, REGTYPE) and needle.search(haystack):
return True
if needle == haystack:
return True
return False
for record in self.records:
if level is not None and record.level != level:
continue
if channel is not None and record.channel != channel:
continue
if message is not None and not _match(message, record.message):
continue
return True
return False
class MailHandler(Handler, StringFormatterHandlerMixin,
LimitingHandlerMixin):
"""A handler that sends error mails. The format string used by this
handler are the contents of the mail plus the headers. This is handy
if you want to use a custom subject or ``X-`` header::
handler = MailHandler(format_string='''\
Subject: {record.level_name} on My Application
{record.message}
{record.extra[a_custom_injected_record]}
''')
This handler will always emit text-only mails for maximum portability and
best performance.
In the default setting it delivers all log records but it can be set up
to not send more than n mails for the same record each hour to not
overload an inbox and the network in case a message is triggered multiple
times a minute. The following example limits it to 60 mails an hour::
from datetime import timedelta
handler = MailHandler(record_limit=1,
record_delta=timedelta(minutes=1))
The default timedelta is 60 seconds (one minute).
The mail handler is sending mails in a blocking manner. If you are not
using some centralized system for logging these messages (with the help
of ZeroMQ or others) and the logging system slows you down you can
wrap the handler in a :class:`logbook.queues.ThreadedWrapperHandler`
that will then send the mails in a background thread.
.. versionchanged:: 0.3
The handler supports the batching system now.
"""
default_format_string = MAIL_FORMAT_STRING
default_related_format_string = MAIL_RELATED_FORMAT_STRING
default_subject = u('Server Error in Application')
#: the maximum number of record hashes in the cache for the limiting
#: feature. Afterwards, record_cache_prune percent of the oldest
#: entries are removed
max_record_cache = 512
#: the number of items to prune on a cache overflow in percent.
record_cache_prune = 0.333
def __init__(self, from_addr, recipients, subject=None,
server_addr=None, credentials=None, secure=None,
record_limit=None, record_delta=None, level=NOTSET,
format_string=None, related_format_string=None,
filter=None, bubble=False):
Handler.__init__(self, level, filter, bubble)
StringFormatterHandlerMixin.__init__(self, format_string)
LimitingHandlerMixin.__init__(self, record_limit, record_delta)
self.from_addr = from_addr
self.recipients = recipients
if subject is None:
subject = self.default_subject
self.subject = subject
self.server_addr = server_addr
self.credentials = credentials
self.secure = secure
if related_format_string is None:
related_format_string = self.default_related_format_string
self.related_format_string = related_format_string
def _get_related_format_string(self):
if isinstance(self.related_formatter, StringFormatter):
return self.related_formatter.format_string
def _set_related_format_string(self, value):
if value is None:
self.related_formatter = None
else:
self.related_formatter = self.formatter_class(value)
related_format_string = property(_get_related_format_string,
_set_related_format_string)
del _get_related_format_string, _set_related_format_string
def get_recipients(self, record):
"""Returns the recipients for a record. By default the
:attr:`recipients` attribute is returned for all records.
"""
return self.recipients
def message_from_record(self, record, suppressed):
"""Creates a new message for a record as email message object
(:class:`email.message.Message`). `suppressed` is the number
of mails not sent if the `record_limit` feature is active.
"""
from email.message import Message
from email.header import Header
msg = Message()
msg.set_charset('utf-8')
lineiter = iter(self.format(record).splitlines())
for line in lineiter:
if not line:
break
h, v = line.split(':', 1)
# We could probably just encode everything. For the moment encode
# only what really needed to avoid breaking a couple of tests.
try:
v.encode('ascii')
except UnicodeEncodeError:
msg[h.strip()] = Header(v.strip(), 'utf-8')
else:
msg[h.strip()] = v.strip()
msg.replace_header('Content-Transfer-Encoding', '8bit')
body = '\r\n'.join(lineiter)
if suppressed:
body += '\r\n\r\nThis message occurred additional %d ' \
'time(s) and was suppressed' % suppressed
# inconsistency in Python 2.5
# other versions correctly return msg.get_payload() as str
if sys.version_info < (2, 6) and isinstance(body, unicode):
body = body.encode('utf-8')
msg.set_payload(body, 'UTF-8')
return msg
def format_related_record(self, record):
"""Used for format the records that led up to another record or
records that are related into strings. Used by the batch formatter.
"""
return self.related_formatter(record, self)
def generate_mail(self, record, suppressed=0):
"""Generates the final email (:class:`email.message.Message`)
with headers and date. `suppressed` is the number of mails
that were not send if the `record_limit` feature is active.
"""
from email.utils import formatdate
msg = self.message_from_record(record, suppressed)
msg['From'] = self.from_addr
msg['Date'] = formatdate()
return msg
def collapse_mails(self, mail, related, reason):
"""When escaling or grouped mails are """
if not related:
return mail
if reason == 'group':
title = 'Other log records in the same group'
else:
title = 'Log records that led up to this one'
mail.set_payload('%s\r\n\r\n\r\n%s:\r\n\r\n%s' % (
mail.get_payload(),
title,
'\r\n\r\n'.join(body.rstrip() for body in related)
))
return mail
def get_connection(self):
"""Returns an SMTP connection. By default it reconnects for
each sent mail.
"""
from smtplib import SMTP, SMTP_PORT, SMTP_SSL_PORT
if self.server_addr is None:
host = 'localhost'
port = self.secure and SMTP_SSL_PORT or SMTP_PORT
else:
host, port = self.server_addr
con = SMTP()
con.connect(host, port)
if self.credentials is not None:
if self.secure is not None:
con.ehlo()
con.starttls(*self.secure)
con.ehlo()
con.login(*self.credentials)
return con
def close_connection(self, con):
"""Closes the connection that was returned by
:meth:`get_connection`.
"""
try:
if con is not None:
con.quit()
except Exception:
pass
def deliver(self, msg, recipients):
"""Delivers the given message to a list of recpients."""
con = self.get_connection()
try:
con.sendmail(self.from_addr, recipients, msg.as_string())
finally:
self.close_connection(con)
def emit(self, record):
suppressed = 0
if self.record_limit is not None:
suppressed, allow_delivery = self.check_delivery(record)
if not allow_delivery:
return
self.deliver(self.generate_mail(record, suppressed),
self.get_recipients(record))
def emit_batch(self, records, reason):
if reason not in ('escalation', 'group'):
return MailHandler.emit_batch(self, records, reason)
records = list(records)
if not records:
return
trigger = records.pop(reason == 'escalation' and -1 or 0)
suppressed = 0
if self.record_limit is not None:
suppressed, allow_delivery = self.check_delivery(trigger)
if not allow_delivery:
return
trigger_mail = self.generate_mail(trigger, suppressed)
related = [self.format_related_record(record)
for record in records]
self.deliver(self.collapse_mails(trigger_mail, related, reason),
self.get_recipients(trigger))
class GMailHandler(MailHandler):
"""
A customized mail handler class for sending emails via GMail (or Google Apps mail)::
handler = GMailHandler("my_user@gmail.com", "mypassword", ["to_user@some_mail.com"], ...) # other arguments same as MailHandler
.. versionadded:: 0.6.0
"""
def __init__(self, account_id, password, recipients, **kw):
super(GMailHandler, self).__init__(
account_id, recipients, secure=(), server_addr=("smtp.gmail.com", 587),
credentials=(account_id, password), **kw)
class SyslogHandler(Handler, StringFormatterHandlerMixin):
"""A handler class which sends formatted logging records to a
syslog server. By default it will send to it via unix socket.
"""
default_format_string = SYSLOG_FORMAT_STRING
# priorities
LOG_EMERG = 0 # system is unusable
LOG_ALERT = 1 # action must be taken immediately
LOG_CRIT = 2 # critical conditions
LOG_ERR = 3 # error conditions
LOG_WARNING = 4 # warning conditions
LOG_NOTICE = 5 # normal but significant condition
LOG_INFO = 6 # informational
LOG_DEBUG = 7 # debug-level messages
# facility codes
LOG_KERN = 0 # kernel messages
LOG_USER = 1 # random user-level messages
LOG_MAIL = 2 # mail system
LOG_DAEMON = 3 # system daemons
LOG_AUTH = 4 # security/authorization messages
LOG_SYSLOG = 5 # messages generated internally by syslogd
LOG_LPR = 6 # line printer subsystem
LOG_NEWS = 7 # network news subsystem
LOG_UUCP = 8 # UUCP subsystem
LOG_CRON = 9 # clock daemon
LOG_AUTHPRIV = 10 # security/authorization messages (private)
LOG_FTP = 11 # FTP daemon
# other codes through 15 reserved for system use
LOG_LOCAL0 = 16 # reserved for local use
LOG_LOCAL1 = 17 # reserved for local use
LOG_LOCAL2 = 18 # reserved for local use
LOG_LOCAL3 = 19 # reserved for local use
LOG_LOCAL4 = 20 # reserved for local use
LOG_LOCAL5 = 21 # reserved for local use
LOG_LOCAL6 = 22 # reserved for local use
LOG_LOCAL7 = 23 # reserved for local use
facility_names = {
'auth': LOG_AUTH,
'authpriv': LOG_AUTHPRIV,
'cron': LOG_CRON,
'daemon': LOG_DAEMON,
'ftp': LOG_FTP,
'kern': LOG_KERN,
'lpr': LOG_LPR,
'mail': LOG_MAIL,
'news': LOG_NEWS,
'syslog': LOG_SYSLOG,
'user': LOG_USER,
'uucp': LOG_UUCP,
'local0': LOG_LOCAL0,
'local1': LOG_LOCAL1,
'local2': LOG_LOCAL2,
'local3': LOG_LOCAL3,
'local4': LOG_LOCAL4,
'local5': LOG_LOCAL5,
'local6': LOG_LOCAL6,
'local7': LOG_LOCAL7,
}
level_priority_map = {
DEBUG: LOG_DEBUG,
INFO: LOG_INFO,
NOTICE: LOG_NOTICE,
WARNING: LOG_WARNING,
ERROR: LOG_ERR,
CRITICAL: LOG_CRIT
}
def __init__(self, application_name=None, address=None,
facility='user', socktype=socket.SOCK_DGRAM,
level=NOTSET, format_string=None, filter=None,
bubble=False):
Handler.__init__(self, level, filter, bubble)
StringFormatterHandlerMixin.__init__(self, format_string)
self.application_name = application_name
if address is None:
if sys.platform == 'darwin':
address = '/var/run/syslog'
else:
address = '/dev/log'
self.address = address
self.facility = facility
self.socktype = socktype
if isinstance(address, string_types):
self._connect_unixsocket()
else:
self._connect_netsocket()
def _connect_unixsocket(self):
self.unixsocket = True
self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
try:
self.socket.connect(self.address)
except socket.error:
self.socket.close()
self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.socket.connect(self.address)
def _connect_netsocket(self):
self.unixsocket = False
self.socket = socket.socket(socket.AF_INET, self.socktype)
if self.socktype == socket.SOCK_STREAM:
self.socket.connect(self.address)
self.address = self.socket.getsockname()
def encode_priority(self, record):
facility = self.facility_names[self.facility]
priority = self.level_priority_map.get(record.level,
self.LOG_WARNING)
return (facility << 3) | priority
def emit(self, record):
prefix = u('')
if self.application_name is not None:
prefix = self.application_name + u(':')
self.send_to_socket((u('<%d>%s%s\x00') % (
self.encode_priority(record),
prefix,
self.format(record)
)).encode('utf-8'))
def send_to_socket(self, data):
if self.unixsocket:
try:
self.socket.send(data)
except socket.error:
self._connect_unixsocket()
self.socket.send(data)
elif self.socktype == socket.SOCK_DGRAM:
# the flags are no longer optional on Python 3
self.socket.sendto(data, 0, self.address)
else:
self.socket.sendall(data)
def close(self):
self.socket.close()
class NTEventLogHandler(Handler, StringFormatterHandlerMixin):
"""A handler that sends to the NT event log system."""
dllname = None
default_format_string = NTLOG_FORMAT_STRING
def __init__(self, application_name, log_type='Application',
level=NOTSET, format_string=None, filter=None,
bubble=False):
Handler.__init__(self, level, filter, bubble)
StringFormatterHandlerMixin.__init__(self, format_string)
if os.name != 'nt':
raise RuntimeError('NTLogEventLogHandler requires a Windows '
'operating system.')
try:
import win32evtlogutil
import win32evtlog
except ImportError:
raise RuntimeError('The pywin32 library is required '
'for the NTEventLogHandler.')
self.application_name = application_name
self._welu = win32evtlogutil
dllname = self.dllname
if not dllname:
dllname = os.path.join(os.path.dirname(self._welu.__file__),
'../win32service.pyd')
self.log_type = log_type
self._welu.AddSourceToRegistry(self.application_name, dllname,
log_type)
self._default_type = win32evtlog.EVENTLOG_INFORMATION_TYPE
self._type_map = {
DEBUG: win32evtlog.EVENTLOG_INFORMATION_TYPE,
INFO: win32evtlog.EVENTLOG_INFORMATION_TYPE,
NOTICE: win32evtlog.EVENTLOG_INFORMATION_TYPE,
WARNING: win32evtlog.EVENTLOG_WARNING_TYPE,
ERROR: win32evtlog.EVENTLOG_ERROR_TYPE,
CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE
}
def unregister_logger(self):
"""Removes the application binding from the registry. If you call
this, the log viewer will no longer be able to provide any
information about the message.
"""
self._welu.RemoveSourceFromRegistry(self.application_name,
self.log_type)
def get_event_type(self, record):
return self._type_map.get(record.level, self._default_type)
def get_event_category(self, record):
return 0
def get_message_id(self, record):
return 1
def emit(self, record):
id = self.get_message_id(record)
cat = self.get_event_category(record)
type = self.get_event_type(record)
self._welu.ReportEvent(self.application_name, id, cat, type,
[self.format(record)])
class FingersCrossedHandler(Handler):
"""This handler wraps another handler and will log everything in
memory until a certain level (`action_level`, defaults to `ERROR`)
is exceeded. When that happens the fingers crossed handler will
activate forever and log all buffered records as well as records
yet to come into another handled which was passed to the constructor.
Alternatively it's also possible to pass a factory function to the
constructor instead of a handler. That factory is then called with
the triggering log entry and the finger crossed handler to create
a handler which is then cached.
The idea of this handler is to enable debugging of live systems. For
example it might happen that code works perfectly fine 99% of the time,
but then some exception happens. But the error that caused the
exception alone might not be the interesting bit, the interesting
information were the warnings that lead to the error.
Here a setup that enables this for a web application::
from logbook import FileHandler
from logbook import FingersCrossedHandler
def issue_logging():
def factory(record, handler):
return FileHandler('/var/log/app/issue-%s.log' % record.time)
return FingersCrossedHandler(factory)
def application(environ, start_response):
with issue_logging():
return the_actual_wsgi_application(environ, start_response)
Whenever an error occours, a new file in ``/var/log/app`` is created
with all the logging calls that lead up to the error up to the point
where the `with` block is exited.
Please keep in mind that the :class:`~logbook.FingersCrossedHandler`
handler is a one-time handler. Once triggered, it will not reset. Because
of that you will have to re-create it whenever you bind it. In this case
the handler is created when it's bound to the thread.
Due to how the handler is implemented, the filter, bubble and level
flags of the wrapped handler are ignored.
.. versionchanged:: 0.3
The default behaviour is to buffer up records and then invoke another
handler when a severity theshold was reached with the buffer emitting.
This now enables this logger to be properly used with the
:class:`~logbook.MailHandler`. You will now only get one mail for
each bfufered record. However once the threshold was reached you would
still get a mail for each record which is why the `reset` flag was added.
When set to `True`, the handler will instantly reset to the untriggered
state and start buffering again::
handler = FingersCrossedHandler(MailHandler(...),
buffer_size=10,
reset=True)
.. versionadded:: 0.3
The `reset` flag was added.
"""
#: the reason to be used for the batch emit. The default is
#: ``'escalation'``.
#:
#: .. versionadded:: 0.3
batch_emit_reason = 'escalation'
def __init__(self, handler, action_level=ERROR, buffer_size=0,
pull_information=True, reset=False, filter=None,
bubble=False):
Handler.__init__(self, NOTSET, filter, bubble)
self.lock = Lock()
self._level = action_level
if isinstance(handler, Handler):
self._handler = handler
self._handler_factory = None
else:
self._handler = None
self._handler_factory = handler
#: the buffered records of the handler. Once the action is triggered
#: (:attr:`triggered`) this list will be None. This attribute can
#: be helpful for the handler factory function to select a proper
#: filename (for example time of first log record)
self.buffered_records = deque()
#: the maximum number of entries in the buffer. If this is exhausted
#: the oldest entries will be discarded to make place for new ones
self.buffer_size = buffer_size
self._buffer_full = False
self._pull_information = pull_information
self._action_triggered = False
self._reset = reset
def close(self):
if self._handler is not None:
self._handler.close()
def enqueue(self, record):
if self._pull_information:
record.pull_information()
if self._action_triggered:
self._handler.emit(record)
else:
self.buffered_records.append(record)
if self._buffer_full:
self.buffered_records.popleft()
elif self.buffer_size and \
len(self.buffered_records) >= self.buffer_size:
self._buffer_full = True
return record.level >= self._level
return False
def rollover(self, record):
if self._handler is None:
self._handler = self._handler_factory(record, self)
self._handler.emit_batch(iter(self.buffered_records), 'escalation')
self.buffered_records.clear()
self._action_triggered = not self._reset
@property
def triggered(self):
"""This attribute is `True` when the action was triggered. From
this point onwards the finger crossed handler transparently
forwards all log records to the inner handler. If the handler resets
itself this will always be `False`.
"""
return self._action_triggered
def emit(self, record):
self.lock.acquire()
try:
if self.enqueue(record):
self.rollover(record)
finally:
self.lock.release()
class GroupHandler(WrapperHandler):
"""A handler that buffers all messages until it is popped again and then
forwards all messages to another handler. This is useful if you for
example have an application that does computations and only a result
mail is required. A group handler makes sure that only one mail is sent
and not multiple. Some other handles might support this as well, though
currently none of the builtins do.
Example::
with GroupHandler(MailHandler(...)):
# everything here ends up in the mail
The :class:`GroupHandler` is implemented as a :class:`WrapperHandler`
thus forwarding all attributes of the wrapper handler.
Notice that this handler really only emit the records when the handler
is popped from the stack.
.. versionadded:: 0.3
"""
_direct_attrs = frozenset(['handler', 'pull_information',
'buffered_records'])
def __init__(self, handler, pull_information=True):
WrapperHandler.__init__(self, handler)
self.pull_information = pull_information
self.buffered_records = []
def rollover(self):
self.handler.emit_batch(self.buffered_records, 'group')
self.buffered_records = []
def pop_application(self):
Handler.pop_application(self)
self.rollover()
def pop_thread(self):
Handler.pop_thread(self)
self.rollover()
def emit(self, record):
if self.pull_information:
record.pull_information()
self.buffered_records.append(record)
| {
"content_hash": "0e11853e0923ca6d63298919273a7590",
"timestamp": "",
"source": "github",
"line_count": 1631,
"max_line_length": 134,
"avg_line_length": 37.06866952789699,
"alnum_prop": 0.608114590052763,
"repo_name": "dplepage/logbook",
"id": "8725e98f4b24795b1714d769a44f5c9bbb6133c4",
"size": "60483",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "logbook/handlers.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
Package.describe({
name: 'ostrio:mailer',
version: '1.0.1',
summary: 'Emails queue with schedule and support of HTML-Templates, and custom SMTP connection',
git: 'https://github.com/VeliovGroup/Meteor-Mailer',
documentation: 'README.md'
});
Package.onUse(function(api) {
api.versionsFrom('1.0');
api.addFiles('ostrio:mailer.coffee', 'server');
api.use(['mongo', 'check', 'sha', 'coffeescript', 'templating', 'email', 'spacebars', 'meteorhacks:ssr@2.1.1', 'underscore', 'ostrio:jsextensions@0.0.4'], 'server');
});
| {
"content_hash": "91a734e4d46d53d2e275d8f2f37b0270",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 167,
"avg_line_length": 40.84615384615385,
"alnum_prop": 0.6854990583804144,
"repo_name": "satyavh/Meteor-Mailer",
"id": "16fcfe796d3b7dd6156761d1a6be46e94c7a5ad3",
"size": "531",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "package.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "7483"
},
{
"name": "JavaScript",
"bytes": "531"
}
],
"symlink_target": ""
} |
#include <string.h>
#include <ctype.h>
#include <espressif/esp_common.h>
#include <espressif/user_interface.h>
#include <esp/uart.h>
#include <FreeRTOS.h>
#include <task.h>
#include "lwip/sockets.h"
#include "wificfg/wificfg.h"
#include "sysparam.h"
static const char http_success_header[] = "HTTP/1.1 200 \r\n"
"Content-Type: text/html; charset=utf-8\r\n"
"Cache-Control: no-store\r\n"
"Transfer-Encoding: chunked\r\n"
"Connection: close\r\n"
"\r\n";
static const char *http_index_content[] = {
#include "content/index.html"
};
static int handle_index(int s, wificfg_method method,
uint32_t content_length,
wificfg_content_type content_type,
char *buf, size_t len)
{
if (wificfg_write_string(s, http_success_header) < 0) return -1;
if (method != HTTP_METHOD_HEAD) {
if (wificfg_write_string_chunk(s, http_index_content[0], buf, len) < 0) return -1;
if (wificfg_write_html_title(s, buf, len, "Home") < 0) return -1;
if (wificfg_write_string_chunk(s, http_index_content[1], buf, len) < 0) return -1;
if (wificfg_write_string_chunk(s, "<dl class=\"dlh\">", buf, len) < 0) return -1;
struct sockaddr_storage addr;
socklen_t addr_len = sizeof(addr);
if (getpeername(s, (struct sockaddr *)&addr, &addr_len) == 0) {
if (((struct sockaddr *)&addr)->sa_family == AF_INET) {
struct sockaddr_in *sa = (struct sockaddr_in *)&addr;
if (wificfg_write_string_chunk(s, "<dt>Peer address</dt>", buf, len) < 0) return -1;
snprintf(buf, len, "<dd>" IPSTR ", port %u</dd>",
IP2STR((ip4_addr_t *)&sa->sin_addr.s_addr), ntohs(sa->sin_port));
if (wificfg_write_string_chunk(s, buf, buf, len) < 0) return -1;
}
#if LWIP_IPV6
if (((struct sockaddr *)&addr)->sa_family == AF_INET6) {
struct sockaddr_in6 *sa = (struct sockaddr_in6 *)&addr;
if (wificfg_write_string_chunk(s, "<dt>Peer address</dt><dd>", buf, len) < 0) return -1;
if (inet6_ntoa_r(sa->sin6_addr, buf, len)) {
if (wificfg_write_string_chunk(s, buf, buf, len) < 0) return -1;
}
snprintf(buf, len, ", port %u</dd>", ntohs(sa->sin6_port));
if (wificfg_write_string_chunk(s, buf, buf, len) < 0) return -1;
}
#endif
}
if (wificfg_write_string_chunk(s, "</dl>", buf, len) < 0) return -1;
if (wificfg_write_string_chunk(s, http_index_content[2], buf, len) < 0) return -1;
if (wificfg_write_chunk_end(s) < 0) return -1;
}
return 0;
}
static const wificfg_dispatch dispatch_list[] = {
{"/", HTTP_METHOD_GET, handle_index, false},
{"/index.html", HTTP_METHOD_GET, handle_index, false},
{NULL, HTTP_METHOD_ANY, NULL}
};
void user_init(void)
{
uart_set_baud(0, 115200);
printf("SDK version:%s\n", sdk_system_get_sdk_version());
sdk_wifi_set_sleep_type(WIFI_SLEEP_MODEM);
wificfg_init(80, dispatch_list);
}
| {
"content_hash": "0a933073a558b9f6947b5341a7b59d34",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 104,
"avg_line_length": 35.94252873563219,
"alnum_prop": 0.5692356891589383,
"repo_name": "bhuvanchandra/esp-open-rtos",
"id": "33e70c025a778767c0718f83a0d98ceb7ebb7753",
"size": "3961",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "examples/wificfg/wificfg.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "25452"
},
{
"name": "C",
"bytes": "1587468"
},
{
"name": "C++",
"bytes": "149091"
},
{
"name": "Emacs Lisp",
"bytes": "775"
},
{
"name": "Makefile",
"bytes": "28149"
},
{
"name": "Python",
"bytes": "3583"
},
{
"name": "Shell",
"bytes": "2789"
}
],
"symlink_target": ""
} |
function validate() {
var artist = document.getElementById('artist').value;
var error = document.getElementById('error');
if (artist.indexOf('soundcloud.com/') != -1) {
var pattern = new RegExp('soundcloud\.com/([^/]*)');
var match = pattern.exec(artist);
if (match == null) {
error.innerText = 'Invalid username: "' + artist + '"';
return false;
}
artist = match[1];
}
var r = Boolean(artist.match(/^[a-z0-9_-]+$/i));
if (!r) {
error.innerText = 'Invalid username: "' + artist + '"';
}
return r;
}
| {
"content_hash": "3a725fe82965c8666d540a85b84c3fc8",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 67,
"avg_line_length": 25.375,
"alnum_prop": 0.5254515599343186,
"repo_name": "mtimkovich/top_tracks",
"id": "03462f0748c82148760e341a0002b4f28d7542f5",
"size": "609",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "static/validate.js",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "HTML",
"bytes": "2081"
},
{
"name": "JavaScript",
"bytes": "871"
},
{
"name": "Python",
"bytes": "3123"
}
],
"symlink_target": ""
} |
<?php
/**
* A view represents the presentation layer of an action. Output can be
* customized by supplying attributes, which a template can manipulate and
* display.
*
* @package symfony
* @subpackage view
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @author Sean Kerr <sean@code-box.org>
* @version SVN: $Id: sfView.class.php 28713 2010-03-23 15:08:22Z fabien $
*/
abstract class sfView
{
/**
* Show an alert view.
*/
const ALERT = 'Alert';
/**
* Show an error view.
*/
const ERROR = 'Error';
/**
* Show a form input view.
*/
const INPUT = 'Input';
/**
* Skip view execution.
*/
const NONE = 'None';
/**
* Show a success view.
*/
const SUCCESS = 'Success';
/**
* Do not render the presentation.
*/
const RENDER_NONE = 1;
/**
* Render the presentation to the client.
*/
const RENDER_CLIENT = 2;
/**
* Render the presentation to a variable.
*/
const RENDER_VAR = 4;
/**
* Skip view rendering but output http headers
*/
const HEADER_ONLY = 8;
protected
$context = null,
$dispatcher = null,
$decorator = false,
$decoratorDirectory = null,
$decoratorTemplate = null,
$directory = null,
$componentSlots = array(),
$template = null,
$attributeHolder = null,
$parameterHolder = null,
$moduleName = '',
$actionName = '',
$viewName = '',
$extension = '.php';
/**
* Class constructor.
*
* @see initialize()
*/
public function __construct($context, $moduleName, $actionName, $viewName)
{
$this->initialize($context, $moduleName, $actionName, $viewName);
}
/**
* Initializes this view.
*
* @param sfContext $context The current application context
* @param string $moduleName The module name for this view
* @param string $actionName The action name for this view
* @param string $viewName The view name
*
* @return bool true, if initialization completes successfully, otherwise false
*/
public function initialize($context, $moduleName, $actionName, $viewName)
{
$this->moduleName = $moduleName;
$this->actionName = $actionName;
$this->viewName = $viewName;
$this->context = $context;
$this->dispatcher = $context->getEventDispatcher();
sfOutputEscaper::markClassesAsSafe(array('sfForm', 'sfFormField', 'sfFormFieldSchema', 'sfModelGeneratorHelper'));
$this->attributeHolder = $this->initializeAttributeHolder();
$this->parameterHolder = new sfParameterHolder();
$this->parameterHolder->add(sfConfig::get('mod_'.strtolower($moduleName).'_view_param', array()));
$request = $context->getRequest();
$format = $request->getRequestFormat();
if (null !== $format)
{
if ('html' != $format)
{
$this->setExtension('.'.$format.$this->getExtension());
}
if ($mimeType = $request->getMimeType($format))
{
$this->context->getResponse()->setContentType($mimeType);
if ('html' != $format)
{
$this->setDecorator(false);
}
}
}
$this->dispatcher->notify(new sfEvent($this, 'view.configure_format', array('format' => $format, 'response' => $context->getResponse(), 'request' => $context->getRequest())));
// include view configuration
$this->configure();
return true;
}
protected function initializeAttributeHolder($attributes = array())
{
if ('both' === sfConfig::get('sf_escaping_strategy'))
{
$this->dispatcher->notify(new sfEvent($this, 'application.log', array('Escaping strategy "both" is deprecated, please use "on".', 'priority' => sfLogger::ERR)));
sfConfig::set('sf_escaping_strategy', 'on');
}
else if ('bc' === sfConfig::get('sf_escaping_strategy'))
{
$this->dispatcher->notify(new sfEvent($this, 'application.log', array('Escaping strategy "bc" is deprecated, please use "off".', 'priority' => sfLogger::ERR)));
sfConfig::set('sf_escaping_strategy', 'off');
}
$attributeHolder = new sfViewParameterHolder($this->dispatcher, $attributes, array(
'escaping_method' => sfConfig::get('sf_escaping_method'),
'escaping_strategy' => sfConfig::get('sf_escaping_strategy'),
));
return $attributeHolder;
}
/**
* Executes any presentation logic and set template attributes.
*/
abstract function execute();
/**
* Configures template.
*/
abstract function configure();
/**
* Retrieves this views decorator template directory.
*
* @return string An absolute filesystem path to this views decorator template directory
*/
public function getDecoratorDirectory()
{
return $this->decoratorDirectory;
}
/**
* Retrieves this views decorator template.
*
* @return string A template filename, if a template has been set, otherwise null
*/
public function getDecoratorTemplate()
{
return $this->decoratorTemplate;
}
/**
* Retrieves this view template directory.
*
* @return string An absolute filesystem path to this views template directory
*/
public function getDirectory()
{
return $this->directory;
}
/**
* Retrieves the template engine associated with this view.
*
* Note: This will return null for PHPView instances.
*
* @return mixed A template engine instance
*/
abstract function getEngine();
/**
* Retrieves this views template.
*
* @return string A template filename, if a template has been set, otherwise null
*/
public function getTemplate()
{
return $this->template;
}
/**
* Retrieves attributes for the current view.
*
* @return sfParameterHolder The attribute parameter holder
*/
public function getAttributeHolder()
{
return $this->attributeHolder;
}
/**
* Retrieves an attribute for the current view.
*
* @param string $name Name of the attribute
* @param string $default Value of the attribute
*
* @return mixed Attribute
*/
public function getAttribute($name, $default = null)
{
return $this->attributeHolder->get($name, $default);
}
/**
* Returns true if the view have attributes.
*
* @param string $name Name of the attribute
*
* @return mixed Attribute of the view
*/
public function hasAttribute($name)
{
return $this->attributeHolder->has($name);
}
/**
* Sets an attribute of the view.
*
* @param string $name Attribute name
* @param string $value Value for the attribute
*/
public function setAttribute($name, $value)
{
$this->attributeHolder->set($name, $value);
}
/**
* Retrieves the parameters for the current view.
*
* @return sfParameterHolder The parameter holder
*/
public function getParameterHolder()
{
return $this->parameterHolder;
}
/**
* Retrieves a parameter from the current view.
*
* @param string $name Parameter name
* @param string $default Default parameter value
*
* @return mixed A parameter value
*/
public function getParameter($name, $default = null)
{
return $this->parameterHolder->get($name, $default);
}
/**
* Indicates whether or not a parameter exist for the current view.
*
* @param string $name Name of the parameter
*
* @return bool true, if the parameter exists otherwise false
*/
public function hasParameter($name)
{
return $this->parameterHolder->has($name);
}
/**
* Sets a parameter for the view.
*
* @param string $name Name of the parameter
* @param string $value The parameter value
*/
public function setParameter($name, $value)
{
$this->parameterHolder->set($name, $value);
}
/**
* Indicates that this view is a decorating view.
*
* @return bool true, if this view is a decorating view, otherwise false
*/
public function isDecorator()
{
return $this->decorator;
}
/**
* Sets the decorating mode for the current view.
*
* @param bool $boolean Set the decorating mode for the view
*/
public function setDecorator($boolean)
{
$this->decorator = (boolean) $boolean;
if (false === $boolean)
{
$this->decoratorTemplate = false;
}
}
/**
* Executes a basic pre-render check to verify all required variables exist
* and that the template is readable.
*
* @throws sfRenderException If the pre-render check fails
*/
protected function preRenderCheck()
{
if (null === $this->template)
{
// a template has not been set
throw new sfRenderException('A template has not been set.');
}
if (!is_readable($this->directory.'/'.$this->template))
{
// 404?
if ('404' == $this->context->getResponse()->getStatusCode())
{
// use default exception templates
$this->template = sfException::getTemplatePathForError($this->context->getRequest()->getRequestFormat(), false);
$this->directory = dirname($this->template);
$this->template = basename($this->template);
$this->setAttribute('code', '404');
$this->setAttribute('text', 'Not Found');
}
else
{
throw new sfRenderException(sprintf('The template "%s" does not exist or is unreadable in "%s".', $this->template, $this->directory));
}
}
}
/**
* Renders the presentation.
*
* @return string A string representing the rendered presentation
*/
abstract function render();
/**
* Sets the decorator template directory for this view.
*
* @param string $directory An absolute filesystem path to a template directory
*/
public function setDecoratorDirectory($directory)
{
$this->decoratorDirectory = $directory;
}
/**
* Sets the decorator template for this view.
*
* If the template path is relative, it will be based on the currently
* executing module's template sub-directory.
*
* @param string $template An absolute or relative filesystem path to a template
*/
public function setDecoratorTemplate($template)
{
if (false === $template)
{
$this->setDecorator(false);
return;
}
else if (null === $template)
{
return;
}
if (!strpos($template, '.'))
{
$template .= $this->getExtension();
}
if (sfToolkit::isPathAbsolute($template))
{
$this->decoratorDirectory = dirname($template);
$this->decoratorTemplate = basename($template);
}
else
{
$this->decoratorDirectory = $this->context->getConfiguration()->getDecoratorDir($template);
$this->decoratorTemplate = $template;
}
// set decorator status
$this->decorator = true;
}
/**
* Sets the template directory for this view.
*
* @param string $directory An absolute filesystem path to a template directory
*/
public function setDirectory($directory)
{
$this->directory = $directory;
}
/**
* Sets the module and action to be executed in place of a particular template attribute.
*
* @param string $attributeName A template attribute name
* @param string $moduleName A module name
* @param string $componentName A component name
*/
public function setComponentSlot($attributeName, $moduleName, $componentName)
{
$this->componentSlots[$attributeName] = array();
$this->componentSlots[$attributeName]['module_name'] = $moduleName;
$this->componentSlots[$attributeName]['component_name'] = $componentName;
}
/**
* Indicates whether or not a component slot exists.
*
* @param string $name The component slot name
*
* @return bool true, if the component slot exists, otherwise false
*/
public function hasComponentSlot($name)
{
return isset($this->componentSlots[$name]);
}
/**
* Gets a component slot
*
* @param string $name The component slot name
*
* @return array The component slot
*/
public function getComponentSlot($name)
{
if (isset($this->componentSlots[$name]) && $this->componentSlots[$name]['module_name'] && $this->componentSlots[$name]['component_name'])
{
return array($this->componentSlots[$name]['module_name'], $this->componentSlots[$name]['component_name']);
}
return null;
}
/**
* Sets the template for this view.
*
* If the template path is relative, it will be based on the currently
* executing module's template sub-directory.
*
* @param string $template An absolute or relative filesystem path to a template
*/
public function setTemplate($template)
{
if (sfToolkit::isPathAbsolute($template))
{
$this->directory = dirname($template);
$this->template = basename($template);
}
else
{
$this->directory = $this->context->getConfiguration()->getTemplateDir($this->moduleName, $template);
$this->template = $template;
}
}
/**
* Retrieves the current view extension.
*
* @return string The extension for current view.
*/
public function getExtension()
{
return $this->extension;
}
/**
* Sets an extension for the current view.
*
* @param string $extension The extension name.
*/
public function setExtension($extension)
{
$this->extension = $extension;
}
/**
* Gets the module name associated with this view.
*
* @return string A module name
*/
public function getModuleName()
{
return $this->moduleName;
}
/**
* Gets the action name associated with this view.
*
* @return string An action name
*/
public function getActionName()
{
return $this->actionName;
}
/**
* Gets the view name associated with this view.
*
* @return string An action name
*/
public function getViewName()
{
return $this->viewName;
}
/**
* Calls methods defined via sfEventDispatcher.
*
* @param string $method The method name
* @param array $arguments The method arguments
*
* @return mixed The returned value of the called method
*
* @throws sfException< If the calls fails
*/
public function __call($method, $arguments)
{
$event = $this->dispatcher->notifyUntil(new sfEvent($this, 'view.method_not_found', array('method' => $method, 'arguments' => $arguments)));
if (!$event->isProcessed())
{
throw new sfException(sprintf('Call to undefined method %s::%s.', get_class($this), $method));
}
return $event->getReturnValue();
}
}
| {
"content_hash": "8647e22cc45cdaca5a69babef5443fad",
"timestamp": "",
"source": "github",
"line_count": 576,
"max_line_length": 179,
"avg_line_length": 25.40451388888889,
"alnum_prop": 0.6293309642588669,
"repo_name": "nationalfield/symfony",
"id": "f1c2dc8210e9de5dab62876c420f1d9ab3e865e7",
"size": "14934",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "lib/view/sfView.class.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "222765"
},
{
"name": "PHP",
"bytes": "4264872"
},
{
"name": "Perl",
"bytes": "2753"
},
{
"name": "Shell",
"bytes": "710"
}
],
"symlink_target": ""
} |
/**
* @file peer_manager.h
*
* @defgroup peer_manager Peer Manager
* @ingroup ble_sdk_lib
* @{
* @brief Module for managing BLE bonding, which includes controlling encryption and pairing
* procedures as well as persistently storing different pieces of data that must be stored
* when bonded.
*
* @details The API consists of functions for configuring the pairing and encryption behavior of the
* device and functions for manipulating the stored data.
*
* This module uses Flash Data Storage (FDS) to interface with persistent storage. The
* Peer Manager needs exclusive use of certain FDS file IDs and record keys. See
* @ref lib_fds_functionality_keys for more information.
*/
#ifndef PEER_MANAGER_H__
#define PEER_MANAGER_H__
#include <stdint.h>
#include <stdbool.h>
#include "sdk_common.h"
#include "headers/ble.h"
#include "ble_gap.h"
#include "peer_manager_types.h"
#include "peer_database.h"
#ifdef __cplusplus
extern "C" {
#endif
/**@brief Security status of a connection.
*/
typedef struct
{
uint8_t connected : 1; /**< @brief The connection is active (not disconnected). */
uint8_t encrypted : 1; /**< @brief Communication on this link is encrypted. */
uint8_t mitm_protected : 1; /**< @brief The encrypted communication is also protected against man-in-the-middle attacks. */
uint8_t bonded : 1; /**< @brief The peer is bonded with us. */
} pm_conn_sec_status_t;
/**@brief Types of events that can come from the @ref peer_manager module.
*/
typedef enum
{
PM_EVT_BONDED_PEER_CONNECTED, /**< @brief A connected peer has been identified as one with which we have a bond. When performing bonding with a peer for the first time, this event will not be sent until a new connection is established with the peer. When we are central, this event is always sent when the Peer Manager receives the @ref BLE_GAP_EVT_CONNECTED event. When we are peripheral, this event might in rare cases arrive later. */
PM_EVT_CONN_SEC_START, /**< @brief A security procedure has started on a link, initiated either locally or remotely. The security procedure is using the last parameters provided via @ref pm_sec_params_set. This event is always followed by either a @ref PM_EVT_CONN_SEC_SUCCEEDED or a @ref PM_EVT_CONN_SEC_FAILED event. This is an informational event; no action is needed for the procedure to proceed. */
PM_EVT_CONN_SEC_SUCCEEDED, /**< @brief A link has been encrypted, either as a result of a call to @ref pm_conn_secure or a result of an action by the peer. The event structure contains more information about the circumstances. This event might contain a peer ID with the value @ref PM_PEER_ID_INVALID, which means that the peer (central) used an address that could not be identified, but it used an encryption key (LTK) that is present in the database. */
PM_EVT_CONN_SEC_FAILED, /**< @brief A pairing or encryption procedure has failed. In some cases, this means that security is not possible on this link (temporarily or permanently). How to handle this error depends on the application. */
PM_EVT_CONN_SEC_CONFIG_REQ, /**< @brief The peer (central) has requested pairing, but a bond already exists with that peer. Reply by calling @ref pm_conn_sec_config_reply before the event handler returns. If no reply is sent, a default is used. */
PM_EVT_STORAGE_FULL, /**< @brief There is no more room for peer data in flash storage. To solve this problem, delete data that is not needed anymore and run a garbage collection procedure in FDS. */
PM_EVT_ERROR_UNEXPECTED, /**< @brief An unrecoverable error happened inside Peer Manager. An operation failed with the provided error. */
PM_EVT_PEER_DATA_UPDATE_SUCCEEDED, /**< @brief A piece of peer data was stored, updated, or cleared in flash storage. This event is sent for all successful changes to peer data, also those initiated internally in Peer Manager. To identify an operation, compare the store token in the event with the store token received during the initiating function call. Events from internally initiated changes might have invalid store tokens. */
PM_EVT_PEER_DATA_UPDATE_FAILED, /**< @brief A piece of peer data could not be stored, updated, or cleared in flash storage. This event is sent instead of @ref PM_EVT_PEER_DATA_UPDATE_SUCCEEDED for the failed operation. */
PM_EVT_PEER_DELETE_SUCCEEDED, /**< @brief A peer was cleared from flash storage, for example because a call to @ref pm_peer_delete succeeded. This event can also be sent as part of a call to @ref pm_peers_delete or internal cleanup. */
PM_EVT_PEER_DELETE_FAILED, /**< @brief A peer could not be cleared from flash storage. This event is sent instead of @ref PM_EVT_PEER_DELETE_SUCCEEDED for the failed operation. */
PM_EVT_PEERS_DELETE_SUCCEEDED, /**< @brief A call to @ref pm_peers_delete has completed successfully. Flash storage now contains no peer data. */
PM_EVT_PEERS_DELETE_FAILED, /**< @brief A call to @ref pm_peers_delete has failed, which means that at least one of the peers could not be deleted. Other peers might have been deleted, or might still be queued to be deleted. No more @ref PM_EVT_PEERS_DELETE_SUCCEEDED or @ref PM_EVT_PEERS_DELETE_FAILED events are sent until the next time @ref pm_peers_delete is called. */
PM_EVT_LOCAL_DB_CACHE_APPLIED, /**< @brief Local database values for a peer (taken from flash storage) have been provided to the SoftDevice. */
PM_EVT_LOCAL_DB_CACHE_APPLY_FAILED, /**< @brief Local database values for a peer (taken from flash storage) were rejected by the SoftDevice, which means that either the database has changed or the user has manually set the local database to an invalid value (using @ref pm_peer_data_store). */
PM_EVT_SERVICE_CHANGED_IND_SENT, /**< @brief A service changed indication has been sent to a peer, as a result of a call to @ref pm_local_database_has_changed. This event will be followed by a @ref PM_EVT_SERVICE_CHANGED_IND_CONFIRMED event if the peer acknowledges the indication. */
PM_EVT_SERVICE_CHANGED_IND_CONFIRMED, /**< @brief A service changed indication that was sent has been confirmed by a peer. The peer can now be considered aware that the local database has changed. */
} pm_evt_id_t;
/**@brief Parameters specific to the @ref PM_EVT_CONN_SEC_SUCCEEDED event.
*/
typedef struct
{
pm_conn_sec_procedure_t procedure; /**< @brief The procedure that led to securing the link. */
} pm_conn_secured_evt_t;
/**@brief Parameters specific to the @ref PM_EVT_CONN_SEC_FAILED event.
*/
typedef struct
{
pm_conn_sec_procedure_t procedure; /**< @brief The procedure that failed. */
pm_sec_error_code_t error; /**< @brief An error code that describes the failure. */
uint8_t error_src; /**< @brief The party that raised the error, see @ref BLE_GAP_SEC_STATUS_SOURCES. */
} pm_conn_secure_failed_evt_t;
/**@brief Actions that can be performed to peer data in persistent storage.
*/
typedef enum
{
PM_PEER_DATA_OP_UPDATE, /**< @brief Writing or overwriting the data. */
PM_PEER_DATA_OP_DELETE, /**< @brief Removing the data. */
} pm_peer_data_op_t;
/**@brief Parameters specific to the @ref PM_EVT_PEER_DATA_UPDATE_SUCCEEDED event.
*/
typedef struct
{
pm_peer_data_id_t data_id; /**< @brief The type of the data that was changed. */
pm_peer_data_op_t action; /**< @brief What happened to the data. */
uint8_t flash_changed : 1; /**< @brief If this is false, no operation was done in flash, because the value was already what it should be. Please note that in certain scenarios, this flag will be true even if the new value is the same as the old. */
pm_store_token_t token; /**< @brief Token that identifies the operation. For @ref PM_PEER_DATA_OP_DELETE actions, this token can be disregarded. For @ref PM_PEER_DATA_OP_UPDATE actions, compare this token with the token that is received from a call to a @ref PM_PEER_DATA_FUNCTIONS function. */
} pm_peer_data_update_succeeded_evt_t;
/**@brief Parameters specific to the @ref PM_EVT_PEER_DATA_UPDATE_FAILED event.
*/
typedef struct
{
pm_peer_data_id_t data_id; /**< @brief The type of the data that was supposed to be changed. */
pm_peer_data_op_t action; /**< @brief The action that failed. */
pm_store_token_t token; /**< @brief Token that identifies the operation. For @ref PM_PEER_DATA_OP_DELETE actions, this token can be disregarded. For @ref PM_PEER_DATA_OP_UPDATE actions, compare this token with the token that is received from a call to a @ref PM_PEER_DATA_FUNCTIONS function. */
ret_code_t error; /**< @brief An error code that describes the failure. */
} pm_peer_data_update_failed_t;
/**@brief Standard parameters for failure events.
*/
typedef struct
{
ret_code_t error; /**< @brief The error that occurred. */
} pm_failure_evt_t;
/**@brief An event from the @ref peer_manager module.
*
* @details The structure contains both standard parameters and parameters that are specific to some events.
*/
typedef struct
{
pm_evt_id_t evt_id; /**< @brief The type of the event. */
uint16_t conn_handle; /**< @brief The connection that this event pertains to, or @ref BLE_CONN_HANDLE_INVALID. */
pm_peer_id_t peer_id; /**< @brief The bonded peer that this event pertains to, or @ref PM_PEER_ID_INVALID. */
union
{
pm_conn_secured_evt_t conn_sec_succeeded; /**< @brief Parameters specific to the @ref PM_EVT_CONN_SEC_SUCCEEDED event. */
pm_conn_secure_failed_evt_t conn_sec_failed; /**< @brief Parameters specific to the @ref PM_EVT_CONN_SEC_FAILED event. */
pm_peer_data_update_succeeded_evt_t peer_data_update_succeeded; /**< @brief Parameters specific to the @ref PM_EVT_PEER_DATA_UPDATE_SUCCEEDED event. */
pm_peer_data_update_failed_t peer_data_update_failed; /**< @brief Parameters specific to the @ref PM_EVT_PEER_DATA_UPDATE_FAILED event. */
pm_failure_evt_t peer_delete_failed; /**< @brief Parameters specific to the @ref PM_EVT_PEER_DELETE_FAILED event. */
pm_failure_evt_t peers_delete_failed_evt; /**< @brief Parameters specific to the @ref PM_EVT_PEERS_DELETE_FAILED event. */
pm_failure_evt_t error_unexpected; /**< @brief Parameters specific to the @ref PM_EVT_PEER_DELETE_FAILED event. */
} params;
} pm_evt_t;
/**@brief Event handler for events from the @ref peer_manager module.
*
* @sa pm_register
*
* @param[in] p_event The event that has occurred.
*/
typedef void (*pm_evt_handler_t)(pm_evt_t const * p_event);
/**@brief Function for initializing the Peer Manager.
*
* @details You must initialize the Peer Manager before you can call any other Peer Manager
* functions.
*
* @retval NRF_SUCCESS If initialization was successful.
* @retval NRF_ERROR_INTERNAL If an internal error occurred.
*/
ret_code_t pm_init(void);
/**@brief Function for registering an event handler with the Peer Manager.
*
* @param[in] event_handler Callback for events from the @ref peer_manager module. @p event_handler
* is called for every event that the Peer Manager sends after this
* function is called.
*
* @retval NRF_SUCCESS If initialization was successful.
* @retval NRF_ERROR_NULL If @p event_handler was NULL.
* @retval NRF_ERROR_NO_MEM If no more registrations can happen.
* @retval NRF_ERROR_INVALID_STATE If the Peer Manager is not initialized.
*/
ret_code_t pm_register(pm_evt_handler_t event_handler);
/**@brief Function for providing pairing and bonding parameters to use for pairing procedures.
*
* @details Until this function is called, all bonding procedures that are initiated by the
* peer are rejected.
*
* This function can be called multiple times with different parameters, even with NULL as
* @p p_sec_params, in which case the Peer Manager starts rejecting all procedures again.
*
* @param[in] p_sec_params Security parameters to be used for subsequent security procedures.
*
* @retval NRF_SUCCESS If the parameters were set successfully.
* @retval NRF_ERROR_INVALID_PARAM If the combination of parameters is invalid.
* @retval NRF_ERROR_INVALID_STATE If the Peer Manager is not initialized.
* @retval NRF_ERROR_INTERNAL If an internal error occurred.
*/
ret_code_t pm_sec_params_set(ble_gap_sec_params_t * p_sec_params);
/**@brief Function for passing BLE events to the Peer Manager.
*
* @details For the module to work as expected, this function must be called with each BLE event
* from the SoftDevice. It must be called after @ref ble_conn_state_on_ble_evt, but before
* the application processes the event.
*
* Calling this function before @ref pm_init is safe, but without effect.
*
* @param[in] p_ble_evt BLE stack event that is dispatched to the function.
*/
void pm_on_ble_evt(ble_evt_t * p_ble_evt);
/**@brief Function for establishing encryption on a connection, and optionally establishing a bond.
*
* @details This function attempts to secure the link that is specified by @p conn_handle. It uses
* the parameters that were previously provided in a call to @ref pm_sec_params_set.
*
* If the connection is a master connection, calling this function starts a security
* procedure on the link. If we have keys from a previous bonding procedure with this peer
* and the keys meet the security requirements in the currently active sec_params, the
* function attempts to establish encryption with the existing keys. If no key exists, the
* function attempts to pair and bond according to the currently active sec_params.
*
* If the function completes successfully, a @ref PM_EVT_CONN_SEC_START event is sent.
* The procedure might be queued, in which case the @ref PM_EVT_CONN_SEC_START event is
* delayed until the procedure is initiated in the SoftDevice.
*
* If the connection is a slave connection, the function sends a security request to
* the peer (master). It is up to the peer then to initiate pairing or encryption.
* If the peer ignores the request, a @ref BLE_GAP_EVT_TIMEOUT event occurs
* with the source @ref BLE_GAP_TIMEOUT_SRC_SECURITY_REQUEST. Otherwise, the peer initiates
* security, in which case things happen as if the peer had initiated security itself.
* See @ref PM_EVT_CONN_SEC_START for information about peer-initiated security.
*
* @param[in] conn_handle Connection handle of the link as provided by the SoftDevice.
* @param[in] force_repairing Whether to force a pairing procedure even if there is an existing
* encryption key. This argument is relevant only for
* the central role. Recommended value: false.
*
* @retval NRF_SUCCESS If the operation completed successfully.
* @retval NRF_ERROR_TIMEOUT If there was an SMP time-out, so that no more SMP
* operations can be performed on this link.
* @retval BLE_ERROR_INVALID_CONN_HANDLE If the connection handle is invalid.
* @retval NRF_ERROR_NOT_FOUND If the security parameters have not been set.
* @retval NRF_ERROR_STORAGE_FULL If there is no more space in persistent storage.
* @retval NRF_ERROR_NO_MEM If no more authentication procedures can run in parallel
* for the given role. See @ref sd_ble_gap_authenticate.
* @retval NRF_ERROR_INVALID_STATE If the Peer Manager is not initialized, or the peer is
* disconnected or in the process of disconnecting.
* @retval NRF_ERROR_INTERNAL If an internal error occurred.
*/
ret_code_t pm_conn_secure(uint16_t conn_handle, bool force_repairing);
/**@brief Function for providing security configuration for a link.
*
* @details This function is optional, and must be called in reply to a @ref
* PM_EVT_CONN_SEC_CONFIG_REQ event, before the Peer Manager event handler returns. If it
* is not called in time, a default configuration is used. See @ref pm_conn_sec_config_t
* for the value of the default.
*
* @param[in] conn_handle The connection to set the configuration for.
* @param[in] p_conn_sec_config The configuration.
*/
void pm_conn_sec_config_reply(uint16_t conn_handle, pm_conn_sec_config_t * p_conn_sec_config);
/**@brief Function for manually informing that the local database has changed.
*
* @details This function sends a service changed indication to all bonded and/or connected peers
* that subscribe to this indication. If a bonded peer is not connected, the indication is
* sent when it reconnects. Every time an indication is sent, a @ref
* PM_EVT_SERVICE_CHANGED_IND_SENT event occurs, followed by a @ref
* PM_EVT_SERVICE_CHANGED_IND_CONFIRMED when the peer sends its confirmation. Peers that
* are not subscribed to the service changed indication when this function is called do not
* receive an indication, and no events are sent to the user. Likewise, if the service
* changed characteristic is not present in the local database, this no indications are
* sent peers, and no events are sent to the user.
*/
void pm_local_database_has_changed(void);
/**@brief Function for getting the security status of a connection.
*
* @param[in] conn_handle Connection handle of the link as provided by the SoftDevice.
* @param[out] p_conn_sec_status Security status of the link.
*
* @retval NRF_SUCCESS If pairing was initiated successfully.
* @retval BLE_ERROR_INVALID_CONN_HANDLE If the connection handle is invalid.
* @retval NRF_ERROR_NULL If @p p_conn_sec_status was NULL.
* @retval NRF_ERROR_INVALID_STATE If the Peer Manager is not initialized.
*/
ret_code_t pm_conn_sec_status_get(uint16_t conn_handle, pm_conn_sec_status_t * p_conn_sec_status);
/**@brief Experimental function for specifying the public key to use for LESC operations.
*
* @details This function can be called multiple times. The specified public key will be used for
* all subsequent LESC (LE Secure Connections) operations until the next time this function
* is called.
*
* @note The key must continue to reside in application memory as it is not copied by Peer Manager.
*
* @param[in] p_public_key The public key to use for all subsequent LESC operations.
*
* @retval NRF_SUCCESS If pairing was initiated successfully.
* @retval NRF_ERROR_INVALID_STATE If the Peer Manager is not initialized.
*/
ret_code_t pm_lesc_public_key_set(ble_gap_lesc_p256_pk_t * p_public_key);
/**@brief Function for setting or clearing the whitelist.
*
* When using the S13x SoftDevice v3.x, this function sets or clears the whitelist.
* When using the S13x SoftDevice v2.x, this function caches a list of
* peers that can be retrieved later by @ref pm_whitelist_get to pass to the @ref lib_ble_advertising.
*
* To clear the current whitelist, pass either NULL as @p p_peers or zero as @p peer_cnt.
*
* @param[in] p_peers The peers to add to the whitelist. Pass NULL to clear the current whitelist.
* @param[in] peer_cnt The number of peers to add to the whitelist. The number must not be greater than
* @ref BLE_GAP_WHITELIST_ADDR_MAX_COUNT. Pass zero to clear the current
* whitelist.
*
* @retval NRF_SUCCESS If the whitelist was successfully set or cleared.
* @retval BLE_GAP_ERROR_WHITELIST_IN_USE If a whitelist is already in use and cannot be set.
* @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If a peer in @p p_peers has an address that cannot
* be used for whitelisting.
* @retval NRF_ERROR_NOT_FOUND If any of the peers in @p p_peers cannot be found.
* @retval NRF_ERROR_DATA_SIZE If @p peer_cnt is greater than
* @ref BLE_GAP_WHITELIST_ADDR_MAX_COUNT.
* @retval NRF_ERROR_INVALID_STATE If the Peer Manager is not initialized.
*/
ret_code_t pm_whitelist_set(pm_peer_id_t const * p_peers,
uint32_t peer_cnt);
/**@brief Function for retrieving the previously set whitelist.
*
* The function retrieves the whitelist of GAP addresses and IRKs that was
* previously set by @ref pm_whitelist_set.
*
* To retrieve only GAP addresses or only IRKs, provide only one of the
* buffers. If a buffer is provided, its size must be specified.
*
* @param[out] p_addrs The buffer where to store GAP addresses. Pass NULL to retrieve
* only IRKs (in that case, @p p_irks must not be NULL).
* @param[in,out] p_addr_cnt In: The size of the @p p_addrs buffer.
* May be NULL if and only if @p p_addrs is NULL.
* Out: The number of GAP addresses copied into the buffer.
* If @p p_addrs is NULL, this parameter remains unchanged.
* @param[out] p_irks The buffer where to store IRKs. Pass NULL to retrieve
* only GAP addresses (in that case, @p p_addrs must not NULL).
* @param[in,out] p_irk_cnt In: The size of the @p p_irks buffer.
* May be NULL if and only if @p p_irks is NULL.
* Out: The number of IRKs copied into the buffer.
* If @p p_irks is NULL, this paramater remains unchanged.
*
* @retval NRF_SUCCESS If the whitelist was successfully retrieved.
* @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If a peer has an address that cannot be used for
* whitelisting (this error can occur only
* when using the S13x SoftDevice v2.x).
* @retval NRF_ERROR_NULL If a required parameter is NULL.
* @retval NRF_ERROR_NO_MEM If the provided buffers are too small.
* @retval NRF_ERROR_NOT_FOUND If the data for any of the cached whitelisted peers
* cannot be found. It might have been deleted.
* @retval NRF_ERROR_INVALID_STATE If the Peer Manager is not initialized.
*/
ret_code_t pm_whitelist_get(ble_gap_addr_t * p_addrs,
uint32_t * p_addr_cnt,
ble_gap_irk_t * p_irks,
uint32_t * p_irk_cnt);
/**@brief Function for setting and clearing the device identities list.
*
* @param[in] p_peers The peers to add to the device identities list. Pass NULL to clear
* the device identities list.
* @param[in] peer_cnt The number of peers. Pass zero to clear the device identities list.
*
* @retval NRF_SUCCESS If the device identities list was successfully
* set or cleared.
* @retval NRF_ERROR_NOT_FOUND If a peer is invalid or its data could not
* be found in flash.
* @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If a peer has an address that cannot be
* used for whitelisting.
* @retval BLE_ERROR_GAP_DEVICE_IDENTITIES_IN_USE If the device identities list is in use and
* cannot be set.
* @retval NRF_ERROR_INVALID_STATE If the Peer Manager is not initialized.
* @retval NRF_ERROR_NOT_SUPPORTED If using a SoftDevice that does not support
* device identities, e.g. S130 v2.0.
*/
ret_code_t pm_device_identities_list_set(pm_peer_id_t const * p_peers,
uint32_t peer_cnt);
/**@brief Function for setting the local <em>Bluetooth</em> identity address.
*
* @details The local <em>Bluetooth</em> identity address is the address that identifies the device to other
* peers. The address type must be either @ref BLE_GAP_ADDR_TYPE_PUBLIC or @ref
* BLE_GAP_ADDR_TYPE_RANDOM_STATIC. The identity address cannot be changed while roles are
* running.
*
* The SoftDevice sets a default address of type @ref BLE_GAP_ADDR_TYPE_RANDOM_STATIC
* when it is enabled. This default address is a random number that is populated during
* the IC manufacturing process. It remains unchanged for the lifetime of each IC, but the application can assign a different identity address.
*
* The identity address is distributed to the peer during bonding.
* If the address changes, the address stored in the peer device will not be valid and the
* ability to reconnect using the old address will be lost.
*
*
* @note The SoftDevice functions @ref sd_ble_gap_addr_set
* and @ref sd_ble_gap_privacy_set must not be called when using the Peer Manager.
* Use this function instead.
*
* @param[in] p_addr The GAP address to be set.
*
* @retval NRF_SUCCESS If the identity address was set successfully.
* @retval NRF_ERROR_NULL If @p p_addr is NULL.
* @retval NRF_ERROR_INVALID_ADDR If the @p p_addr pointer is invalid.
* @retval BLE_ERROR_GAP_INVALID_BLE_ADDR If the BLE address is invalid.
* @retval NRF_ERROR_BUSY If the SoftDevice was busy. Process SoftDevice events
* and retry.
* @retval NRF_ERROR_INVALID_STATE If the Peer Manager is not initialized or if this function
* was called while advertising, scanning, or while connected.
* @retval NRF_ERROR_INTERNAL If an internal error occurred.
*/
ret_code_t pm_id_addr_set(ble_gap_addr_t const * p_addr);
/**@brief Function for retrieving the local <em>Bluetooth</em> identity address.
*
* This function always returns the identity address, irrespective of the privacy settings.
* This means that the address type will always be either @ref BLE_GAP_ADDR_TYPE_PUBLIC or @ref
* BLE_GAP_ADDR_TYPE_RANDOM_STATIC.
*
* @param[out] p_addr Pointer to the address structure to be filled in.
*
* @retval NRF_SUCCESS If the address was retrieved successfully.
* @retval NRF_ERROR_NULL If @p p_addr is NULL.
* @retval NRF_ERROR_INVALID_STATE If the Peer Manager is not initialized.
*/
ret_code_t pm_id_addr_get(ble_gap_addr_t * p_addr);
/**@brief Function for configuring privacy settings.
*
* The privacy settings cannot be configured while advertising, scanning, or while in a connection.
*
* @note The SoftDevice functions @ref sd_ble_gap_addr_set
* and @ref sd_ble_gap_privacy_set must not be called when using the Peer Manager.
* Use this function instead.
*
* @param[in] p_privacy_params Privacy settings.
*
* @retval NRF_SUCCESS If the privacy settings were configured successfully.
* @retval NRF_ERROR_NULL If @p p_privacy_params is NULL.
* @retval NRF_ERROR_BUSY If the operation could not be performed at this time.
* Process SoftDevice events and retry.
* @retval NRF_ERROR_INVALID_PARAM If the address type is invalid.
* @retval NRF_ERROR_INVALID_STATE If this function is called while BLE roles using
* privacy are enabled.
* @retval NRF_ERROR_INVALID_STATE If the Peer Manager is not initialized.
*/
ret_code_t pm_privacy_set(pm_privacy_params_t const * p_privacy_params);
/**@brief Function for retrieving privacy settings.
*
* The privacy settings that are returned include the current IRK as well.
*
* @param[out] p_privacy_params Privacy settings.
*
* @retval NRF_SUCCESS If the privacy settings were retrieved successfully.
* @retval NRF_ERROR_NULL If @p p_privacy_params or @p p_privacy_params->p_device_irk is
* NULL.
* @retval NRF_ERROR_INVALID_STATE If the Peer Manager is not initialized.
*/
ret_code_t pm_privacy_get(pm_privacy_params_t * p_privacy_params);
/**@brief Function for getting the connection handle of the connection with a bonded peer.
*
* @param[in] peer_id The peer ID of the bonded peer.
* @param[out] p_conn_handle Connection handle, or @ref BLE_ERROR_INVALID_CONN_HANDLE if the peer
* is not connected.
*
* @retval NRF_SUCCESS If the connection handle was retrieved successfully.
* @retval NRF_ERROR_NULL If @p p_conn_handle was NULL.
* @retval NRF_ERROR_INVALID_STATE If the Peer Manager is not initialized.
*/
ret_code_t pm_conn_handle_get(pm_peer_id_t peer_id, uint16_t * p_conn_handle);
/**@brief Function for retrieving the ID of a peer, given its connection handle.
*
* @param[in] conn_handle The connection handle of the peer.
* @param[out] p_peer_id The peer ID, or @ref PM_PEER_ID_INVALID if the peer is not bonded or
* @p conn_handle does not refer to a valid connection.
*
* @retval NRF_SUCCESS If the peer ID was retrieved successfully.
* @retval NRF_ERROR_NULL If @p p_peer_id was NULL.
* @retval NRF_ERROR_INVALID_STATE If the Peer Manager is not initialized.
*/
ret_code_t pm_peer_id_get(uint16_t conn_handle, pm_peer_id_t * p_peer_id);
/**@brief Function for getting the next peer ID in the sequence of all used peer IDs.
*
* @details This function can be used to loop through all used peer IDs. The order in which
* peer IDs are returned should be considered unpredictable. @ref PM_PEER_ID_INVALID
* is considered to be before the first and after the last used peer ID.
*
* @details To loop through all peer IDs exactly once, use the following constuct:
* @code{c}
* pm_peer_id_t current_peer_id = pm_next_peer_id_get(PM_PEER_ID_INVALID);
* while (current_peer_id != PM_PEER_ID_INVALID)
* {
* // Do something with current_peer_id.
* current_peer_id = pm_next_peer_id_get(current_peer_id)
* }
* @endcode
*
* @param[in] prev_peer_id The previous peer ID.
*
* @return The next peer ID. If @p prev_peer_id was @ref PM_PEER_ID_INVALID, the
* next peer ID is the first used peer ID. If @p prev_peer_id was the last
* used peer ID, the function returns @ref PM_PEER_ID_INVALID.
*/
pm_peer_id_t pm_next_peer_id_get(pm_peer_id_t prev_peer_id);
/**@brief Function for querying the number of valid peer IDs that are available.
*
* @details This function returns the number of peers for which there is data in persistent storage.
*
* @return The number of valid peer IDs.
*/
uint32_t pm_peer_count(void);
/**@anchor PM_PEER_DATA_FUNCTIONS
* @name Functions (Peer Data)
* Functions for manipulating peer data.
* @{
*/
/**
* @{
*/
/**@brief Function for retrieving stored data of a peer.
*
* @note The length of the provided buffer must be a multiple of 4.
*
* @param[in] peer_id Peer ID to get data for.
* @param[in] data_id Which type of data to read.
* @param[out] p_data Where to put the retrieved data.
* @param[inout] p_len In: The length in bytes of @p p_data.
* Out: The length in bytes of the read data, if the read was successful.
*
* @retval NRF_SUCCESS If the data was read successfully.
* @retval NRF_ERROR_INVALID_PARAM If the the data type or the peer ID was invalid or unallocated,
* or if the length in @p p_length was not a multiple of 4.
* @retval NRF_ERROR_NULL If a pointer parameter was NULL.
* @retval NRF_ERROR_NOT_FOUND If no stored data was found for this peer ID/data ID combination.
* @retval NRF_ERROR_DATA_SIZE If the provided buffer was not large enough.
* @retval NRF_ERROR_INVALID_STATE If the Peer Manager is not initialized.
*/
ret_code_t pm_peer_data_load(pm_peer_id_t peer_id,
pm_peer_data_id_t data_id,
void * p_data,
uint16_t * p_len);
/**@brief Function for reading a peer's bonding data (@ref PM_PEER_DATA_ID_BONDING).
* @details See @ref pm_peer_data_load for parameters and return values. */
ret_code_t pm_peer_data_bonding_load(pm_peer_id_t peer_id,
pm_peer_data_bonding_t * p_data);
/**@brief Function for reading a peer's remote DB values. (@ref PM_PEER_DATA_ID_GATT_REMOTE).
* @details See @ref pm_peer_data_load for parameters and return values. */
ret_code_t pm_peer_data_remote_db_load(pm_peer_id_t peer_id,
ble_gatt_db_srv_t * p_data,
uint16_t * p_len);
/**@brief Function for reading a peer's application data. (@ref PM_PEER_DATA_ID_APPLICATION).
* @details See @ref pm_peer_data_load for parameters and return values. */
ret_code_t pm_peer_data_app_data_load(pm_peer_id_t peer_id,
uint8_t * p_data,
uint16_t * p_len);
/** @}*/
/**
* @{
*/
/**@brief Function for setting or updating stored data of a peer.
*
* @note Writing the data to persistent storage happens asynchronously. Therefore, the buffer
* that contains the data must be kept alive until the operation has completed.
*
* @note The data written using this function might later be overwritten as a result of internal
* operations in the Peer Manager. A Peer Manager event is sent each time data is updated,
* regardless of whether the operation originated internally or from action by the user.
*
* @param[in] peer_id Peer ID to set data for.
* @param[in] data_id Which type of data to set.
* @param[in] p_data New value to set.
* @param[in] len The length in bytes of @p p_data.
* @param[out] p_token A token that identifies this particular store operation. The token can be
* used to identify events that pertain to this operation. This parameter can
* be NULL.
*
* @retval NRF_SUCCESS If the data is scheduled to be written to persistent storage.
* @retval NRF_ERROR_NULL If @p p_data is NULL.
* @retval NRF_ERROR_NOT_FOUND If no peer was found for the peer ID.
* @retval NRF_ERROR_BUSY If the underlying flash handler is busy with other flash
* operations. Try again after receiving a Peer Manager event.
* @retval NRF_ERROR_INVALID_STATE If the Peer Manager is not initialized.
*/
ret_code_t pm_peer_data_store(pm_peer_id_t peer_id,
pm_peer_data_id_t data_id,
void const * p_data,
uint16_t len,
pm_store_token_t * p_token);
/**@brief Function for setting or updating a peer's bonding data (@ref PM_PEER_DATA_ID_BONDING).
* @details See @ref pm_peer_data_store for parameters and return values. */
ret_code_t pm_peer_data_bonding_store(pm_peer_id_t peer_id,
pm_peer_data_bonding_t const * p_data,
pm_store_token_t * p_token);
/**@brief Function for setting or updating a peer's remote DB values. (@ref PM_PEER_DATA_ID_GATT_REMOTE).
* @details See @ref pm_peer_data_store for parameters and return values. */
ret_code_t pm_peer_data_remote_db_store(pm_peer_id_t peer_id,
ble_gatt_db_srv_t const * p_data,
uint16_t len,
pm_store_token_t * p_token);
/**@brief Function for setting or updating a peer's application data. (@ref PM_PEER_DATA_ID_APPLICATION).
* @details See @ref pm_peer_data_store for parameters and return values. */
ret_code_t pm_peer_data_app_data_store(pm_peer_id_t peer_id,
uint8_t const * p_data,
uint16_t len,
pm_store_token_t * p_token);
/** @}*/
/**
* @{
*/
/**@brief Function for deleting a peer's stored pieces of data.
*
* @details This function deletes specific data that is stored for a peer. Note that bonding data
* cannot be cleared separately.
*
* To delete all data for a peer (including bonding data), use @ref pm_peer_delete.
*
* @note Clearing data in persistent storage happens asynchronously.
*
* @param[in] peer_id Peer ID to clear data for.
* @param[in] data_id Which data to clear.
*
* @retval NRF_SUCCESS If the clear procedure was initiated successfully.
* @retval NRF_ERROR_INVALID_PARAM If @p data_id was PM_PEER_DATA_ID_BONDING or invalid, or
* @p peer_id was invalid.
* @retval NRF_ERROR_NOT_FOUND If there was no data to clear for this peer ID/data ID combination.
* @retval NRF_ERROR_BUSY If the underlying flash handler is busy with other flash
* operations. Try again after receiving a Peer Manager event.
* @retval NRF_ERROR_INVALID_STATE If the Peer Manager is not initialized.
* @retval NRF_ERROR_INTERNAL If an internal error occurred.
*/
ret_code_t pm_peer_data_delete(pm_peer_id_t peer_id, pm_peer_data_id_t data_id);
/**@brief Function for manually adding a peer to the persistent storage.
*
* @details This function allocates a new peer ID and stores bonding data for the new peer. The
* bonding data is necessary to prevent ambiguity/inconsistency in peer data.
*
* @param[in] p_bonding_data The bonding data of the new peer (must contain a public/static
* address or a non-zero IRK).
* @param[out] p_new_peer_id Peer ID for the new peer, or an existing peer if a match was found.
* @param[out] p_token A token that identifies this particular store operation (storing the
* bonding data). The token can be used to identify events that pertain
* to this operation. This parameter can be NULL.
*
* @retval NRF_SUCCESS If the store operation for bonding data was initiated successfully.
* @retval NRF_ERROR_NULL If @p p_bonding_data or @p p_new_peer_id is NULL.
* @retval NRF_ERROR_STORAGE_FULL If there is no more space in persistent storage.
* @retval NRF_ERROR_NO_MEM If there are no more available peer IDs.
* @retval NRF_ERROR_BUSY If the underlying flash filesystem is busy with other flash
* operations. Try again after receiving a Peer Manager event.
* @retval NRF_ERROR_INVALID_STATE If the Peer Manager is not initialized.
* @retval NRF_ERROR_INTERNAL If an internal error occurred.
*/
ret_code_t pm_peer_new(pm_peer_id_t * p_new_peer_id,
pm_peer_data_bonding_t * p_bonding_data,
pm_store_token_t * p_token);
/**@brief Function for freeing persistent storage for a peer.
*
* @details This function deletes every piece of data that is associated with the specified peer and
* frees the peer ID to be used for another peer. The deletion happens asynchronously, and
* the peer ID is not freed until the data is deleted. When the operation finishes, a @ref
* PM_EVT_PEER_DELETE_SUCCEEDED or @ref PM_EVT_PEER_DELETE_FAILED event is sent.
*
* @warning Use this function only when not connected to or connectable for the peer that is being
* deleted. If the peer is or becomes connected or data is manually written in flash during
* this procedure (until the success or failure event happens), the behavior is undefined.
*
* @param[in] peer_id Peer ID to be freed and have all associated data deleted.
*
* @retval NRF_SUCCESS If the operation was initiated successfully.
* @retval NRF_ERROR_INVALID_PARAM If the peer ID was not valid.
* @retval NRF_ERROR_INVALID_STATE If the Peer Manager is not initialized.
*/
ret_code_t pm_peer_delete(pm_peer_id_t peer_id);
/**@brief Function for deleting all data stored for all peers.
*
* @details This function sends either a @ref PM_EVT_PEERS_DELETE_SUCCEEDED or a @ref
* PM_EVT_PEERS_DELETE_FAILED event. In addition, a @ref PM_EVT_PEER_DELETE_SUCCEEDED or
* @ref PM_EVT_PEER_DELETE_FAILED event is sent for each deleted peer.
*
* @note No event is sent when there is no peer data in flash.
*
* @warning Use this function only when not connected or connectable. If a peer is or becomes
* connected or a @ref PM_PEER_DATA_FUNCTIONS function is used during this procedure (until
* the success or failure event happens), the behavior is undefined.
*
* @retval NRF_SUCCESS If the deletion process was initiated successfully.
* @retval NRF_ERROR_INVALID_STATE If the Peer Manager is not initialized.
* @retval NRF_ERROR_INTERNAL If an internal error occurred.
*/
ret_code_t pm_peers_delete(void);
/** @}*/
/**
* @{
*/
/**@brief Function for finding the highest and lowest ranked peers.
*
* @details The rank is saved in persistent storage under the data ID @ref PM_PEER_DATA_ID_PEER_RANK.
*
* @details The interpretation of rank is up to the user, because the rank is only updated by
* calling @ref pm_peer_rank_highest or by manipulating the value using a @ref
* PM_PEER_DATA_FUNCTIONS function.
*
* @note Any argument that is NULL is ignored.
*
* @param[out] p_highest_ranked_peer The peer ID with the highest rank of all peers, for example,
* the most recently used peer.
* @param[out] p_highest_rank The highest rank.
* @param[out] p_lowest_ranked_peer The peer ID with the lowest rank of all peers, for example,
* the least recently used peer.
* @param[out] p_lowest_rank The lowest rank.
*
* @retval NRF_SUCCESS If the operation completed successfully.
* @retval NRF_ERROR_NOT_FOUND If no peers were found.
* @retval NRF_ERROR_INVALID_STATE If the Peer Manager is not initialized.
* @retval NRF_ERROR_INTERNAL If an internal error occurred.
*/
ret_code_t pm_peer_ranks_get(pm_peer_id_t * p_highest_ranked_peer,
uint32_t * p_highest_rank,
pm_peer_id_t * p_lowest_ranked_peer,
uint32_t * p_lowest_rank);
/**@brief Function for updating the rank of a peer to be highest among all stored peers.
*
* @details If this function returns @ref NRF_SUCCESS, either a @ref PM_EVT_PEER_DATA_UPDATE_SUCCEEDED or a
* @ref PM_EVT_PEER_DATA_UPDATE_FAILED event is sent with a @ref
* PM_STORE_TOKEN_INVALID store token when the operation is complete. Until the operation
* is complete, this function returns @ref NRF_ERROR_BUSY.
*
* When the operation is complete, the peer is the highest ranked peer as reported by
* @ref pm_peer_ranks_get.
*
* @note The @ref PM_EVT_PEER_DATA_UPDATE_SUCCEEDED event can arrive before the function returns if the peer
* is already ranked highest. In this case, the @ref pm_peer_data_update_succeeded_evt_t::flash_changed flag
* in the event will be false.
*
* @param[in] peer_id The peer to rank highest.
*
* @retval NRF_SUCCESS If the peer's rank is, or will be updated to be highest.
* @retval NRF_ERROR_BUSY If the underlying flash handler is busy with other flash
* operations, or if a previous call to this function has not
* completed. Try again after receiving a Peer Manager event.
* @retval NRF_ERROR_INVALID_STATE If the Peer Manager is not initialized.
* @retval NRF_ERROR_INTERNAL If an internal error occurred.
*/
ret_code_t pm_peer_rank_highest(pm_peer_id_t peer_id);
/** @}*/
/** @} */
/** @} */
#ifdef __cplusplus
}
#endif
#endif // PEER_MANAGER_H__
| {
"content_hash": "60c038cb917fc3bfbc1710a55518fa2e",
"timestamp": "",
"source": "github",
"line_count": 822,
"max_line_length": 472,
"avg_line_length": 55.07420924574209,
"alnum_prop": 0.6510127896445849,
"repo_name": "bulislaw/mbed-os",
"id": "b5cc5af781908da4fa37f0ae5f02cc61b3f1cf40",
"size": "47323",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_manager.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "6239805"
},
{
"name": "Batchfile",
"bytes": "22"
},
{
"name": "C",
"bytes": "264200837"
},
{
"name": "C++",
"bytes": "9736087"
},
{
"name": "CMake",
"bytes": "5235"
},
{
"name": "HTML",
"bytes": "1681688"
},
{
"name": "Makefile",
"bytes": "99320"
},
{
"name": "Objective-C",
"bytes": "444257"
},
{
"name": "Perl",
"bytes": "2589"
},
{
"name": "Python",
"bytes": "36524"
},
{
"name": "Shell",
"bytes": "16819"
},
{
"name": "XSLT",
"bytes": "5596"
}
],
"symlink_target": ""
} |
package org.openuap.cms.engine.profile;
import java.lang.reflect.Constructor;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openuap.cms.config.CMSConfig;
import org.openuap.runtime.profile.ProfileInfoHolder;
import org.springframework.util.ReflectionUtils;
/**
* <p>
* 发布侦测维持器.
* </p>
*
* <p>
* $Id: PublishProfileInfoHolder.java 3924 2010-10-26 11:53:36Z orangeforjava $
* </p>
*
* @author Joseph
* @version 1.0
*/
public class PublishProfileInfoHolder {
private static Log logger = LogFactory
.getLog(PublishProfileInfoHolder.class);
public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL";
public static final String SYSTEM_PROPERTY = "publish.profile.strategy";
public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL";
public static final String MODE_GLOBAL = "MODE_GLOBAL";
private static String strategyName = System.getProperty(SYSTEM_PROPERTY);
private static int initializeCount = 0;
private static PublishProfileHolderStrategy strategy;
static {
initialize();
}
public static int getInitializeCount() {
return initializeCount;
}
private static void initialize() {
if ((strategyName == null) || "".equals(strategyName)) {
// Set default
strategyName = MODE_THREADLOCAL;
}
if (strategyName.equals(MODE_THREADLOCAL)) {
strategy = new PublishThreadLocalProfileHolderStrategy();
} else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) {
strategy = new PublishInheritableThreadLocalProfileHolderStrategy();
} else if (strategyName.equals(MODE_GLOBAL)) {
strategy = new PublishGlobalProfileHolderStrategy();
} else {
// Try to load a custom strategy
try {
Class clazz = Class.forName(strategyName);
Constructor customStrategy = clazz
.getConstructor(new Class[] {});
strategy = (PublishProfileHolderStrategy) customStrategy
.newInstance(new Object[] {});
} catch (Exception ex) {
ReflectionUtils.handleReflectionException(ex);
}
}
initializeCount++;
}
public static void setStrategyName(String strategyName) {
PublishProfileInfoHolder.strategyName = strategyName;
initialize();
}
public static void clearProfile() {
strategy.clearProfile();
}
public static PublishActionProfile getProfile() {
return strategy.getProfile();
}
public static void setProfile(PublishActionProfile profile) {
strategy.setProfile(profile);
}
public static boolean isEnableProfile() {
return CMSConfig.getInstance().getBooleanProperty("cms.publish.profile", true);
}
/**
* 把分析信息记录到日志内
*/
public static void logProfile() {
PublishActionProfile ap = getProfile();
if (ap != null) {
//
System.out
.println("//--------------------------profile start-------------------");
System.out.println("request URL=" + ap.getActionURI());
System.out.println("request Action=" + ap.getActionName());
System.out.println("locatorActionTimes="
+ ap.getLocatorActionTimes() + " ms");
System.out.println("ProcessActionTimes="
+ ap.getProcessActionTimes() + " ms");
System.out.println("RenderTimes=" + ap.getRenderTimes() + " ms");
System.out.println("---------------Operation start-------------");
List dbs = ap.getAllPublishOperations();
int size = dbs.size();
System.out.println("total publish operation=" + size + " times");
int totalDbTimes = 0;
for (int i = 0; i < size; i++) {
PublishOperationProfile db = (PublishOperationProfile) dbs.get(i);
System.out.println(" publish operation[" + i + "]=(" + db.getOperation()
+ ") spare " + db.getProccessTimes() + " ms");
Exception ex = db.getException();
if (ex != null) {
System.out.println(" exception publish operation[" + i + "]="
+ ex.getMessage());
}
totalDbTimes += db.getProccessTimes();
}
System.out.println("total publish operationy spare=" + totalDbTimes + " ms");
System.out.println("---------------Operation end -------------");
if (ProfileInfoHolder.isEnableProfile()) {
ProfileInfoHolder.logDBProfile();
}
System.out
.println("//--------------------------profile end -------------------");
}
}
}
| {
"content_hash": "5e933fe66a8010ece6f64af672ce7691",
"timestamp": "",
"source": "github",
"line_count": 142,
"max_line_length": 88,
"avg_line_length": 29.845070422535212,
"alnum_prop": 0.6776781500707881,
"repo_name": "juweiping/ocms",
"id": "b7892c553562d5295c2fe4ce24fc675948d96997",
"size": "4894",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/org/openuap/cms/engine/profile/PublishProfileInfoHolder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "434506"
},
{
"name": "ColdFusion",
"bytes": "5390"
},
{
"name": "Java",
"bytes": "2714260"
},
{
"name": "JavaScript",
"bytes": "2290371"
},
{
"name": "PHP",
"bytes": "7226"
},
{
"name": "Perl",
"bytes": "4746"
}
],
"symlink_target": ""
} |
<?php
require_once 'config.php';
$user = new UserModel;
$user->user_name = 'martin_adamko';
$user->first_name = 'Martin';
$user->last_name = 'Adamko';
$user->save();
$user = new UserModel;
$user->user_name = 'milan_lasica';
$user->first_name = 'Milan';
$user->last_name = 'Lasica';
$user->save();
$user = new UserModel;
$user->user_name = 'jan_kroner';
$user->first_name = 'Ján';
$user->last_name = 'Króner';
$id = $user->save();
$user = new UserModel($id);
print_pre($user);
$user->first_name = 'Janko';
$user->save();
print_pre($user, $user->full_name);
require_once dirname(dirname(__FILE__)).'/config-common-footer.php';
| {
"content_hash": "b50b5ce3dafe398932f84f71df1af169",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 68,
"avg_line_length": 20.516129032258064,
"alnum_prop": 0.6320754716981132,
"repo_name": "attitude/PHP-Library-Demo",
"id": "58bc4ff0a2f99e549e765deb43374bec4af0213c",
"size": "638",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "demo-filesystem/01-fill-data.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "9495"
}
],
"symlink_target": ""
} |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Task = require('../ember-cli/lib/models/task');
const chalk = require("chalk");
const child_process_1 = require("child_process");
exports.default = Task.extend({
run: function () {
const ui = this.ui;
let packageManager = this.packageManager;
if (packageManager === 'default') {
packageManager = 'npm';
}
ui.writeLine(chalk.green(`Installing packages for tooling via ${packageManager}.`));
let installCommand = `${packageManager} install`;
if (packageManager === 'npm') {
installCommand = `${packageManager} --quiet install`;
}
return new Promise((resolve, reject) => {
child_process_1.exec(installCommand, (err, _stdout, stderr) => {
if (err) {
ui.writeLine(stderr);
const message = 'Package install failed, see above.';
ui.writeLine(chalk.red(message));
reject(message);
}
else {
ui.writeLine(chalk.green(`Installed packages for tooling via ${packageManager}.`));
resolve();
}
});
});
}
});
//# sourceMappingURL=/users/arick/angular-cli/tasks/npm-install.js.map | {
"content_hash": "8c8d474083b52d2839ed8e222966b656",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 103,
"avg_line_length": 40.1764705882353,
"alnum_prop": 0.5439238653001464,
"repo_name": "rtnews/rtsfnt",
"id": "98dd6a76c60819960086916e12983fcc5a7f7bcf",
"size": "1366",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "node_modules/@angular/cli/tasks/npm-install.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "27385"
},
{
"name": "HTML",
"bytes": "13394"
},
{
"name": "JavaScript",
"bytes": "1979"
},
{
"name": "TypeScript",
"bytes": "94530"
}
],
"symlink_target": ""
} |
API Controller Bundle Documentation
======
What is OAuth
----------------
Why are we using OAuth
----------------
OAuth 2.0 Basics
----------------
OAuth is a relatively simple protocol that allows a user to grant an application
access to their data on a separate server or platform. For example allowing a
event planning application to access your Google Calendar to find your free time
automatically.
To implement OAuth 2.0 one must understand the 'players' involved in setting up
OAuth2 authorization/communication. At a minimum there are three players.
* Server
* Provides Auth,Token endpoints as well as an REST or other web service API.
* Client App
* Provides a name and redirect url
* User - Often one @Server and one @ClientApp. For example you would have an account
with Google for their calendar and one with the event planning application example
above.
For Our Demo
------------
Server: http://nuvi.noblet.ca
* Auth Endpoint: https://nuvi.noblet.ca/oauth/v2/auth
* Token Endpoint: https://nuvi.noblet.ca/oauth/v2/token
Client: http://nuviclient.noblet.ca/
* Redirect Url: http://nuviclient.noblet.ca/authorize
For our purposes we'll use
* User @Server: api@noblet.ca
* User @Client: remote@noblet.ca
Step One
--------
A **Developer @ClientApp** would fill out a registration form on the Server
application. At a minimum the developer will provide a name for this client and
a url where users who approve the access will be redirected back to **@ClientApp**.
Developer @ClientApp Registers With
-----------------------------------
* ClientApp Name: NUVIClient
* Redirect URL: http://nuviclient.noblet.ca/authorize
Server Provides
---------------
* Client ID: 10_asiRasuf...
* Client Secret: adfiaue...
These two must be stored and kept safe since gaining these two pieces of
information allows an attacker to impersonate the **ClientApp** and have access to
the User's data **@Server**.
Step Two
--------
ClientApp creates a link that User can click on sending them to **@Server's** auth
endpoint. This url will include the client id and secret and as such should be accessed
over a secured channel such as HTTPS/SSL. The url is the **Server's** Auth Endpoint
providing OAuth2 required parameters.
* Client Id
* Client Secret
* The redirect URL - If this doesn't match what was provided to the Server during
ClientApp registration authentication will fail.
* A grant type - In our case we are requesting the Authorization Code flow
Step Three
----------
Given the above, if I were a ClientApp developer I would present the User with a
link whose target was (line breaks have been added for readability):
```
https://nuvi.noblet.ca/oauth/v2/auth?
client_id=10_asiRsasu&
client_secret=adfiaue&
redirect_uri=http://nuviclient.noblet.ca/authorize&
grant_type=code
```
Obviously clicking on this link will send the User from **ClientApp** to the page
on the **Server**. It is the responsibility of the server to authenticate the user
against its own user repository. Once logged into the server the User will be
presented with a 'grant authorization' page. This typically displays the name the
**ClientApp** registered with and a list of requested permissions. In our case there
are no specific permissions. However in the calendar example we mentioned previously
one could imagine it would ask for read only access to all events or perhaps only
access to the 'free/busy' information. To complete the connection the user must
accept the request.
Step Four
----------
Upon accepting the permissions the **Server** will redirect the User back to
**ClientApp** using the redirect url previously registered and requested in the
incoming request from **ClientApp**. The server adds a query parameter to the
redirect.
So for our example the server would cause a redirect to the url
http://nuviclient.noblet.ca/authorize?code=12SFg15d662FFSGha.
Step Five
---------
The **ClientApp** page handling this request has a few things to do in a small
window of time. It must use the code which has a validity of only a few minutes
to request an access token from the server's token endpoint. This is typically a
POST request.
For example the **ClientApp** would make a background request to http://nuvi.noblet.ca/oauth/v2/token
including Client ID, Client Secret, the Code and Grant type. In our case this
would look like:
```
POST nuvi.noblet.ca/oauth/v2/token
Accept: application/json
client_id=10_asiRsasu&
client_secret=adfiaue&
code=12SFg15d662FFSGha&
grant_type=authorization_code
```
The response of which would be a JSON encoded array that provides the access token,
expiry in seconds and if granted by the server a refresh_token. It would look something
like:
```JSON
{ "access_token": "NjlmNDNiZT....", "expires_in": 3600, "refresh_token": "ZGU2NzlhOT...." }
```
As you can see the access token is only good for one hour. The expiry depends on
the particular server's configuration. The refresh token has a longer expiry
however it only valid in exchange for a new access token. It will not grant you
access to the API functions.
**ClientApp** would typically store the access and refresh token and expiry to be
able for the duration that it requires to communicate with the **Server**. In our
setup the refresh tokens are good for 2 weeks.
Step Six
--------
**ClientApp** should implement a way to detect expired tokens using the refresh
token. If the access token is expired
a special request to the token endpoint. For example:
```
POST nuvi.noblet.ca/oauth/v2/token
Accept: application/json
client_id=10_asiRsasu&
client_secret=adfiaue&
refresh_token=ZGU2NzlhOT....&
grant_type=refresh_token
```
Results in a new access and refresh token.
```
{ "access_token": "GjRlSauxx231...", "expires_in": 3600, "refresh_token": "DAaf1as15qbe9T...." }
```
If the refresh token has expired steps 2 to 5 must be repeated.
Step Seven
----------
**ClientApp** can now make requests of the **Server** API. When using a REST based
api, the HTTP Headers and Verbs (GET,POST,PUT,PATCH,DELETE) and HTTP Return codes
(200 OK, 201 Created, 401 Bad Request, 404 Not Found etc) are much more important
than in a simple html browser based system.
For example to make a simple GET request that returns data, one must specify the
desired return format using the 'Accept' HTTP header. Access to the API is protected
by the access token which is passed via the 'Authorization' HTTP header.
An example request to a test function would look as follows:
```
GET nuvi.noblet.ca/api/v1/test
Accept: application/json
Authorization: Bearer XXXXXX
```
The response would be:
```
200 OK
Content-Type: application/json
Content-Length: 63
{ "username": "api@noblet.ca",
"roles": ["ROLE_COUNTRY_API" ] }
```
A successful call to the API's create case would create the following request:
```
POST nuvi.noblet.ca/api/v1/ibd/cases
Content-Type: application/json
Accept: application/json
Authorization: Bearer GjRlSauxx231
{"caseId": "ACaseId", "type": 1, "site": 394 }
```
And receive a response with an empty content body such as:
```
201 Created
Location: http://nuvi.noblet.ca/api/v1/ibd/cases/CA-ALBCHILD-14-000001
```
From here on **ClientApp** developers should use the API documentation to interact
with the **Server**.
Additional Resources
--------------------
* [https://developers.google.com/accounts/docs/OAuth2WebServer]
Very good OAuth2 documentation for Google's implementation of the protocol and
similar to how our implementation
* [http://blog.tankist.de/blog/2013/07/16/oauth2-explained-part-1-principles-and-terminology/]
PHP/Symfony based examples of implementing OAuth on a server. However includes
many command line examples of working with REST APIs. It also includes documentation
on other 'Grant Types' we haven't included here.
* [http://aaronparecki.com/articles/2012/07/29/1/oauth2-simplified#other-app-types]
* [http://oauth.net/2/] - Official OAuth 2.0 specification. Good but highly technical.
* [https://github.com/adoy/PHP-OAuth2] - A very simple PHP based OAuth2 client.
* Chrome has a browser extension called 'POSTMAN' that allows one to manually
craft requests to help debug and develop an OAuth client.
* The WHO/NUVI system has api documentation and sandbox available at https://server.domain.com/en/doc/api
| {
"content_hash": "d757a2cf8845037710f46b1ac6ad09ab",
"timestamp": "",
"source": "github",
"line_count": 239,
"max_line_length": 106,
"avg_line_length": 34.87866108786611,
"alnum_prop": 0.7461612284069098,
"repo_name": "IBVPD/Nuvi",
"id": "9e9bf9edac0afee9b541a5a4c4cae105bab2394d",
"size": "8336",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/Resources/doc/api.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3810"
},
{
"name": "HTML",
"bytes": "534456"
},
{
"name": "JavaScript",
"bytes": "8914"
},
{
"name": "PHP",
"bytes": "2146082"
},
{
"name": "PostScript",
"bytes": "402419"
},
{
"name": "Shell",
"bytes": "1503"
}
],
"symlink_target": ""
} |
package org.apache.airavata.registry.core.workflow.catalog.model;
import java.io.Serializable;
public class Port_PK implements Serializable {
private String templateId;
private String portId;
public Port_PK(String templateId, String portId) {
this.templateId = templateId;
this.portId = portId;
}
public Port_PK() {
;
}
@Override
public boolean equals(Object o) {
return false;
}
@Override
public int hashCode() {
return 1;
}
public String getTemplateID() {
return templateId;
}
public void setTemplateID(String templateID) {
this.templateId = templateID;
}
public String getPortId() {
return portId;
}
public void setPortId(String portId) {
this.portId = portId;
}
}
| {
"content_hash": "5107be7b8fadb65a25ddd0d4be93833f",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 65,
"avg_line_length": 18.886363636363637,
"alnum_prop": 0.618531889290012,
"repo_name": "gouravshenoy/airavata",
"id": "6f8651c7cc6f8c32d4395495c56d2273fad4e250",
"size": "1642",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/workflow/catalog/model/Port_PK.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5598"
},
{
"name": "C",
"bytes": "53885"
},
{
"name": "C++",
"bytes": "7147253"
},
{
"name": "CSS",
"bytes": "26656"
},
{
"name": "HTML",
"bytes": "84328"
},
{
"name": "Java",
"bytes": "34853075"
},
{
"name": "PHP",
"bytes": "294193"
},
{
"name": "Python",
"bytes": "295765"
},
{
"name": "Shell",
"bytes": "58504"
},
{
"name": "Thrift",
"bytes": "423314"
},
{
"name": "XSLT",
"bytes": "34643"
}
],
"symlink_target": ""
} |
namespace ui {
using testing::AllOf;
using testing::InSequence;
using testing::Property;
class EventObserver {
public:
void EventDispatchCallback(Event* event) {
DispatchEventFromNativeUiEvent(
event, base::Bind(&EventObserver::OnEvent, base::Unretained(this)));
}
void OnEvent(Event* event) {
if (event->IsMouseEvent()) {
if (event->type() == ET_MOUSEWHEEL) {
OnMouseWheelEvent(static_cast<MouseWheelEvent*>(event));
} else {
OnMouseEvent(static_cast<MouseEvent*>(event));
}
}
}
// Mock functions for intercepting mouse events.
MOCK_METHOD1(OnMouseEvent, void(MouseEvent* event));
MOCK_METHOD1(OnMouseWheelEvent, void(MouseWheelEvent* event));
};
class MockCursorEvdev : public CursorDelegateEvdev {
public:
MockCursorEvdev() {}
~MockCursorEvdev() override {}
// CursorDelegateEvdev:
void MoveCursorTo(gfx::AcceleratedWidget widget,
const gfx::PointF& location) override {
cursor_location_ = location;
}
void MoveCursorTo(const gfx::PointF& location) override {
cursor_location_ = location;
}
void MoveCursor(const gfx::Vector2dF& delta) override {
cursor_location_ = gfx::PointF(delta.x(), delta.y());
}
bool IsCursorVisible() override { return 1; }
gfx::Rect GetCursorConfinedBounds() override {
NOTIMPLEMENTED();
return gfx::Rect();
}
gfx::PointF GetLocation() override { return cursor_location_; }
void InitializeOnEvdev() override {}
private:
// The location of the mock cursor.
gfx::PointF cursor_location_;
DISALLOW_COPY_AND_ASSIGN(MockCursorEvdev);
};
MATCHER_P4(MatchesMouseEvent, type, button, x, y, "") {
if (arg->type() != type) {
*result_listener << "Expected type: " << type << " actual: " << arg->type()
<< " (" << arg->name() << ")";
return false;
}
if (button == EF_LEFT_MOUSE_BUTTON && !arg->IsLeftMouseButton()) {
*result_listener << "Expected the left button flag is set.";
return false;
}
if (button == EF_RIGHT_MOUSE_BUTTON && !arg->IsRightMouseButton()) {
*result_listener << "Expected the right button flag is set.";
return false;
}
if (button == EF_MIDDLE_MOUSE_BUTTON && !arg->IsMiddleMouseButton()) {
*result_listener << "Expected the middle button flag is set.";
return false;
}
if (arg->x() != x || arg->y() != y) {
*result_listener << "Expected location: (" << x << ", " << y
<< ") actual: (" << arg->x() << ", " << arg->y() << ")";
return false;
}
return true;
}
class InputInjectorEvdevTest : public testing::Test {
public:
InputInjectorEvdevTest();
protected:
void SimulateMouseClick(int x, int y, EventFlags button, int count);
void ExpectClick(int x, int y, int button, int count);
EventObserver event_observer_;
EventDispatchCallback dispatch_callback_;
MockCursorEvdev cursor_;
std::unique_ptr<DeviceManager> device_manager_;
std::unique_ptr<EventFactoryEvdev> event_factory_;
InputInjectorEvdev injector_;
base::MessageLoop message_loop_;
base::RunLoop run_loop_;
private:
DISALLOW_COPY_AND_ASSIGN(InputInjectorEvdevTest);
};
InputInjectorEvdevTest::InputInjectorEvdevTest()
: dispatch_callback_(base::Bind(&EventObserver::EventDispatchCallback,
base::Unretained(&event_observer_))),
device_manager_(CreateDeviceManagerForTest()),
event_factory_(CreateEventFactoryEvdevForTest(
&cursor_,
device_manager_.get(),
ui::KeyboardLayoutEngineManager::GetKeyboardLayoutEngine(),
dispatch_callback_)),
injector_(CreateDeviceEventDispatcherEvdevForTest(event_factory_.get()),
&cursor_) {
}
void InputInjectorEvdevTest::SimulateMouseClick(int x,
int y,
EventFlags button,
int count) {
injector_.MoveCursorTo(gfx::PointF(x, y));
for (int i = 0; i < count; i++) {
injector_.InjectMouseButton(button, true);
injector_.InjectMouseButton(button, false);
}
}
void InputInjectorEvdevTest::ExpectClick(int x, int y, int button, int count) {
InSequence dummy;
EXPECT_CALL(event_observer_,
OnMouseEvent(MatchesMouseEvent(ET_MOUSE_MOVED, EF_NONE, x, y)));
for (int i = 0; i < count; i++) {
EXPECT_CALL(event_observer_, OnMouseEvent(MatchesMouseEvent(
ET_MOUSE_PRESSED, button, x, y)));
EXPECT_CALL(event_observer_, OnMouseEvent(MatchesMouseEvent(
ET_MOUSE_RELEASED, button, x, y)));
}
}
TEST_F(InputInjectorEvdevTest, LeftClick) {
ExpectClick(12, 13, EF_LEFT_MOUSE_BUTTON, 1);
SimulateMouseClick(12, 13, EF_LEFT_MOUSE_BUTTON, 1);
run_loop_.RunUntilIdle();
}
TEST_F(InputInjectorEvdevTest, RightClick) {
ExpectClick(12, 13, EF_RIGHT_MOUSE_BUTTON, 1);
SimulateMouseClick(12, 13, EF_RIGHT_MOUSE_BUTTON, 1);
run_loop_.RunUntilIdle();
}
TEST_F(InputInjectorEvdevTest, DoubleClick) {
ExpectClick(12, 13, EF_LEFT_MOUSE_BUTTON, 2);
SimulateMouseClick(12, 13, EF_LEFT_MOUSE_BUTTON, 2);
run_loop_.RunUntilIdle();
}
TEST_F(InputInjectorEvdevTest, MouseMoved) {
injector_.MoveCursorTo(gfx::PointF(1, 1));
run_loop_.RunUntilIdle();
EXPECT_EQ(cursor_.GetLocation(), gfx::PointF(1, 1));
}
TEST_F(InputInjectorEvdevTest, MouseDragged) {
InSequence dummy;
EXPECT_CALL(event_observer_,
OnMouseEvent(MatchesMouseEvent(ET_MOUSE_PRESSED,
EF_LEFT_MOUSE_BUTTON, 0, 0)));
EXPECT_CALL(event_observer_,
OnMouseEvent(MatchesMouseEvent(ET_MOUSE_DRAGGED,
EF_LEFT_MOUSE_BUTTON, 1, 1)));
EXPECT_CALL(event_observer_,
OnMouseEvent(MatchesMouseEvent(ET_MOUSE_DRAGGED,
EF_LEFT_MOUSE_BUTTON, 2, 3)));
EXPECT_CALL(event_observer_,
OnMouseEvent(MatchesMouseEvent(ET_MOUSE_RELEASED,
EF_LEFT_MOUSE_BUTTON, 2, 3)));
injector_.InjectMouseButton(EF_LEFT_MOUSE_BUTTON, true);
injector_.MoveCursorTo(gfx::PointF(1, 1));
injector_.MoveCursorTo(gfx::PointF(2, 3));
injector_.InjectMouseButton(EF_LEFT_MOUSE_BUTTON, false);
run_loop_.RunUntilIdle();
}
TEST_F(InputInjectorEvdevTest, MouseWheel) {
InSequence dummy;
EXPECT_CALL(event_observer_, OnMouseWheelEvent(AllOf(
MatchesMouseEvent(ET_MOUSEWHEEL, 0, 10, 20),
Property(&MouseWheelEvent::x_offset, 0),
Property(&MouseWheelEvent::y_offset, 100))));
EXPECT_CALL(event_observer_, OnMouseWheelEvent(AllOf(
MatchesMouseEvent(ET_MOUSEWHEEL, 0, 10, 20),
Property(&MouseWheelEvent::x_offset, 100),
Property(&MouseWheelEvent::y_offset, 0))));
injector_.MoveCursorTo(gfx::PointF(10, 20));
injector_.InjectMouseWheel(0, 100);
injector_.InjectMouseWheel(100, 0);
run_loop_.RunUntilIdle();
}
} // namespace ui
| {
"content_hash": "8d0656d43c3c6d44eeaf65c932dfafa8",
"timestamp": "",
"source": "github",
"line_count": 207,
"max_line_length": 80,
"avg_line_length": 34.79710144927536,
"alnum_prop": 0.6221019019852839,
"repo_name": "danakj/chromium",
"id": "fe07e328cf6603320a18d86510c2076f68629b17",
"size": "7929",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ui/events/ozone/evdev/input_injector_evdev_unittest.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
namespace butil {
namespace snappy {
class Source;
class Sink;
// Windows does not have an iovec type, yet the concept is universally useful.
// It is simple to define it ourselves, so we put it inside our own namespace.
struct iovec {
void* iov_base;
size_t iov_len;
};
// ------------------------------------------------------------------------
// Generic compression/decompression routines.
// ------------------------------------------------------------------------
// Compress the bytes read from "*source" and append to "*sink". Return the
// number of bytes written.
size_t Compress(Source* source, Sink* sink);
// Find the uncompressed length of the given stream, as given by the header.
// Note that the true length could deviate from this; the stream could e.g.
// be truncated.
//
// Also note that this leaves "*source" in a state that is unsuitable for
// further operations, such as RawUncompress(). You will need to rewind
// or recreate the source yourself before attempting any further calls.
bool GetUncompressedLength(Source* source, uint32_t* result);
// ------------------------------------------------------------------------
// Higher-level string based routines (should be sufficient for most users)
// ------------------------------------------------------------------------
// Sets "*output" to the compressed version of "input[0,input_length-1]".
// Original contents of *output are lost.
//
// REQUIRES: "input[]" is not an alias of "*output".
size_t Compress(const char* input, size_t input_length, std::string* output);
// Decompresses "compressed[0,compressed_length-1]" to "*uncompressed".
// Original contents of "*uncompressed" are lost.
//
// REQUIRES: "compressed[]" is not an alias of "*uncompressed".
//
// returns false if the message is corrupted and could not be decompressed
bool Uncompress(const char* compressed, size_t compressed_length,
std::string* uncompressed);
// Decompresses "compressed" to "*uncompressed".
//
// returns false if the message is corrupted and could not be decompressed
bool Uncompress(Source* compressed, Sink* uncompressed);
// This routine uncompresses as much of the "compressed" as possible
// into sink. It returns the number of valid bytes added to sink
// (extra invalid bytes may have been added due to errors; the caller
// should ignore those). The emitted data typically has length
// GetUncompressedLength(), but may be shorter if an error is
// encountered.
size_t UncompressAsMuchAsPossible(Source* compressed, Sink* uncompressed);
// ------------------------------------------------------------------------
// Lower-level character array based routines. May be useful for
// efficiency reasons in certain circumstances.
// ------------------------------------------------------------------------
// REQUIRES: "compressed" must point to an area of memory that is at
// least "MaxCompressedLength(input_length)" bytes in length.
//
// Takes the data stored in "input[0..input_length]" and stores
// it in the array pointed to by "compressed".
//
// "*compressed_length" is set to the length of the compressed output.
//
// Example:
// char* output = new char[snappy::MaxCompressedLength(input_length)];
// size_t output_length;
// RawCompress(input, input_length, output, &output_length);
// ... Process(output, output_length) ...
// delete [] output;
void RawCompress(const char* input,
size_t input_length,
char* compressed,
size_t* compressed_length);
// Given data in "compressed[0..compressed_length-1]" generated by
// calling the Snappy::Compress routine, this routine
// stores the uncompressed data to
// uncompressed[0..GetUncompressedLength(compressed)-1]
// returns false if the message is corrupted and could not be decrypted
bool RawUncompress(const char* compressed, size_t compressed_length,
char* uncompressed);
// Given data from the byte source 'compressed' generated by calling
// the Snappy::Compress routine, this routine stores the uncompressed
// data to
// uncompressed[0..GetUncompressedLength(compressed,compressed_length)-1]
// returns false if the message is corrupted and could not be decrypted
bool RawUncompress(Source* compressed, char* uncompressed);
// Given data in "compressed[0..compressed_length-1]" generated by
// calling the Snappy::Compress routine, this routine
// stores the uncompressed data to the iovec "iov". The number of physical
// buffers in "iov" is given by iov_cnt and their cumulative size
// must be at least GetUncompressedLength(compressed). The individual buffers
// in "iov" must not overlap with each other.
//
// returns false if the message is corrupted and could not be decrypted
bool RawUncompressToIOVec(const char* compressed, size_t compressed_length,
const struct iovec* iov, size_t iov_cnt);
// Given data from the byte source 'compressed' generated by calling
// the Snappy::Compress routine, this routine stores the uncompressed
// data to the iovec "iov". The number of physical
// buffers in "iov" is given by iov_cnt and their cumulative size
// must be at least GetUncompressedLength(compressed). The individual buffers
// in "iov" must not overlap with each other.
//
// returns false if the message is corrupted and could not be decrypted
bool RawUncompressToIOVec(Source* compressed, const struct iovec* iov,
size_t iov_cnt);
// Returns the maximal size of the compressed representation of
// input data that is "source_bytes" bytes in length;
size_t MaxCompressedLength(size_t source_bytes);
// REQUIRES: "compressed[]" was produced by RawCompress() or Compress()
// Returns true and stores the length of the uncompressed data in
// *result normally. Returns false on parsing error.
// This operation takes O(1) time.
bool GetUncompressedLength(const char* compressed, size_t compressed_length,
size_t* result);
// Returns true iff the contents of "compressed[]" can be uncompressed
// successfully. Does not return the uncompressed data. Takes
// time proportional to compressed_length, but is usually at least
// a factor of four faster than actual decompression.
bool IsValidCompressedBuffer(const char* compressed,
size_t compressed_length);
// Returns true iff the contents of "compressed" can be uncompressed
// successfully. Does not return the uncompressed data. Takes
// time proportional to *compressed length, but is usually at least
// a factor of four faster than actual decompression.
// On success, consumes all of *compressed. On failure, consumes an
// unspecified prefix of *compressed.
bool IsValidCompressed(Source* compressed);
// The size of a compression block. Note that many parts of the compression
// code assumes that kBlockSize <= 65536; in particular, the hash table
// can only store 16-bit offsets, and EmitCopy() also assumes the offset
// is 65535 bytes or less. Note also that if you change this, it will
// affect the framing format (see framing_format.txt).
//
// Note that there might be older data around that is compressed with larger
// block sizes, so the decompression code should not rely on the
// non-existence of long backreferences.
static const int kBlockLog = 16;
static const size_t kBlockSize = 1 << kBlockLog;
static const int kMaxHashTableBits = 14;
static const size_t kMaxHashTableSize = 1 << kMaxHashTableBits;
} // end namespace snappy
} // end namespace butil
#endif // BUTIL_THIRD_PARTY_SNAPPY_SNAPPY_H__
| {
"content_hash": "f3b80811ea16029fd892d744cb5e4cb6",
"timestamp": "",
"source": "github",
"line_count": 166,
"max_line_length": 78,
"avg_line_length": 45.6566265060241,
"alnum_prop": 0.690856313497823,
"repo_name": "brpc/brpc",
"id": "a096030e4d4ede7dac9227a0ec506ca5ead382e8",
"size": "9704",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/butil/third_party/snappy/snappy.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "33259"
},
{
"name": "C++",
"bytes": "9214610"
},
{
"name": "CMake",
"bytes": "137534"
},
{
"name": "Dockerfile",
"bytes": "693"
},
{
"name": "Makefile",
"bytes": "39158"
},
{
"name": "Objective-C",
"bytes": "21762"
},
{
"name": "Objective-C++",
"bytes": "32018"
},
{
"name": "Perl",
"bytes": "149499"
},
{
"name": "Python",
"bytes": "23632"
},
{
"name": "Shell",
"bytes": "57667"
},
{
"name": "Thrift",
"bytes": "297"
}
],
"symlink_target": ""
} |
use core::arch::x86_64::__m128i;
use crate::memmem::{
prefilter::{PrefilterFnTy, PrefilterState},
NeedleInfo,
};
// Check that the functions below satisfy the Prefilter function type.
const _: PrefilterFnTy = find;
/// An SSE2 accelerated candidate finder for single-substring search.
///
/// # Safety
///
/// Callers must ensure that the sse2 CPU feature is enabled in the current
/// environment. This feature should be enabled in all x86_64 targets.
#[target_feature(enable = "sse2")]
pub(crate) unsafe fn find(
prestate: &mut PrefilterState,
ninfo: &NeedleInfo,
haystack: &[u8],
needle: &[u8],
) -> Option<usize> {
// If the haystack is too small for SSE2, then just run memchr on the
// rarest byte and be done with it. (It is likely that this code path is
// rarely exercised, since a higher level routine will probably dispatch to
// Rabin-Karp for such a small haystack.)
fn simple_memchr_fallback(
_prestate: &mut PrefilterState,
ninfo: &NeedleInfo,
haystack: &[u8],
needle: &[u8],
) -> Option<usize> {
let (rare, _) = ninfo.rarebytes.as_rare_ordered_usize();
crate::memchr(needle[rare], haystack).map(|i| i.saturating_sub(rare))
}
super::super::genericsimd::find::<__m128i>(
prestate,
ninfo,
haystack,
needle,
simple_memchr_fallback,
)
}
#[cfg(all(test, feature = "std"))]
mod tests {
#[test]
#[cfg(not(miri))]
fn prefilter_permutations() {
use crate::memmem::prefilter::tests::PrefilterTest;
// SAFETY: super::find is safe to call for all inputs on x86.
unsafe { PrefilterTest::run_all_tests(super::find) };
}
}
| {
"content_hash": "8bf7e6da33fe54119b78b1626e3934e3",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 79,
"avg_line_length": 31.181818181818183,
"alnum_prop": 0.6355685131195336,
"repo_name": "nwjs/chromium.src",
"id": "b11356ee000090316440894aba03b611bae773e5",
"size": "1715",
"binary": false,
"copies": "9",
"ref": "refs/heads/nw70",
"path": "third_party/rust/memchr/v2/crate/src/memmem/prefilter/x86/sse.rs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
import { Injectable, OnDestroy, Optional } from '@angular/core';
import { SkyLibResourcesService } from '@skyux/i18n';
import { SkyThemeService, SkyThemeSettings } from '@skyux/theme';
import {
CellClassParams,
ColDef,
EditableCallbackParams,
GridOptions,
ICellRendererParams,
RowClassParams,
SuppressKeyboardEventParams,
ValueFormatterParams,
} from 'ag-grid-community';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { SkyAgGridAdapterService } from './ag-grid-adapter.service';
import { applySkyLookupPropertiesDefaults } from './apply-lookup-properties-defaults';
import { SkyAgGridCellEditorAutocompleteComponent } from './cell-editors/cell-editor-autocomplete/cell-editor-autocomplete.component';
import { SkyAgGridCellEditorCurrencyComponent } from './cell-editors/cell-editor-currency/cell-editor-currency.component';
import { SkyAgGridCellEditorDatepickerComponent } from './cell-editors/cell-editor-datepicker/cell-editor-datepicker.component';
import { SkyAgGridCellEditorLookupComponent } from './cell-editors/cell-editor-lookup/cell-editor-lookup.component';
import { SkyAgGridCellEditorNumberComponent } from './cell-editors/cell-editor-number/cell-editor-number.component';
import { SkyAgGridCellEditorTextComponent } from './cell-editors/cell-editor-text/cell-editor-text.component';
import { SkyAgGridCellRendererCurrencyValidatorComponent } from './cell-renderers/cell-renderer-currency/cell-renderer-currency-validator.component';
import { SkyAgGridCellRendererCurrencyComponent } from './cell-renderers/cell-renderer-currency/cell-renderer-currency.component';
import { SkyAgGridCellRendererLookupComponent } from './cell-renderers/cell-renderer-lookup/cell-renderer-lookup.component';
import { SkyAgGridCellRendererRowSelectorComponent } from './cell-renderers/cell-renderer-row-selector/cell-renderer-row-selector.component';
import { SkyAgGridCellRendererValidatorTooltipComponent } from './cell-renderers/cell-renderer-validator-tooltip/cell-renderer-validator-tooltip.component';
import { SkyAgGridHeaderGroupComponent } from './header/header-group.component';
import { SkyAgGridHeaderComponent } from './header/header.component';
import { SkyCellClass } from './types/cell-class';
import { SkyCellType } from './types/cell-type';
import { SkyHeaderClass } from './types/header-class';
import { SkyGetGridOptionsArgs } from './types/sky-grid-options';
function autocompleteComparator(
value1: { name: string },
value2: { name: string }
): number {
if (value1 && value2) {
if (value1.name > value2.name) {
return 1;
}
if (value1.name < value2.name) {
return -1;
}
return 0;
}
return value1 ? 1 : -1;
}
function autocompleteFormatter(params: ValueFormatterParams): string {
return params.value && params.value.name;
}
function dateComparator(date1: Date | string, date2: Date | string): number {
let date1value = date1;
let date2value = date2;
if (typeof date1value === 'string') {
date1value = new Date(date1);
}
if (typeof date2value === 'string') {
date2value = new Date(date2);
}
if (date1value && date2value) {
if (date1value > date2value) {
return 1;
}
if (date1value < date2value) {
return -1;
}
return 0;
}
return date1value ? 1 : -1;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function getValidatorCellRendererSelector(component: string, fallback?: any) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (params: ICellRendererParams): any => {
if (
params.colDef &&
typeof params.colDef.cellRendererParams?.skyComponentProperties
?.validator === 'function'
) {
if (
!params.colDef.cellRendererParams.skyComponentProperties.validator(
params.value,
params.data,
params.rowIndex
)
) {
return {
component,
params: {
...params.colDef.cellRendererParams,
},
};
}
}
return fallback;
};
}
let rowNodeId = -1;
/**
* `SkyAgGridService` provides methods to get AG Grid `gridOptions` to ensure grids match SKY UX functionality. The `gridOptions` can be overridden, and include registered SKY UX column types.
*/
@Injectable({
providedIn: 'any',
})
export class SkyAgGridService implements OnDestroy {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
#keyMap = new WeakMap<any, string>();
#ngUnsubscribe = new Subject<void>();
#currentTheme: SkyThemeSettings | undefined = undefined;
#agGridAdapterService: SkyAgGridAdapterService;
#resources: SkyLibResourcesService | undefined;
constructor(
agGridAdapterService: SkyAgGridAdapterService,
@Optional() themeSvc?: SkyThemeService,
@Optional() resources?: SkyLibResourcesService
) {
this.#agGridAdapterService = agGridAdapterService;
this.#resources = resources;
/*istanbul ignore else*/
if (themeSvc) {
themeSvc.settingsChange
.pipe(takeUntil(this.#ngUnsubscribe))
.subscribe((settingsChange) => {
this.#currentTheme = settingsChange.currentSettings;
});
}
}
public ngOnDestroy(): void {
this.#ngUnsubscribe.next();
this.#ngUnsubscribe.complete();
}
/**
* Returns [AG Grid `gridOptions`](https://www.ag-grid.com/javascript-grid-properties/) with default SKY UX options, styling, and cell renderers registered for read-only grids.
* @param args
* @returns
*/
public getGridOptions(args: SkyGetGridOptionsArgs): GridOptions {
const defaultGridOptions = this.#getDefaultGridOptions(args);
const mergedGridOptions = this.#mergeGridOptions(
defaultGridOptions,
args.gridOptions
);
return mergedGridOptions;
}
/**
* Returns [AG Grid `gridOptions`](https://www.ag-grid.com/javascript-grid-properties/) with default SKY UX options, styling, and cell editors registered for editable grids.
* @param args
* @returns
*/
public getEditableGridOptions(args: SkyGetGridOptionsArgs): GridOptions {
const defaultGridOptions = this.#getDefaultEditableGridOptions(args);
const mergedGridOptions = this.#mergeGridOptions(
defaultGridOptions,
args.gridOptions
);
return mergedGridOptions;
}
public getHeaderHeight(): number {
return this.#currentTheme?.theme?.name === 'modern' ? 60 : 37;
}
#mergeGridOptions(
defaultGridOptions: GridOptions,
providedGridOptions: GridOptions
): GridOptions {
const mergedGridOptions: GridOptions = {
...defaultGridOptions,
...providedGridOptions,
components: {
...providedGridOptions.components,
// Apply default components last to prevent consumers from overwriting our component types.
...defaultGridOptions.components,
},
columnTypes: {
...providedGridOptions.columnTypes,
// apply default second to prevent consumers from overwriting our default column types
...defaultGridOptions.columnTypes,
},
defaultColDef: {
...defaultGridOptions.defaultColDef,
...providedGridOptions.defaultColDef,
// allow consumers to override all defaultColDef properties except cellClassRules, which we reserve for styling
cellClassRules: defaultGridOptions.defaultColDef?.cellClassRules,
},
defaultColGroupDef: {
...defaultGridOptions.defaultColGroupDef,
...providedGridOptions.defaultColGroupDef,
},
icons: {
...defaultGridOptions.icons,
...providedGridOptions.icons,
},
};
// Prefer `getRowNodeId` over `getNodeId` if set by the consumer, for backward compatibility.
if (mergedGridOptions.getRowNodeId) {
delete mergedGridOptions.getRowId;
}
return mergedGridOptions;
}
#getDefaultGridOptions(args: SkyGetGridOptionsArgs): GridOptions {
// cellClassRules can be functions or string expressions
const cellClassRuleTrueExpression = (): boolean => true;
function getEditableFn(
isUneditable?: boolean
): (params: CellClassParams) => boolean {
return function (params: CellClassParams): boolean {
let isEditable = params.colDef.editable;
if (typeof isEditable === 'function') {
const column = params.columnApi.getColumn(params.colDef.field);
isEditable = isEditable({
...params,
column,
} as EditableCallbackParams);
}
return isUneditable ? !isEditable : !!isEditable;
};
}
const editableCellClassRules = {
[SkyCellClass.Editable]: getEditableFn(),
[SkyCellClass.Uneditable]: getEditableFn(true),
};
function getValidatorFn(): (params: CellClassParams) => boolean {
return function (param: CellClassParams) {
if (
param.colDef &&
typeof param.colDef.cellRendererParams?.skyComponentProperties
?.validator === 'function'
) {
return !param.colDef.cellRendererParams.skyComponentProperties.validator(
param.value,
param.data,
param.rowIndex
);
}
return false;
};
}
const validatorCellClassRules = {
[SkyCellClass.Invalid]: getValidatorFn(),
};
const defaultSkyGridOptions: GridOptions = {
columnTypes: {
[SkyCellType.Autocomplete]: {
cellClassRules: {
[SkyCellClass.Autocomplete]: cellClassRuleTrueExpression,
...editableCellClassRules,
},
cellEditor: SkyAgGridCellEditorAutocompleteComponent,
valueFormatter: autocompleteFormatter,
comparator: autocompleteComparator,
minWidth: 185,
},
[SkyCellType.Currency]: {
cellClassRules: {
[SkyCellClass.Currency]: cellClassRuleTrueExpression,
...validatorCellClassRules,
...editableCellClassRules,
},
cellRendererSelector: getValidatorCellRendererSelector(
'sky-ag-grid-cell-renderer-currency-validator',
{ component: 'sky-ag-grid-cell-renderer-currency' }
),
cellEditor: SkyAgGridCellEditorCurrencyComponent,
headerClass: SkyHeaderClass.RightAligned,
minWidth: 185,
},
[SkyCellType.Date]: {
cellClassRules: {
[SkyCellClass.Date]: cellClassRuleTrueExpression,
...editableCellClassRules,
},
cellEditor: SkyAgGridCellEditorDatepickerComponent,
comparator: dateComparator,
minWidth: this.#currentTheme?.theme?.name === 'modern' ? 180 : 160,
valueFormatter: (params: ValueFormatterParams) =>
this.#dateFormatter(params, args.locale),
},
[SkyCellType.Lookup]: {
cellClassRules: {
[SkyCellClass.Lookup]: cellClassRuleTrueExpression,
...editableCellClassRules,
},
cellEditor: SkyAgGridCellEditorLookupComponent,
cellRenderer: SkyAgGridCellRendererLookupComponent,
valueFormatter: (params) => {
const lookupProperties = applySkyLookupPropertiesDefaults(params);
return (params.value || [])
.map((value: Record<string, unknown>) => {
return value[lookupProperties.descriptorProperty as string];
})
.filter((value: unknown) => value !== '' && value !== undefined)
.join('; ');
},
minWidth: 185,
},
[SkyCellType.Number]: {
cellClassRules: {
[SkyCellClass.Number]: cellClassRuleTrueExpression,
...validatorCellClassRules,
...editableCellClassRules,
},
cellRendererSelector: getValidatorCellRendererSelector(
'sky-ag-grid-cell-renderer-validator-tooltip'
),
cellEditor: SkyAgGridCellEditorNumberComponent,
headerClass: SkyHeaderClass.RightAligned,
},
[SkyCellType.RowSelector]: {
cellClassRules: {
[SkyCellClass.RowSelector]: cellClassRuleTrueExpression,
[SkyCellClass.Uneditable]: cellClassRuleTrueExpression,
},
cellRenderer: SkyAgGridCellRendererRowSelectorComponent,
headerName: '',
minWidth: 55,
maxWidth: 55,
sortable: false,
width: 55,
},
[SkyCellType.Text]: {
cellClassRules: {
[SkyCellClass.Text]: cellClassRuleTrueExpression,
...validatorCellClassRules,
...editableCellClassRules,
},
cellEditor: SkyAgGridCellEditorTextComponent,
cellRendererSelector: getValidatorCellRendererSelector(
'sky-ag-grid-cell-renderer-validator-tooltip'
),
},
[SkyCellType.Validator]: {
cellClassRules: {
...validatorCellClassRules,
...editableCellClassRules,
},
cellRendererSelector: getValidatorCellRendererSelector(
'sky-ag-grid-cell-renderer-validator-tooltip'
),
},
},
defaultColDef: {
cellClassRules: editableCellClassRules,
headerComponent: SkyAgGridHeaderComponent,
minWidth: 100,
resizable: true,
sortable: true,
suppressKeyboardEvent: (keypress: SuppressKeyboardEventParams) =>
this.#suppressTab(keypress),
},
defaultColGroupDef: {
headerGroupComponent: SkyAgGridHeaderGroupComponent,
},
domLayout: 'autoHeight',
enterMovesDownAfterEdit: true,
components: {
'sky-ag-grid-cell-renderer-currency':
SkyAgGridCellRendererCurrencyComponent,
'sky-ag-grid-cell-renderer-currency-validator':
SkyAgGridCellRendererCurrencyValidatorComponent,
'sky-ag-grid-cell-renderer-validator-tooltip':
SkyAgGridCellRendererValidatorTooltipComponent,
},
getRowId: (params) => {
const dataId = params.data.id;
if (dataId !== undefined) {
return `${params.data.id}`;
}
if (!this.#keyMap.has(params.data)) {
this.#keyMap.set(params.data, `${rowNodeId--}`);
}
return this.#keyMap.get(params.data) as string;
},
getRowClass: (params: RowClassParams) => {
if (params.node.id) {
return `sky-ag-grid-row-${params.node.id}`;
} else {
return undefined;
}
},
headerHeight: this.getHeaderHeight(),
icons: {
sortDescending: this.#getIconTemplate('caret-down'),
sortAscending: this.#getIconTemplate('caret-up'),
columnMoveMove: this.#getIconTemplate('arrows'),
columnMoveHide: this.#getIconTemplate('arrows'),
columnMoveLeft: this.#getIconTemplate('arrows'),
columnMoveRight: this.#getIconTemplate('arrows'),
columnMovePin: this.#getIconTemplate('arrows'),
},
onCellFocused: () => this.#onCellFocused(),
rowHeight: this.#getRowHeight(),
getRowHeight: () => this.#getRowHeight(),
rowMultiSelectWithClick: true,
rowSelection: 'multiple',
singleClickEdit: true,
sortingOrder: ['desc', 'asc', null],
suppressRowClickSelection: true,
suppressDragLeaveHidesColumns: true,
};
const columnTypes = defaultSkyGridOptions.columnTypes as Record<
string,
ColDef
>;
columnTypes[SkyCellType.CurrencyValidator] = {
...columnTypes[SkyCellType.Currency],
cellRendererParams: {
skyComponentProperties: {
validator: (value: string): boolean => {
return !!`${value || ''}`.match(/^[^0-9]*(\d+[,.]?)+\d*[^0-9]*$/);
},
validatorMessage: 'Please enter a valid currency',
},
},
};
/*istanbul ignore else*/
if (this.#resources) {
this.#resources
.getString('sky_ag_grid_cell_renderer_currency_validator_message')
.subscribe((value) => {
columnTypes[
SkyCellType.CurrencyValidator
].cellRendererParams.skyComponentProperties.validatorMessage = value;
});
}
columnTypes[SkyCellType.NumberValidator] = {
...columnTypes[SkyCellType.Validator],
...columnTypes[SkyCellType.Number],
cellClassRules: {
...columnTypes[SkyCellType.Validator].cellClassRules,
...columnTypes[SkyCellType.Number].cellClassRules,
},
cellRendererParams: {
skyComponentProperties: {
validator: (value: string): boolean => {
return !!value && !isNaN(parseFloat(value));
},
validatorMessage: 'Please enter a valid number',
},
},
};
/*istanbul ignore else*/
if (this.#resources) {
this.#resources
.getString('sky_ag_grid_cell_renderer_number_validator_message')
.subscribe((value) => {
columnTypes[
SkyCellType.NumberValidator
].cellRendererParams.skyComponentProperties.validatorMessage = value;
});
}
return defaultSkyGridOptions;
}
#onCellFocused(): void {
const currentElement = this.#agGridAdapterService.getFocusedElement();
this.#agGridAdapterService.focusOnFocusableChildren(currentElement);
}
#getDefaultEditableGridOptions(args: SkyGetGridOptionsArgs): GridOptions {
const defaultGridOptions = this.#getDefaultGridOptions(args);
defaultGridOptions.rowSelection = undefined;
return defaultGridOptions;
}
#dateFormatter(
params: ValueFormatterParams,
locale: string = 'en-us'
): string {
const dateConfig = { year: 'numeric', month: '2-digit', day: '2-digit' };
let date: Date = params.value;
if (date && typeof date === 'string') {
date = new Date(params.value);
}
const formattedDate =
date &&
date.toLocaleDateString &&
date.toLocaleDateString(locale, dateConfig as Intl.DateTimeFormatOptions);
if (date && date.getTime && !isNaN(date.getTime())) {
return formattedDate;
}
return '';
}
#getIconTemplate(iconName: string): string {
return `<i class="fa fa-${iconName}"></i>`;
}
#suppressTab(params: SuppressKeyboardEventParams): boolean {
if (params.event.code === 'Tab') {
if (params.editing) {
const currentlyFocusedEl =
this.#agGridAdapterService.getFocusedElement();
// inline cell editors have the 'ag-cell' class, while popup editors have the 'ag-popup-editor' class
const cellEl = this.#agGridAdapterService.getElementOrParentWithClass(
currentlyFocusedEl,
'ag-cell'
);
const popupEl = this.#agGridAdapterService.getElementOrParentWithClass(
currentlyFocusedEl,
'ag-popup-editor'
);
const parentEl = cellEl || (popupEl as HTMLElement);
const nextFocusableElementInCell =
this.#agGridAdapterService.getNextFocusableElement(
currentlyFocusedEl,
parentEl,
params.event.shiftKey
);
return !!nextFocusableElementInCell;
}
return true;
}
return false;
}
#getRowHeight(): number {
return this.#currentTheme?.theme?.name === 'modern' ? 60 : 38;
}
}
| {
"content_hash": "7bdc67688a973b96bfa1f88967af98ba",
"timestamp": "",
"source": "github",
"line_count": 568,
"max_line_length": 192,
"avg_line_length": 34.12852112676056,
"alnum_prop": 0.6498839308743874,
"repo_name": "blackbaud/skyux",
"id": "7993ac33b21b5cdc1998d1dba9b9e086ba03ba37",
"size": "19385",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "libs/components/ag-grid/src/lib/modules/ag-grid/ag-grid.service.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "806202"
},
{
"name": "JavaScript",
"bytes": "39129"
},
{
"name": "SCSS",
"bytes": "320321"
},
{
"name": "TypeScript",
"bytes": "7288448"
}
],
"symlink_target": ""
} |
<?php
namespace libphonenumber;
/**
* Country code source from number
*/
class CountryCodeSource
{
/**
* The country_code is derived based on a phone number with a leading "+", e.g. the French
* number "+33 1 42 68 53 00".
*/
const FROM_NUMBER_WITH_PLUS_SIGN = 0;
/**
* The country_code is derived based on a phone number with a leading IDD, e.g. the French
* number "011 33 1 42 68 53 00", as it is dialled from US.
*/
const FROM_NUMBER_WITH_IDD = 1;
/**
* The country_code is derived based on a phone number without a leading "+", e.g. the French
* number "33 1 42 68 53 00" when defaultCountry is supplied as France.
*/
const FROM_NUMBER_WITHOUT_PLUS_SIGN = 2;
/**
* The country_code is derived NOT based on the phone number itself, but from the defaultCountry
* parameter provided in the parsing function by the clients. This happens mostly for numbers
* written in the national format (without country code). For example, this would be set when
* parsing the French number "01 42 68 53 00", when defaultCountry is supplied as France.
*/
const FROM_DEFAULT_COUNTRY = 3;
}
| {
"content_hash": "a37a62ad39060e0b5901ef98e5b93620",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 100,
"avg_line_length": 36.9375,
"alnum_prop": 0.6632825719120136,
"repo_name": "helsingborg-stad/api-event-manager",
"id": "0a9b9dfdf3e5c1adb311b9755b15ac00683ef468",
"size": "1182",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "vendor/giggsey/libphonenumber-for-php/src/libphonenumber/CountryCodeSource.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "38065"
},
{
"name": "PHP",
"bytes": "800540"
},
{
"name": "SCSS",
"bytes": "11019"
}
],
"symlink_target": ""
} |
"""
CacheItem interface:
'_id': string,
'url': string,
'response_url': string,
'body': string,
'head': string,
'response_code': int,
'cookies': None,#grab.response.cookies,
TODO: WTF with cookies???
"""
from hashlib import sha1
import zlib
import logging
import pymongo
from bson import Binary
import time
import six
from weblib.encoding import make_str
from grab.response import Response
from grab.cookie import CookieManager
logger = logging.getLogger('grab.spider.cache_backend.mongo')
class CacheBackend(object):
def __init__(self, database, use_compression=True, spider=None, **kwargs):
self.spider = spider
self.db = pymongo.MongoClient(**kwargs)[database]
self.use_compression = use_compression
def get_item(self, url, timeout=None):
"""
Returned item should have specific interface. See module docstring.
"""
_hash = self.build_hash(url)
if timeout is not None:
ts = int(time.time()) - timeout
query = {'_id': _hash, 'timestamp': {'$gt': ts}}
else:
query = {'_id': _hash}
return self.db.cache.find_one(query)
def build_hash(self, url):
utf_url = make_str(url)
return sha1(utf_url).hexdigest()
def remove_cache_item(self, url):
_hash = self.build_hash(url)
self.db.cache.remove({'_id': _hash})
def load_response(self, grab, cache_item):
grab.setup_document(cache_item['body'])
body = cache_item['body']
if self.use_compression:
body = zlib.decompress(body)
def custom_prepare_response_func(transport, grab):
response = Response()
response.head = cache_item['head'].decode('utf-8')
response.body = body
response.code = cache_item['response_code']
response.download_size = len(body)
response.upload_size = 0
response.download_speed = 0
response.url = cache_item['response_url']
response.parse(charset=grab.config['document_charset'])
response.cookies = CookieManager(transport.extract_cookiejar())
response.from_cache = True
return response
grab.process_request_result(custom_prepare_response_func)
def save_response(self, url, grab):
body = grab.response.body
if self.use_compression:
body = zlib.compress(body)
_hash = self.build_hash(url)
item = {
'_id': _hash,
'timestamp': int(time.time()),
'url': url,
'response_url': grab.response.url,
'body': Binary(body),
'head': Binary(grab.response.head.encode('utf-8')),
'response_code': grab.response.code,
'cookies': None,
}
try:
self.db.cache.save(item, w=1)
except Exception as ex:
if 'document too large' in six.text_type(ex):
logging.error('Document too large. It was not saved into mongo'
' cache. Url: %s' % url)
else:
raise
def clear(self):
self.db.cache.remove()
def size(self):
return self.db.cache.count()
def has_item(self, url, timeout=None):
"""
Test if required item exists in the cache.
"""
_hash = self.build_hash(url)
if timeout is not None:
ts = int(time.time()) - timeout
query = {'_id': _hash, 'timestamp': {'$gt': ts}}
else:
query = {'_id': _hash}
doc = self.db.cache.find_one(query, {'id': 1})
return doc is not None
| {
"content_hash": "0e8fac1fc584ffdbdb8705278fa0e8d3",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 79,
"avg_line_length": 30.322314049586776,
"alnum_prop": 0.5696375034069229,
"repo_name": "huiyi1990/grab",
"id": "7f79dda385839742707f61e46853c3d104e45a80",
"size": "3669",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "grab/spider/cache_backend/mongo.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "5434"
},
{
"name": "Makefile",
"bytes": "910"
},
{
"name": "PostScript",
"bytes": "2788"
},
{
"name": "Python",
"bytes": "405529"
}
],
"symlink_target": ""
} |
package org.apache.hadoop.hive.ql.plan;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
/**
* All member variables should have a setters and getters of the form get<member
* name> and set<member name> or else they won't be recreated properly at run
* time.
*
*/
@Explain(displayName = "UDTF Operator")
public class UDTFDesc extends AbstractOperatorDesc {
private static final long serialVersionUID = 1L;
private GenericUDTF genericUDTF;
private boolean outerLV;
public UDTFDesc() {
}
public UDTFDesc(final GenericUDTF genericUDTF, boolean outerLV) {
this.genericUDTF = genericUDTF;
this.outerLV = outerLV;
}
public GenericUDTF getGenericUDTF() {
return genericUDTF;
}
public void setGenericUDTF(final GenericUDTF genericUDTF) {
this.genericUDTF = genericUDTF;
}
@Explain(displayName = "function name")
public String getUDTFName() {
return genericUDTF.toString();
}
public boolean isOuterLV() {
return outerLV;
}
public void setOuterLV(boolean outerLV) {
this.outerLV = outerLV;
}
@Explain(displayName = "outer lateral view")
public String isOuterLateralView() {
return outerLV ? "true" : null;
}
}
| {
"content_hash": "5e7395f6cff08c6a2dede3a46078cb4c",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 80,
"avg_line_length": 22.641509433962263,
"alnum_prop": 0.7166666666666667,
"repo_name": "wangbin83-gmail-com/hive-1.1.0-cdh5.4.8",
"id": "741a0e073c56ba4fd0d4031530ee1763509b1716",
"size": "2006",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "ql/src/java/org/apache/hadoop/hive/ql/plan/UDTFDesc.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "48158"
},
{
"name": "C",
"bytes": "120921"
},
{
"name": "C++",
"bytes": "163950"
},
{
"name": "CSS",
"bytes": "1372"
},
{
"name": "GAP",
"bytes": "117068"
},
{
"name": "Groff",
"bytes": "5379"
},
{
"name": "HTML",
"bytes": "22057"
},
{
"name": "Java",
"bytes": "24439585"
},
{
"name": "M",
"bytes": "2173"
},
{
"name": "Makefile",
"bytes": "6963"
},
{
"name": "PHP",
"bytes": "1717937"
},
{
"name": "PLpgSQL",
"bytes": "43781"
},
{
"name": "Perl",
"bytes": "316328"
},
{
"name": "PigLatin",
"bytes": "12333"
},
{
"name": "Protocol Buffer",
"bytes": "6353"
},
{
"name": "Python",
"bytes": "268109"
},
{
"name": "SQLPL",
"bytes": "1414"
},
{
"name": "Shell",
"bytes": "152105"
},
{
"name": "Thrift",
"bytes": "93411"
},
{
"name": "XSLT",
"bytes": "7619"
}
],
"symlink_target": ""
} |
# cssbuttongenerator-css-rails
[][gem]
[][travis]
[][gemnasium]
[][code climate]
[][coveralls]
[gem]: https://rubygems.org/gems/cssbuttongenerator-css-rails
[travis]: https://travis-ci.org/jhx/gem-cssbuttongenerator-css-rails
[gemnasium]: https://gemnasium.com/jhx/gem-cssbuttongenerator-css-rails
[code climate]: https://codeclimate.com/github/jhx/gem-cssbuttongenerator-css-rails
[coveralls]: https://coveralls.io/r/jhx/gem-cssbuttongenerator-css-rails
> Gemified by Doc Walker
Provides imageless css buttons for the Rails 3.1+ asset pipeline.
## Installation
Add these lines to your application's `Gemfile`:
```rb
# imageless css buttons packaged for the rails asset pipeline
gem 'cssbuttongenerator-css-rails', '~> 1.0.5'
```
And then execute:
```sh
$ bundle
```
Or install it yourself as:
```sh
$ gem install cssbuttongenerator-css-rails
```
## Usage
Add these lines to `app/assets/stylesheets/application.css`
```css
/*
provides imageless css buttons from gem 'cssbuttongenerator-css-rails':
= require cssbuttongenerator-css-rails
*/
```
Use one or more of the following button classes:
```css
.button_css_grey_0
.button_css_red_1
.button_css_green_2
.button_css_blue_3
.button_css_orange_4
.button_css_magenta_5
.button_css_violet_6
.button_css_green_8
.button_css_red_9
.button_css_orange_10
.button_css_blue_12
.button_css_grey_13
.button_css_orange_14
.button_css_green_15
.button_css_blue_16
.button_css_orange_18
.button_css_blue_20
.button_css_orange_21
.button_css_red_22
.button_css_red_24
.button_css_green_26
```
Rails/HAML examples:
```haml
= f.submit :value => 'Submit', :class => :button_css_green_2
= link_to 'Cancel', :back, :class => :button_css_blue_3
```
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
## Acknowledgements
- [CSS Button Generator](http://www.cssbuttongenerator.com) Imageless css buttons simplified with css button generator
- [RailsCast #245](http://railscasts.com/episodes/245-new-gem-with-bundler) New Gem with Bundler -- inspiration
- [Gemify Assets for Rails](http://prioritized.net/blog/gemify-assets-for-rails/) -- guidance
| {
"content_hash": "e4b244c934ea699051d20f726ca67c74",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 125,
"avg_line_length": 29.242105263157896,
"alnum_prop": 0.7429805615550756,
"repo_name": "jhx/gem-cssbuttongenerator-css-rails",
"id": "876fef6bb3a27ed1d3bb521df0eb3dbc9e07653c",
"size": "2778",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "26679"
},
{
"name": "HTML",
"bytes": "2316"
},
{
"name": "Ruby",
"bytes": "16916"
}
],
"symlink_target": ""
} |
package com.facebook.buck.ocaml;
import com.facebook.buck.graph.MutableDirectedGraph;
import com.facebook.buck.graph.TopologicalSort;
import com.facebook.buck.util.MoreCollectors;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Stream;
import javax.annotation.Nullable;
/**
* Parse output of ocamldep tool and build dependency graph of ocaml source files (*.ml & *.mli)
*/
public class OcamlDependencyGraphGenerator {
private static final String OCAML_SOURCE_AND_DEPS_SEPARATOR = ":";
private static final String OCAML_DEPS_SEPARATOR = " ";
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
@Nullable
private MutableDirectedGraph<String> graph;
public ImmutableList<String> generate(String depToolOutput) {
parseDependencies(depToolOutput);
Preconditions.checkNotNull(graph);
final ImmutableList<String> sortedDeps = TopologicalSort.sort(graph);
// Two copies of dependencies as .cmo can map to .ml or .re
return Stream.concat(
sortedDeps.stream().map(input -> replaceObjExtWithSourceExt(input, false /* isReason */)),
sortedDeps.stream().map(input -> replaceObjExtWithSourceExt(input, true /* isReason */)))
.collect(MoreCollectors.toImmutableList());
}
private String replaceObjExtWithSourceExt(String name, boolean isReason) {
return name.replaceAll(
OcamlCompilables.OCAML_CMX_REGEX,
isReason ? OcamlCompilables.OCAML_RE : OcamlCompilables.OCAML_ML)
.replaceAll(
OcamlCompilables.OCAML_CMI_REGEX,
isReason ? OcamlCompilables.OCAML_REI : OcamlCompilables.OCAML_MLI);
}
public ImmutableMap<Path, ImmutableList<Path>> generateDependencyMap(
String depString) {
ImmutableMap.Builder<Path, ImmutableList<Path>> mapBuilder = ImmutableMap.builder();
Iterable<String> lines = Splitter.on(LINE_SEPARATOR).split(depString);
for (String line : lines) {
List<String> sourceAndDeps = Splitter.on(OCAML_SOURCE_AND_DEPS_SEPARATOR)
.trimResults().splitToList(line);
if (sourceAndDeps.size() >= 1) {
String sourceML = replaceObjExtWithSourceExt(sourceAndDeps.get(0), /* isReason */ false);
String sourceRE = replaceObjExtWithSourceExt(sourceAndDeps.get(0), /* isReason */ true);
if (sourceML.endsWith(OcamlCompilables.OCAML_ML) ||
sourceML.endsWith(OcamlCompilables.OCAML_MLI)) {
// Two copies of dependencies as .cmo can map to .ml or .re
ImmutableList<Path> dependencies = Splitter.on(OCAML_DEPS_SEPARATOR)
.trimResults()
.splitToList(sourceAndDeps.get(1))
.stream()
.filter(input -> !input.isEmpty())
.flatMap(input ->
Stream.of(
Paths.get(replaceObjExtWithSourceExt(input, /* isReason */ false)),
Paths.get(replaceObjExtWithSourceExt(input, /* isReason */ true))))
.collect(MoreCollectors.toImmutableList());
mapBuilder
.put(Paths.get(sourceML), dependencies)
.put(Paths.get(sourceRE), dependencies);
}
}
}
return mapBuilder.build();
}
private void parseDependencies(String stdout) {
graph = new MutableDirectedGraph<>();
Iterable<String> lines = Splitter.on(LINE_SEPARATOR).split(stdout);
for (String line : lines) {
List<String> sourceAndDeps = Splitter.on(OCAML_SOURCE_AND_DEPS_SEPARATOR)
.trimResults().splitToList(line);
if (sourceAndDeps.size() >= 1) {
String source = sourceAndDeps.get(0);
if (source.endsWith(OcamlCompilables.OCAML_CMX) || source.endsWith(
OcamlCompilables.OCAML_CMI)) {
addSourceDeps(sourceAndDeps, source);
}
}
}
}
private void addSourceDeps(List<String> sourceAndDeps, String source) {
Preconditions.checkNotNull(graph);
graph.addNode(source);
if (sourceAndDeps.size() >= 2) {
String deps = sourceAndDeps.get(1);
if (!deps.isEmpty()) {
List<String> dependencies = Splitter.on(OCAML_DEPS_SEPARATOR)
.trimResults().splitToList(deps);
for (String dep : dependencies) {
if (!dep.isEmpty()) {
graph.addEdge(source, dep);
}
}
}
}
}
}
| {
"content_hash": "2a5b213a6b921d5c4c25f83728f79e15",
"timestamp": "",
"source": "github",
"line_count": 119,
"max_line_length": 100,
"avg_line_length": 38.319327731092436,
"alnum_prop": 0.6690789473684211,
"repo_name": "daedric/buck",
"id": "16880d49a734b7d9cdfc8d26d393c68e5776acde",
"size": "5165",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/com/facebook/buck/ocaml/OcamlDependencyGraphGenerator.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "579"
},
{
"name": "Batchfile",
"bytes": "2093"
},
{
"name": "C",
"bytes": "252007"
},
{
"name": "C#",
"bytes": "237"
},
{
"name": "C++",
"bytes": "9880"
},
{
"name": "CSS",
"bytes": "54863"
},
{
"name": "D",
"bytes": "1017"
},
{
"name": "Go",
"bytes": "15018"
},
{
"name": "Groovy",
"bytes": "3362"
},
{
"name": "HTML",
"bytes": "6372"
},
{
"name": "Haskell",
"bytes": "895"
},
{
"name": "IDL",
"bytes": "128"
},
{
"name": "Java",
"bytes": "18174574"
},
{
"name": "JavaScript",
"bytes": "934578"
},
{
"name": "Kotlin",
"bytes": "2079"
},
{
"name": "Lex",
"bytes": "2595"
},
{
"name": "Makefile",
"bytes": "1816"
},
{
"name": "Matlab",
"bytes": "47"
},
{
"name": "OCaml",
"bytes": "3949"
},
{
"name": "Objective-C",
"bytes": "1163632"
},
{
"name": "Objective-C++",
"bytes": "34"
},
{
"name": "PowerShell",
"bytes": "244"
},
{
"name": "Python",
"bytes": "577083"
},
{
"name": "Roff",
"bytes": "440"
},
{
"name": "Rust",
"bytes": "3335"
},
{
"name": "Scala",
"bytes": "4906"
},
{
"name": "Shell",
"bytes": "42982"
},
{
"name": "Smalltalk",
"bytes": "4721"
},
{
"name": "Standard ML",
"bytes": "15"
},
{
"name": "Swift",
"bytes": "6592"
},
{
"name": "Thrift",
"bytes": "18953"
},
{
"name": "Yacc",
"bytes": "323"
}
],
"symlink_target": ""
} |
(function(){
Template.__define__("pending", (function() {
var self = this;
var template = this;
return HTML.Raw('<div class="text-center">\n <br>\n Coming Soon...\n </div>');
}));
})();
| {
"content_hash": "83ae722d92a803561b1a7018fbdf3e7d",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 87,
"avg_line_length": 25,
"alnum_prop": 0.56,
"repo_name": "josmas/UCapp",
"id": "7a47288e71c47ce07589e5946d4e6e39473b6115",
"size": "200",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "platforms/android/assets/www/client/views/template.pending.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "257952"
},
{
"name": "D",
"bytes": "23204"
},
{
"name": "Java",
"bytes": "738072"
},
{
"name": "JavaScript",
"bytes": "4590722"
},
{
"name": "Shell",
"bytes": "11293"
}
],
"symlink_target": ""
} |
require "spec_helper"
describe Keynote::Extractor do
it "has a version number" do
expect(Keynote::Extractor::VERSION).not_to be nil
end
it "returns text from keynote presentation" do
file = file = File.expand_path("spec/support/whydots.key", Dir.pwd)
file_text = Keynote::Extractor::Parse.text(file)
expect(file_text).to include('president')
expect(file_text).to include('greenhouse gas')
end
it "returns all iwa files from larger new keynote presentations" do
file = file = File.expand_path("spec/support/process.key", Dir.pwd)
file_text = Keynote::Extractor::Parse.text(file)
end
end
| {
"content_hash": "f50146bc48784a19da719b56a530c2c1",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 71,
"avg_line_length": 33.21052631578947,
"alnum_prop": 0.7099841521394612,
"repo_name": "cbaykam/keynote-extractor",
"id": "06880c2f8396469602f8265c44098721fc101b8e",
"size": "631",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/keynote/extractor_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "5353"
},
{
"name": "Shell",
"bytes": "131"
}
],
"symlink_target": ""
} |
@import Foundation;
@import UIKit;
@import CoreGraphics;
/// Class to draw the circle for the points.
@interface BEMCircle : UIView
/// Set to YES if the data point circles should be constantly displayed. NO if they should only appear when relevant.
@property (assign, nonatomic) BOOL shouldDisplayConstantly;
/// The point color
@property (strong, nonatomic) UIColor *Pointcolor;
/// The value of the point
@property (nonatomic) CGFloat absoluteValue;
@end | {
"content_hash": "c1a03017a4e3d5919e4a00b1fce589e9",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 117,
"avg_line_length": 25.72222222222222,
"alnum_prop": 0.7645788336933045,
"repo_name": "Boris-Em/BEMSimpleLineGraph",
"id": "413195d05145919402c4aaaaae4aab5fc9607073",
"size": "672",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "Classes/BEMCircle.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "167289"
}
],
"symlink_target": ""
} |
package be.jabapage.perfectiongame.gae.api;
import java.util.List;
/**
*
* Translating a list to
* @author Jan Verstuyft
*
* @param <A>
* @param <M>
*/
public interface IListTranslator <A, M> extends ITranslator<List<A>, List<M>> {
}
| {
"content_hash": "b9901aba6913cc5e35e358a01527ad00",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 79,
"avg_line_length": 15.5,
"alnum_prop": 0.657258064516129,
"repo_name": "JanVerstuyft/jabapage",
"id": "ce9b6270d3c98eb414de073a95101497390bb88e",
"size": "248",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "perfectiongame/rest-appengine/src/main/java/be/jabapage/perfectiongame/gae/api/IListTranslator.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1542"
},
{
"name": "Dart",
"bytes": "8710043"
},
{
"name": "Java",
"bytes": "252700"
},
{
"name": "JavaScript",
"bytes": "6784"
},
{
"name": "Shell",
"bytes": "290"
}
],
"symlink_target": ""
} |
'use strict';
angular.module('app.directive')
.directive('lineChart', function () {
return {
template: '<div></div>',
scope: {
chart: '='
},
restrict: 'E',
replace: true,
link: function postLink(scope, element) {
var lineChart = new google.visualization.LineChart(element[0]);
function draw(chart) {
var data = chart.data;
var table = new google.visualization.DataTable();
table.addColumn('datetime');
table.addColumn('number');
table.addRows(data.length);
var view = new google.visualization.DataView(table);
for (var i = 0; i < data.length; i++) {
var item = data[i];
table.setCell(i, 0, new Date(item.timestamp));
var value = parseFloat(item.value);
table.setCell(i, 1, value);
}
var last = data[data.length - 1];
var max = new Date(last.timestamp);
var min = new Date(last.timestamp - chart.max * 1000);
var chartOptions = {
legend: 'none',
vAxis: { minValue: 0, maxValue: 100 },
hAxis: { viewWindow: { min: min, max: max }}
};
lineChart.draw(view, chartOptions);
}
scope.$watch('chart', function (chart) {
if (chart && chart.data && chart.max) {
draw(chart);
}
});
}
};
});
| {
"content_hash": "cc45a562b37c66db8cea02c9de44e167",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 71,
"avg_line_length": 27.807692307692307,
"alnum_prop": 0.5089903181189488,
"repo_name": "nickholub/angular-real-time-charts",
"id": "e6ca910a807e4ce6846f52ecf83e6feb8c712109",
"size": "1446",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/scripts/directives/lineChart.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "731"
},
{
"name": "JavaScript",
"bytes": "20069"
}
],
"symlink_target": ""
} |
package com.sasbury.genetik.population;
import java.util.*;
import com.sasbury.genetik.*;
public class InMemoryPopulation implements Population
{
protected ArrayList<Individual> individuals;
/**
* InMemory populations have a dynamic size
* @param size
*/
public InMemoryPopulation()
{
individuals = new ArrayList<Individual>();
}
/**
* Set the storage to null so things can be GC'd.
*/
public void dispose()
{
individuals.clear();
individuals = null;
}
/**
* Throws an exception if the index is out of bounds
*/
public Individual get(int i)
{
return individuals.get(i);
}
public Individual get(String id)
{
Individual retVal = null;
if(null == id) return null;
for(Individual i : individuals)
{
if(id.equals(i.getId()))
{
retVal = i;
break;
}
}
return retVal;
}
public int indexFor(String id)
{
int retVal = -1;
int count = 0;
if(null == id) return retVal;
for(Individual i : individuals)
{
if(id.equals(i.getId()))
{
retVal = count;
break;
}
count++;
}
return retVal;
}
/**
* No op for an in-memory population, always returns true.
*/
public boolean save() throws Exception
{
return true;
}
/**
* If the index is greater than or equal to the size or negative, the the individual is added to the end. InMemory populations cannot be sparse.
*/
public void set(int index, Individual individual)
{
if(index>=0 && index < individuals.size())
{
individual.setIndex(index);
individuals.set(index, individual);
}
else
{
individual.setIndex(individuals.size());
individuals.add(individual);
}
}
public int size()
{
return individuals.size();
}
@Override
public int hashCode()
{
final int PRIME = 31;
int result = 1;
result = PRIME * result + ((individuals == null) ? 0 : individuals.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;
final InMemoryPopulation other = (InMemoryPopulation) obj;
if(individuals == null)
{
if(other.individuals != null)
return false;
}
else if(!Arrays.equals(individuals.toArray(), other.individuals.toArray()))
return false;
return true;
}
}
| {
"content_hash": "fe39bee711cc00e01709cb62a7d71dcf",
"timestamp": "",
"source": "github",
"line_count": 136,
"max_line_length": 148,
"avg_line_length": 21.852941176470587,
"alnum_prop": 0.5080753701211306,
"repo_name": "sasbury/genetik",
"id": "5e8a44cf125c61328e6b4a0f3397b799578b3add",
"size": "2972",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/sasbury/genetik/population/InMemoryPopulation.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "335469"
},
{
"name": "JavaScript",
"bytes": "428007"
},
{
"name": "Shell",
"bytes": "1010"
}
],
"symlink_target": ""
} |
package ch.epfl.yinyang.typetransformers
import scala.reflect.macros.blackbox.Context
import scala.reflect.runtime.universe.definitions.FunctionClass
trait PolyTransformerLike[C <: Context] { this: TypeTransformer[C] =>
import c.universe._
val MaxFunctionArity = 22
def toType(s: Symbol) = s.name
protected def isFunctionType(tp: Type): Boolean = tp.dealias match {
case TypeRef(_, sym, args) if args.nonEmpty =>
val arity = args.length - 1
arity <= MaxFunctionArity &&
arity >= 0 &&
sym.fullName == FunctionClass(arity).fullName
case _ =>
false
}
def constructPolyTree(typeCtx: TypeContext, inType: Type): Tree = inType match {
case TypeRef(pre, sym, Nil) if rewiredToThis(inType.typeSymbol.name.toString) =>
SingletonTypeTree(This(typeNames.EMPTY))
case TypeRef(pre, sym, Nil) =>
Select(This(TypeName(className)), toType(inType.typeSymbol))
case TypeRef(pre, sym, args) if isFunctionType(inType) =>
AppliedTypeTree(Select(Ident(TermName("scala")), toType(sym)),
args map { x => constructPolyTree(typeCtx, x) })
case TypeRef(pre, sym, args) =>
AppliedTypeTree(Select(This(TypeName(className)), toType(sym)),
args map { x => constructPolyTree(typeCtx, x) })
case ConstantType(t) =>
Select(This(TypeName(className)), toType(inType.typeSymbol))
case SingleType(pre, name) if rewiredToThis(inType.typeSymbol.name.toString) =>
SingletonTypeTree(This(typeNames.EMPTY))
case SingleType(pre, name) if inType.typeSymbol.isModuleClass =>
SingletonTypeTree(Select(This(TypeName(className)),
TermName(inType.typeSymbol.name.toString)))
case s @ SingleType(pre, name) if inType.typeSymbol.isClass =>
constructPolyTree(typeCtx,
s.asInstanceOf[scala.reflect.internal.Types#SingleType]
.underlying.asInstanceOf[c.universe.Type])
case annTpe @ AnnotatedType(annotations, underlying) =>
constructPolyTree(typeCtx, underlying)
case another @ _ =>
TypeTree(another)
}
}
class PolyTransformer[C <: Context](ctx: C) extends TypeTransformer[C](ctx) with PolyTransformerLike[C] {
def transform(ctx: TypeContext, t: c.universe.Type): c.universe.Tree =
constructPolyTree(ctx, t)
} | {
"content_hash": "d9dd86c3790e3a70cf1c104f43f3c75e",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 105,
"avg_line_length": 35.546875,
"alnum_prop": 0.6980219780219781,
"repo_name": "amirsh/yin-yang",
"id": "d38766e856b50d6855057b6720bed0f3b340da88",
"size": "2275",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "components/yin-yang/src/typetransformers/PolyTransformer.scala",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Scala",
"bytes": "503754"
},
{
"name": "Shell",
"bytes": "3424"
}
],
"symlink_target": ""
} |
<md-list class="contact-list">
<md-list-item *ngFor="let contact of contacts" (click)="gotoMessage(this.contact.id)">
<span md-list-avatar class="conntect-avatar truck" ngClass="icon-{{contact.type}}"></span>
<h4 md-line><span class="contact-title">{{contact.name}}</span><span class="contact-date">{{contact.updated | date}}</span></h4>
<p class="contact-message" md-line>{{contact.lastMessage}}</p>
</md-list-item>
</md-list> | {
"content_hash": "c5955eb53fbd39e3adf5e1cda074b860",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 136,
"avg_line_length": 65.57142857142857,
"alnum_prop": 0.6557734204793029,
"repo_name": "jo3d3v/pwa-messenger",
"id": "4a8a7c0a87e8706d08b41e74860b803f6c8dfca7",
"size": "459",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/src/app/contact/contact.component.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "19510"
},
{
"name": "HTML",
"bytes": "15733"
},
{
"name": "JavaScript",
"bytes": "19160"
},
{
"name": "TypeScript",
"bytes": "67450"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>V8 API Reference Guide for node.js v0.8.5 - v0.8.7: v8::Debug::Message Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">V8 API Reference Guide for node.js v0.8.5 - v0.8.7
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.9.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="classv8_1_1_debug.html">Debug</a></li><li class="navelem"><a class="el" href="classv8_1_1_debug_1_1_message.html">Message</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="classv8_1_1_debug_1_1_message-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">v8::Debug::Message Class Reference<span class="mlabels"><span class="mlabel">abstract</span></span></div> </div>
</div><!--header-->
<div class="contents">
<p><code>#include <<a class="el" href="v8-debug_8h_source.html">v8-debug.h</a>></code></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:a36ade83a9c960ce581b1a4051f763785"><td class="memItemLeft" align="right" valign="top">virtual bool </td><td class="memItemRight" valign="bottom"><a class="el" href="classv8_1_1_debug_1_1_message.html#a36ade83a9c960ce581b1a4051f763785">IsEvent</a> () const =0</td></tr>
<tr class="separator:a36ade83a9c960ce581b1a4051f763785"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a1d65d6efbb5adb96406f7e285bb25ee3"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a1d65d6efbb5adb96406f7e285bb25ee3"></a>
virtual bool </td><td class="memItemRight" valign="bottom"><b>IsResponse</b> () const =0</td></tr>
<tr class="separator:a1d65d6efbb5adb96406f7e285bb25ee3"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a8a99a5c9fe0db14fbaccaed297d9c203"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a8a99a5c9fe0db14fbaccaed297d9c203"></a>
virtual DebugEvent </td><td class="memItemRight" valign="bottom"><b>GetEvent</b> () const =0</td></tr>
<tr class="separator:a8a99a5c9fe0db14fbaccaed297d9c203"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:af8d236b6a334423732a38cbf8cfd7aef"><td class="memItemLeft" align="right" valign="top">virtual bool </td><td class="memItemRight" valign="bottom"><a class="el" href="classv8_1_1_debug_1_1_message.html#af8d236b6a334423732a38cbf8cfd7aef">WillStartRunning</a> () const =0</td></tr>
<tr class="separator:af8d236b6a334423732a38cbf8cfd7aef"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aa54e11b06d304e8b8f34cc79ee49d869"><td class="memItemLeft" align="right" valign="top">virtual <a class="el" href="classv8_1_1_handle.html">Handle</a>< <a class="el" href="classv8_1_1_object.html">Object</a> > </td><td class="memItemRight" valign="bottom"><a class="el" href="classv8_1_1_debug_1_1_message.html#aa54e11b06d304e8b8f34cc79ee49d869">GetExecutionState</a> () const =0</td></tr>
<tr class="separator:aa54e11b06d304e8b8f34cc79ee49d869"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aa18f6c01d91d176d4e3d0a018890e59a"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aa18f6c01d91d176d4e3d0a018890e59a"></a>
virtual <a class="el" href="classv8_1_1_handle.html">Handle</a>< <a class="el" href="classv8_1_1_object.html">Object</a> > </td><td class="memItemRight" valign="bottom"><b>GetEventData</b> () const =0</td></tr>
<tr class="separator:aa18f6c01d91d176d4e3d0a018890e59a"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a41076f64f82c927cbb2fe5c8325557d5"><td class="memItemLeft" align="right" valign="top">virtual <a class="el" href="classv8_1_1_handle.html">Handle</a>< <a class="el" href="classv8_1_1_string.html">String</a> > </td><td class="memItemRight" valign="bottom"><a class="el" href="classv8_1_1_debug_1_1_message.html#a41076f64f82c927cbb2fe5c8325557d5">GetJSON</a> () const =0</td></tr>
<tr class="separator:a41076f64f82c927cbb2fe5c8325557d5"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a34ff90d879888746a7a0eacebd6aa088"><td class="memItemLeft" align="right" valign="top">virtual <a class="el" href="classv8_1_1_handle.html">Handle</a>< <a class="el" href="classv8_1_1_context.html">Context</a> > </td><td class="memItemRight" valign="bottom"><a class="el" href="classv8_1_1_debug_1_1_message.html#a34ff90d879888746a7a0eacebd6aa088">GetEventContext</a> () const =0</td></tr>
<tr class="separator:a34ff90d879888746a7a0eacebd6aa088"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ab81bb81d233f5f37e6626a7bcac22142"><td class="memItemLeft" align="right" valign="top">virtual <a class="el" href="classv8_1_1_debug_1_1_client_data.html">ClientData</a> * </td><td class="memItemRight" valign="bottom"><a class="el" href="classv8_1_1_debug_1_1_message.html#ab81bb81d233f5f37e6626a7bcac22142">GetClientData</a> () const =0</td></tr>
<tr class="separator:ab81bb81d233f5f37e6626a7bcac22142"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>A message object passed to the debug message handler. </p>
</div><h2 class="groupheader">Member Function Documentation</h2>
<a class="anchor" id="ab81bb81d233f5f37e6626a7bcac22142"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">virtual <a class="el" href="classv8_1_1_debug_1_1_client_data.html">ClientData</a>* v8::Debug::Message::GetClientData </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">pure virtual</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Client data passed with the corresponding request if any. This is the client_data data value passed into Debug::SendCommand along with the request that led to the message or NULL if the message is an event. The debugger takes ownership of the data and will delete it even if there is no message handler. </p>
</div>
</div>
<a class="anchor" id="a34ff90d879888746a7a0eacebd6aa088"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">virtual <a class="el" href="classv8_1_1_handle.html">Handle</a><<a class="el" href="classv8_1_1_context.html">Context</a>> v8::Debug::Message::GetEventContext </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">pure virtual</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Get the context active when the debug event happened. Note this is not the current active context as the JavaScript part of the debugger is running in its own context which is entered at this point. </p>
</div>
</div>
<a class="anchor" id="aa54e11b06d304e8b8f34cc79ee49d869"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">virtual <a class="el" href="classv8_1_1_handle.html">Handle</a><<a class="el" href="classv8_1_1_object.html">Object</a>> v8::Debug::Message::GetExecutionState </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">pure virtual</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Access to execution state and event data. Don't store these cross callbacks as their content becomes invalid. These objects are from the debugger event that started the debug message loop. </p>
</div>
</div>
<a class="anchor" id="a41076f64f82c927cbb2fe5c8325557d5"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">virtual <a class="el" href="classv8_1_1_handle.html">Handle</a><<a class="el" href="classv8_1_1_string.html">String</a>> v8::Debug::Message::GetJSON </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">pure virtual</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Get the debugger protocol JSON. </p>
</div>
</div>
<a class="anchor" id="a36ade83a9c960ce581b1a4051f763785"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">virtual bool v8::Debug::Message::IsEvent </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">pure virtual</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Check type of message. </p>
</div>
</div>
<a class="anchor" id="af8d236b6a334423732a38cbf8cfd7aef"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">virtual bool v8::Debug::Message::WillStartRunning </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">pure virtual</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Indicate whether this is a response to a continue command which will start the VM running after this is processed. </p>
</div>
</div>
<hr/>The documentation for this class was generated from the following file:<ul>
<li>deps/v8/include/<a class="el" href="v8-debug_8h_source.html">v8-debug.h</a></li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Tue Aug 11 2015 23:48:39 for V8 API Reference Guide for node.js v0.8.5 - v0.8.7 by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.9.1
</small></address>
</body>
</html>
| {
"content_hash": "42aa3ab78c078a0e80603bb6d7502002",
"timestamp": "",
"source": "github",
"line_count": 283,
"max_line_length": 418,
"avg_line_length": 50.522968197879855,
"alnum_prop": 0.6652678696321164,
"repo_name": "v8-dox/v8-dox.github.io",
"id": "978bad77b0499673278bf96bbd08ed34560d79e7",
"size": "14298",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "2981f01/html/classv8_1_1_debug_1_1_message.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
define([
'../Core/defined',
'../Core/DeveloperError',
'../Core/loadImage',
'../ThirdParty/when',
'./CubeMap'
], function(
defined,
DeveloperError,
loadImage,
when,
CubeMap) {
'use strict';
/**
* Asynchronously loads six images and creates a cube map. Returns a promise that
* will resolve to a {@link CubeMap} once loaded, or reject if any image fails to load.
*
* @exports loadCubeMap
*
* @param {Context} context The context to use to create the cube map.
* @param {Object} urls The source URL of each image. See the example below.
* @param {Boolean} [allowCrossOrigin=true] Whether to request the image using Cross-Origin
* Resource Sharing (CORS). CORS is only actually used if the image URL is actually cross-origin.
* Data URIs are never requested using CORS.
* @returns {Promise.<CubeMap>} a promise that will resolve to the requested {@link CubeMap} when loaded.
*
* @exception {DeveloperError} context is required.
* @exception {DeveloperError} urls is required and must have positiveX, negativeX, positiveY, negativeY, positiveZ, and negativeZ properties.
*
*
* @example
* Cesium.loadCubeMap(context, {
* positiveX : 'skybox_px.png',
* negativeX : 'skybox_nx.png',
* positiveY : 'skybox_py.png',
* negativeY : 'skybox_ny.png',
* positiveZ : 'skybox_pz.png',
* negativeZ : 'skybox_nz.png'
* }).then(function(cubeMap) {
* // use the cubemap
* }).otherwise(function(error) {
* // an error occurred
* });
*
* @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
* @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
*
* @private
*/
function loadCubeMap(context, urls, allowCrossOrigin) {
//>>includeStart('debug', pragmas.debug);
if (!defined(context)) {
throw new DeveloperError('context is required.');
}
if ((!defined(urls)) ||
(!defined(urls.positiveX)) ||
(!defined(urls.negativeX)) ||
(!defined(urls.positiveY)) ||
(!defined(urls.negativeY)) ||
(!defined(urls.positiveZ)) ||
(!defined(urls.negativeZ))) {
throw new DeveloperError('urls is required and must have positiveX, negativeX, positiveY, negativeY, positiveZ, and negativeZ properties.');
}
//>>includeEnd('debug');
// PERFORMANCE_IDEA: Given the size of some cube maps, we should consider tiling them, which
// would prevent hiccups when uploading, for example, six 4096x4096 textures to the GPU.
//
// Also, it is perhaps acceptable to use the context here in the callbacks, but
// ideally, we would do it in the primitive's update function.
var facePromises = [
loadImage(urls.positiveX, allowCrossOrigin),
loadImage(urls.negativeX, allowCrossOrigin),
loadImage(urls.positiveY, allowCrossOrigin),
loadImage(urls.negativeY, allowCrossOrigin),
loadImage(urls.positiveZ, allowCrossOrigin),
loadImage(urls.negativeZ, allowCrossOrigin)
];
return when.all(facePromises, function(images) {
return new CubeMap({
context : context,
source : {
positiveX : images[0],
negativeX : images[1],
positiveY : images[2],
negativeY : images[3],
positiveZ : images[4],
negativeZ : images[5]
}
});
});
}
return loadCubeMap;
});
| {
"content_hash": "e3014e347d1ad7a5135c6f1f7400f5b4",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 152,
"avg_line_length": 40.09183673469388,
"alnum_prop": 0.5609569865105625,
"repo_name": "LauhLemus10/geojsoncesium",
"id": "d6965900ce3eb2afd34974aa01cb7b6728b92b72",
"size": "3929",
"binary": false,
"copies": "15",
"ref": "refs/heads/master",
"path": "Source/Renderer/loadCubeMap.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "680535"
},
{
"name": "GLSL",
"bytes": "210268"
},
{
"name": "HTML",
"bytes": "1529894"
},
{
"name": "JavaScript",
"bytes": "58381248"
},
{
"name": "Shell",
"bytes": "297"
}
],
"symlink_target": ""
} |
/* $PostgreSQL: pgsql/contrib/ltree/uninstall_ltree.sql,v 1.5 2007/11/13 04:24:28 momjian Exp $ */
-- Adjust this setting to control where the objects get dropped.
SET search_path = public;
DROP OPERATOR CLASS gist__ltree_ops USING gist;
DROP FUNCTION _ltree_same(internal, internal, internal);
DROP FUNCTION _ltree_union(internal, internal);
DROP FUNCTION _ltree_picksplit(internal, internal);
DROP FUNCTION _ltree_penalty(internal,internal,internal);
DROP FUNCTION _ltree_compress(internal);
DROP FUNCTION _ltree_consistent(internal,internal,int2);
DROP OPERATOR ?@ (_ltree, ltxtquery);
DROP FUNCTION _ltxtq_extract_exec(_ltree,ltxtquery);
DROP OPERATOR ?~ (_ltree, lquery);
DROP FUNCTION _ltq_extract_regex(_ltree,lquery);
DROP OPERATOR ?<@ (_ltree, ltree);
DROP FUNCTION _ltree_extract_risparent(_ltree,ltree);
DROP OPERATOR ?@> (_ltree, ltree);
DROP FUNCTION _ltree_extract_isparent(_ltree,ltree);
DROP OPERATOR ^@ (ltxtquery, _ltree);
DROP OPERATOR ^@ (_ltree, ltxtquery);
DROP OPERATOR ^? (_lquery, _ltree);
DROP OPERATOR ^? (_ltree, _lquery);
DROP OPERATOR ^~ (lquery, _ltree);
DROP OPERATOR ^~ (_ltree, lquery);
DROP OPERATOR ^@> (ltree, _ltree);
DROP OPERATOR ^<@ (_ltree, ltree);
DROP OPERATOR ^<@ (ltree, _ltree);
DROP OPERATOR ^@> (_ltree, ltree);
DROP OPERATOR @ (ltxtquery, _ltree);
DROP OPERATOR @ (_ltree, ltxtquery);
DROP OPERATOR ? (_lquery, _ltree);
DROP OPERATOR ? (_ltree, _lquery);
DROP OPERATOR ~ (lquery, _ltree);
DROP OPERATOR ~ (_ltree, lquery);
DROP OPERATOR @> (ltree, _ltree);
DROP OPERATOR <@ (_ltree, ltree);
DROP OPERATOR <@ (ltree, _ltree);
DROP OPERATOR @> (_ltree, ltree);
DROP FUNCTION _ltxtq_rexec(ltxtquery, _ltree);
DROP FUNCTION _ltxtq_exec(_ltree, ltxtquery);
DROP FUNCTION _lt_q_rregex(_lquery,_ltree);
DROP FUNCTION _lt_q_regex(_ltree,_lquery);
DROP FUNCTION _ltq_rregex(lquery,_ltree);
DROP FUNCTION _ltq_regex(_ltree,lquery);
DROP FUNCTION _ltree_r_risparent(ltree,_ltree);
DROP FUNCTION _ltree_risparent(_ltree,ltree);
DROP FUNCTION _ltree_r_isparent(ltree,_ltree);
DROP FUNCTION _ltree_isparent(_ltree,ltree);
DROP OPERATOR CLASS gist_ltree_ops USING gist;
DROP FUNCTION ltree_same(internal, internal, internal);
DROP FUNCTION ltree_union(internal, internal);
DROP FUNCTION ltree_picksplit(internal, internal);
DROP FUNCTION ltree_penalty(internal,internal,internal);
DROP FUNCTION ltree_decompress(internal);
DROP FUNCTION ltree_compress(internal);
DROP FUNCTION ltree_consistent(internal,internal,int2);
DROP TYPE ltree_gist CASCADE;
DROP OPERATOR ^@ (ltxtquery, ltree);
DROP OPERATOR ^@ (ltree, ltxtquery);
DROP OPERATOR @ (ltxtquery, ltree);
DROP OPERATOR @ (ltree, ltxtquery);
DROP FUNCTION ltxtq_rexec(ltxtquery, ltree);
DROP FUNCTION ltxtq_exec(ltree, ltxtquery);
DROP TYPE ltxtquery CASCADE;
DROP OPERATOR ^? (_lquery, ltree);
DROP OPERATOR ^? (ltree, _lquery);
DROP OPERATOR ? (_lquery, ltree);
DROP OPERATOR ? (ltree, _lquery);
DROP FUNCTION lt_q_rregex(_lquery,ltree);
DROP FUNCTION lt_q_regex(ltree,_lquery);
DROP OPERATOR ^~ (lquery, ltree);
DROP OPERATOR ^~ (ltree, lquery);
DROP OPERATOR ~ (lquery, ltree);
DROP OPERATOR ~ (ltree, lquery);
DROP FUNCTION ltq_rregex(lquery,ltree);
DROP FUNCTION ltq_regex(ltree,lquery);
DROP TYPE lquery CASCADE;
DROP OPERATOR CLASS ltree_ops USING btree;
DROP OPERATOR || (text, ltree);
DROP OPERATOR || (ltree, text);
DROP OPERATOR || (ltree, ltree);
DROP OPERATOR ^<@ (ltree, ltree);
DROP OPERATOR <@ (ltree, ltree);
DROP OPERATOR ^@> (ltree, ltree);
DROP OPERATOR @> (ltree, ltree);
DROP FUNCTION ltreeparentsel(internal, oid, internal, integer);
DROP FUNCTION ltree_textadd(text,ltree);
DROP FUNCTION ltree_addtext(ltree,text);
DROP FUNCTION ltree_addltree(ltree,ltree);
DROP FUNCTION ltree_risparent(ltree,ltree);
DROP FUNCTION ltree_isparent(ltree,ltree);
DROP FUNCTION lca(ltree,ltree,ltree,ltree,ltree,ltree,ltree,ltree);
DROP FUNCTION lca(ltree,ltree,ltree,ltree,ltree,ltree,ltree);
DROP FUNCTION lca(ltree,ltree,ltree,ltree,ltree,ltree);
DROP FUNCTION lca(ltree,ltree,ltree,ltree,ltree);
DROP FUNCTION lca(ltree,ltree,ltree,ltree);
DROP FUNCTION lca(ltree,ltree,ltree);
DROP FUNCTION lca(ltree,ltree);
DROP FUNCTION lca(_ltree);
DROP FUNCTION text2ltree(text);
DROP FUNCTION ltree2text(ltree);
DROP FUNCTION nlevel(ltree);
DROP FUNCTION index(ltree,ltree,int4);
DROP FUNCTION index(ltree,ltree);
DROP FUNCTION subpath(ltree,int4);
DROP FUNCTION subpath(ltree,int4,int4);
DROP FUNCTION subltree(ltree,int4,int4);
DROP OPERATOR <> (ltree, ltree);
DROP OPERATOR = (ltree, ltree);
DROP OPERATOR > (ltree, ltree);
DROP OPERATOR >= (ltree, ltree);
DROP OPERATOR <= (ltree, ltree);
DROP OPERATOR < (ltree, ltree);
DROP FUNCTION ltree_ne(ltree,ltree);
DROP FUNCTION ltree_gt(ltree,ltree);
DROP FUNCTION ltree_ge(ltree,ltree);
DROP FUNCTION ltree_eq(ltree,ltree);
DROP FUNCTION ltree_le(ltree,ltree);
DROP FUNCTION ltree_lt(ltree,ltree);
DROP FUNCTION ltree_cmp(ltree,ltree);
DROP TYPE ltree CASCADE;
| {
"content_hash": "9cbbc1edb12a0ca4ae5c6560077165af",
"timestamp": "",
"source": "github",
"line_count": 240,
"max_line_length": 98,
"avg_line_length": 20.9125,
"alnum_prop": 0.7310221159593544,
"repo_name": "ahachete/gpdb",
"id": "4d976839a4a547d8315760d2c41be29ac995f1d0",
"size": "5019",
"binary": false,
"copies": "18",
"ref": "refs/heads/master",
"path": "contrib/ltree/uninstall_ltree.sql",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "5196"
},
{
"name": "Batchfile",
"bytes": "11028"
},
{
"name": "C",
"bytes": "36034528"
},
{
"name": "C++",
"bytes": "4753599"
},
{
"name": "CMake",
"bytes": "32398"
},
{
"name": "CSS",
"bytes": "7068"
},
{
"name": "Csound Score",
"bytes": "179"
},
{
"name": "Cucumber",
"bytes": "912850"
},
{
"name": "DTrace",
"bytes": "1160"
},
{
"name": "FORTRAN",
"bytes": "14777"
},
{
"name": "Groff",
"bytes": "601878"
},
{
"name": "HTML",
"bytes": "218703"
},
{
"name": "Java",
"bytes": "951675"
},
{
"name": "Lex",
"bytes": "208535"
},
{
"name": "M4",
"bytes": "93480"
},
{
"name": "Makefile",
"bytes": "454460"
},
{
"name": "Objective-C",
"bytes": "7388"
},
{
"name": "PLSQL",
"bytes": "174787"
},
{
"name": "PLpgSQL",
"bytes": "48974914"
},
{
"name": "Perl",
"bytes": "759121"
},
{
"name": "Python",
"bytes": "5212042"
},
{
"name": "Ruby",
"bytes": "3283"
},
{
"name": "SQLPL",
"bytes": "146203"
},
{
"name": "Shell",
"bytes": "472600"
},
{
"name": "XS",
"bytes": "8309"
},
{
"name": "XSLT",
"bytes": "5779"
},
{
"name": "Yacc",
"bytes": "481906"
}
],
"symlink_target": ""
} |
#include "SDLFbLocal.h"
NAMESPACE_UPP
#define LLOG(x) //LOG(x)
SDL_Surface *CreateScreen(int w, int h, int bpp, int flags)
{
SDL_Surface * screen = SDL_SetVideoMode(w, h, bpp, flags);
if(!screen)
{
Cout() << Format("Couldn't set display mode: %s\n", SDL_GetError());
return NULL;
}
Cout() << Format("Screen is in %s mode\n", (screen->flags & SDL_FULLSCREEN) ? "fullscreen" : "windowed");
return screen;
}
//cant use these, because SDL_PumpEvents gets called for each SDL_PollEvent, which recalculates KeyStates
//but we need them to remain constant from upp layer POV
#if 0
//GetModState ??
bool GetShift() { uint8* ka = SDL_GetKeyState(NULL); return ka[SDLK_LSHIFT] || ka[SDLK_RSHIFT]; }
bool GetCtrl() { uint8* ka = SDL_GetKeyState(NULL); return ka[SDLK_LCTRL] || ka[SDLK_RCTRL]; }
bool GetAlt() { uint8* ka = SDL_GetKeyState(NULL); return ka[SDLK_LALT] || ka[SDLK_RALT]; }
bool GetCapsLock() { uint8* ka = SDL_GetKeyState(NULL); return ka[SDLK_CAPSLOCK]; }
bool GetMouseLeft() { return (SDL_GetMouseState(NULL,NULL) & SDL_BUTTON(SDL_BUTTON_LEFT)); }
bool GetMouseRight() { return (SDL_GetMouseState(NULL,NULL) & SDL_BUTTON(SDL_BUTTON_RIGHT)); }
bool GetMouseMiddle() { return (SDL_GetMouseState(NULL,NULL) & SDL_BUTTON(SDL_BUTTON_MIDDLE)); }
#else
dword mouseb = 0;
dword modkeys = 0;
enum KM {
KM_NONE = 0x00,
KM_LSHIFT= 0x01,
KM_RSHIFT= 0x02,
KM_LCTRL = 0x04,
KM_RCTRL = 0x08,
KM_LALT = 0x10,
KM_RALT = 0x20,
KM_CAPS = 0x40,
KM_NUM = 0x80,
KM_CTRL = KM_LCTRL | KM_RCTRL,
KM_SHIFT = KM_LSHIFT | KM_RSHIFT,
KM_ALT = KM_LALT | KM_RALT,
};
bool GetMouseLeft() { return mouseb & (1<<0); }
bool GetMouseRight() { return mouseb & (1<<1); }
bool GetMouseMiddle() { return mouseb & (1<<2); }
bool GetShift() { return modkeys & KM_SHIFT; }
bool GetCtrl() { return modkeys & KM_CTRL; }
bool GetAlt() { return modkeys & KM_ALT; }
bool GetCapsLock() { return modkeys & KM_CAPS; }
#endif
dword fbKEYtoK(dword chr) {
if(chr == SDLK_TAB)
chr = K_TAB;
else
if(chr == SDLK_SPACE)
chr = K_SPACE;
else
if(chr == SDLK_RETURN)
chr = K_RETURN;
else
chr = chr + K_DELTA;
if(chr == K_ALT_KEY || chr == K_CTRL_KEY || chr == K_SHIFT_KEY)
return chr;
if(GetCtrl()) chr |= K_CTRL;
if(GetAlt()) chr |= K_ALT;
if(GetShift()) chr |= K_SHIFT;
return chr;
}
dword lastbdowntime[8] = {0};
dword isdblclick[8] = {0};
void HandleSDLEvent(SDL_Event* event)
{
switch(event->type) {
case SDL_ACTIVEEVENT: //SDL_ActiveEvent
break;
case SDL_KEYDOWN:
case SDL_KEYUP: //SDL_KeyboardEvent
{
// bool b = false;
dword keycode = 0;
if(event->type == SDL_KEYDOWN) {
switch(event->key.keysym.sym)
{
case SDLK_LSHIFT: modkeys |= KM_LSHIFT; break;
case SDLK_RSHIFT: modkeys |= KM_RSHIFT; break;
case SDLK_LCTRL: modkeys |= KM_LCTRL; break;
case SDLK_RCTRL: modkeys |= KM_RCTRL; break;
case SDLK_LALT: modkeys |= KM_LALT; break;
case SDLK_RALT: modkeys |= KM_RALT; break;
default:;
}
keycode = fbKEYtoK((dword)event->key.keysym.sym);
if(keycode != K_SPACE) //dont send space on keydown
/*b = */Ctrl::DoKeyFB(keycode, 1);
//send respective keyup things as char events as well
keycode = (dword)event->key.keysym.unicode;
if((keycode != 127 && keycode >= 32 && keycode < 255))
/*b = */Ctrl::DoKeyFB(keycode, 1);
}
else
if(event->type == SDL_KEYUP)
{
switch(event->key.keysym.sym)
{
case SDLK_LSHIFT: modkeys &= ~KM_LSHIFT; break;
case SDLK_RSHIFT: modkeys &= ~KM_RSHIFT; break;
case SDLK_LCTRL: modkeys &= ~KM_LCTRL; break;
case SDLK_RCTRL: modkeys &= ~KM_RCTRL; break;
case SDLK_LALT: modkeys &= ~KM_LALT; break;
case SDLK_RALT: modkeys &= ~KM_RALT; break;
default:;
}
keycode = fbKEYtoK((dword)event->key.keysym.sym) | K_KEYUP;
/*b = */Ctrl::DoKeyFB(keycode, 1);
}
}
break;
case SDL_MOUSEMOTION: //SDL_MouseMotionEvent
Ctrl::DoMouseFB(Ctrl::MOUSEMOVE, Point(event->motion.x, event->motion.y));
break;
case SDL_MOUSEBUTTONDOWN: //SDL_MouseButtonEvent, FIXME DoubleClick
{
Point p(event->button.x, event->button.y);
int bi = event->button.button;
dword ct = SDL_GetTicks();
if(isdblclick[bi] && (abs(int(ct) - int(lastbdowntime[bi])) < 400))
{
switch(bi)
{
case SDL_BUTTON_LEFT: Ctrl::DoMouseFB(Ctrl::LEFTDOUBLE, p); break;
case SDL_BUTTON_RIGHT: Ctrl::DoMouseFB(Ctrl::RIGHTDOUBLE, p); break;
case SDL_BUTTON_MIDDLE: Ctrl::DoMouseFB(Ctrl::MIDDLEDOUBLE, p); break;
//case SDL_BUTTON_WHEELUP: Ctrl::DoMouseFB(Ctrl::MOUSEWHEELDOUBLE, p, +120); break;
//case SDL_BUTTON_WHEELDOWN: Ctrl::DoMouseFB(Ctrl::MOUSEWHEELDOUBLE, p, -120); break;
}
isdblclick[bi] = 0; //reset, to go ahead sending repeats
}
else
{
lastbdowntime[bi] = ct;
isdblclick[bi] = 0; //prepare for repeat
switch(bi)
{
case SDL_BUTTON_LEFT: mouseb |= (1<<0); Ctrl::DoMouseFB(Ctrl::LEFTDOWN, p); break;
case SDL_BUTTON_RIGHT: mouseb |= (1<<1); Ctrl::DoMouseFB(Ctrl::RIGHTDOWN, p); break;
case SDL_BUTTON_MIDDLE: mouseb |= (1<<2); Ctrl::DoMouseFB(Ctrl::MIDDLEDOWN, p); break;
case SDL_BUTTON_WHEELUP: Ctrl::DoMouseFB(Ctrl::MOUSEWHEEL, p, +120); break;
case SDL_BUTTON_WHEELDOWN: Ctrl::DoMouseFB(Ctrl::MOUSEWHEEL, p, -120); break;
}
}
}
break;
case SDL_MOUSEBUTTONUP:
{
int bi = event->button.button;
isdblclick[bi] = 1; //indicate maybe a dblclick
Point p(event->button.x, event->button.y);
switch(bi)
{
case SDL_BUTTON_LEFT: mouseb &= ~(1<<0); Ctrl::DoMouseFB(Ctrl::LEFTUP, p); break;
case SDL_BUTTON_RIGHT: mouseb &= ~(1<<1); Ctrl::DoMouseFB(Ctrl::RIGHTUP, p); break;
case SDL_BUTTON_MIDDLE: mouseb &= ~(1<<2); Ctrl::DoMouseFB(Ctrl::MIDDLEUP, p); break;
case SDL_BUTTON_WHEELUP: Ctrl::DoMouseFB(Ctrl::MOUSEWHEEL, p, +120); break;
case SDL_BUTTON_WHEELDOWN: Ctrl::DoMouseFB(Ctrl::MOUSEWHEEL, p, -120); break;
}
}
break;
case SDL_JOYAXISMOTION: //SDL_JoyAxisEvent
break;
case SDL_JOYBALLMOTION: //SDL_JoyBallEvent
break;
case SDL_JOYHATMOTION: //SDL_JoyHatEvent
break;
case SDL_JOYBUTTONDOWN:
case SDL_JOYBUTTONUP: //SDL_JoyButtonEvent
break;
case SDL_VIDEORESIZE: //SDL_ResizeEvent
{
width = event->resize.w;
height = event->resize.h;
SDL_FreeSurface(screen);
screen = CreateScreen(width, height, bpp, videoflags);
ASSERT(screen);
Ctrl::SetFramebufferSize(Size(width, height));
}
break;
case SDL_VIDEOEXPOSE: //SDL_ExposeEvent
break;
case SDL_QUIT: //SDL_QuitEvent
Ctrl::EndSession();
break;
case SDL_USEREVENT: //SDL_UserEvent
HandleUserEvent(event);
break;
case SDL_SYSWMEVENT: //SDL_SysWMEvent
break;
default:
break;
} // End switch
}
void HandleUserEvent(SDL_Event* event)
{
/*
switch (event->user.code) {
case RUN_GAME_LOOP:
GameLoop();
break;
default:
break;
}
*/
}
END_UPP_NAMESPACE
| {
"content_hash": "2e8517021add74fbcdd43cbd4592e1da",
"timestamp": "",
"source": "github",
"line_count": 235,
"max_line_length": 106,
"avg_line_length": 30.7531914893617,
"alnum_prop": 0.6192057561920575,
"repo_name": "dreamsxin/ultimatepp",
"id": "69fa806d9d9071caa138f9e60226b7449313e3e5",
"size": "7227",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rainbow/SDLFb/Proc.cpp",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Assembly",
"bytes": "8477"
},
{
"name": "C",
"bytes": "47921993"
},
{
"name": "C++",
"bytes": "28354499"
},
{
"name": "CSS",
"bytes": "659"
},
{
"name": "JavaScript",
"bytes": "7006"
},
{
"name": "Objective-C",
"bytes": "178854"
},
{
"name": "Perl",
"bytes": "65041"
},
{
"name": "Python",
"bytes": "38142"
},
{
"name": "Shell",
"bytes": "91097"
},
{
"name": "Smalltalk",
"bytes": "101"
},
{
"name": "Turing",
"bytes": "661569"
}
],
"symlink_target": ""
} |
#ifndef ALIA:ALYSISTASKEMCALJETENERGYFLOW_H
#define ALIANALYSISTASKEMCALJETENERGYFLOW_H
/**
* \file AliAnalysisTaskEmcalJetEnergyFlow.h
* \brief Declaration of class AliAnalysisTaskEmcalJetEnergyFlow
*
* In this header file the class AliAnalysisTaskEmcalJetEnergyFlow is declared
* This is an analysis task which calculates the energy flow between jets of increasing jet radii, defined as the difference of pt in matched jets.
* The goal of this task is to define an observable for the effect of the recoil of medium particles from the jet equivalent to the feature modeled to Jewel generator.
*
* \author Christos Pliatskas <c.pliatskas.stylianidis@nikhef.nl>, Nikhef
* \date Mar 04, 2021
*/
/* Copyright(c) 1998-2020, ALICE Experiment at CERN, All rights reserved.*
* See cxx source for full copyright notice */
#include "AliAnalysisTaskEmcalJet.h"
#include "THistManager.h"
/**
* \class AliAnalysisTaskEmcalJetEFRecoilpp
* \brief Implementation of analysis task which calculates the energy flow between jets of increasing
* jet radii. It derives from AliAnalysisTaskEmcalJet.
* After performing a geometrical matching for the jets of the different radii, it calculates the pt
* difference between subsequent pairs of them. Additionally some basic analysis on track and jet
* spectra is performed.
*/
class AliAnalysisTaskEmcalJetEnergyFlow: public AliAnalysisTaskEmcalJet {
public:
AliAnalysisTaskEmcalJetEnergyFlow() ;
AliAnalysisTaskEmcalJetEnergyFlow(const char* name) ;
virtual ~AliAnalysisTaskEmcalJetEnergyFlow() ;
void UserCreateOutputObjects() ;
void Terminate(Option_t* option) ;
static AliAnalysisTaskEmcalJetEnergyFlow* AddTaskEmcalJetEnergyFlow(
const char *ntracks = "usedefault",
const char *nclusters = "usedefault",
const char *ncells = "usedefault",
const char *suffix = "");
protected:
void JetMatcher(const TList *genJetsList,const Int_t &kGenJets,
const TList *recJetsList,const Int_t &kRecJets,
TArrayI &iGenIndex,TArrayI &iRecIndex,
Int_t iDebug = 0,Float_t maxDist = 0.3,Float_t max_eta = 0.5); ///< This is a re-implementation of the AliAnalysisHelperJetTasks::GetClosestJets adjusted for AliEmcalJet instead of AliAODjets for the function's inputs.
void ExecOnce() ;
Bool_t FillHistograms() ;
Bool_t Run() ;
void AllocateJetHistograms() ;
void AllocateTrackHistograms() ; ///<Same as Sample task
void AllocateClusterHistograms() ; ///<May remove later
void AllocateCellHistograms() ; ///<May remove later
void AllocateEnergyflowHistograms() ;
void DoJetLoop() ;
void DoTrackLoop() ;
void FillEFHistograms() ;
void DoClusterLoop() ; ///<May remove later
void DoCellLoop() ; ///<May remove later
THistManager fHistManager ;///< Histogram manager
// TList* fOutput ;///!<! Output list
private:
AliAnalysisTaskEmcalJetEnergyFlow(const AliAnalysisTaskEmcalJetEnergyFlow&); // not implemented
AliAnalysisTaskEmcalJetEnergyFlow &operator=(const AliAnalysisTaskEmcalJetEnergyFlow&); // not implemented
/// \cond CLASSIMP
ClassDef(AliAnalysisTaskEmcalJetEnergyFlow, 7);
/// \endcond
};
#endif
| {
"content_hash": "aa8c958749f2622801b8810449cf6359",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 229,
"avg_line_length": 44,
"alnum_prop": 0.6887226697353279,
"repo_name": "hzanoli/AliPhysics",
"id": "99c2975caf14f0f46c8ed6f93b7133f15aa967e6",
"size": "3476",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "PWGJE/EMCALJetTasks/UserTasks/AliAnalysisTaskEmcalJetEnergyFlow.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "78557034"
},
{
"name": "C++",
"bytes": "147396251"
},
{
"name": "CMake",
"bytes": "634010"
},
{
"name": "CSS",
"bytes": "5189"
},
{
"name": "Fortran",
"bytes": "134275"
},
{
"name": "HTML",
"bytes": "34924"
},
{
"name": "JavaScript",
"bytes": "3536"
},
{
"name": "Makefile",
"bytes": "24994"
},
{
"name": "Objective-C",
"bytes": "178817"
},
{
"name": "Perl",
"bytes": "18619"
},
{
"name": "Python",
"bytes": "773268"
},
{
"name": "Shell",
"bytes": "1020909"
},
{
"name": "TeX",
"bytes": "392122"
}
],
"symlink_target": ""
} |
"""
Application related tasks for Invoke.
"""
from invoke import Collection
from . import dependencies, env, db, run
from config import BaseConfig
namespace = Collection(
dependencies,
env,
db,
run,
)
namespace.configure({
'app': {
'static_root': BaseConfig.STATIC_ROOT,
}
})
| {
"content_hash": "b1002c64e762b32948641f3c91ac8015",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 46,
"avg_line_length": 14.227272727272727,
"alnum_prop": 0.6517571884984026,
"repo_name": "ssls/beetle-agent",
"id": "4ada6f6932b976f1086fde99b2633304ce520d24",
"size": "331",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tasks/app/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "14909"
},
{
"name": "Mako",
"bytes": "1637"
},
{
"name": "Python",
"bytes": "234058"
}
],
"symlink_target": ""
} |
package com.simpligility.maven.plugins.android.configuration;
import static org.junit.Assert.assertArrayEquals;
import org.apache.maven.plugin.MojoExecutionException;
import org.junit.Test;
import com.simpligility.maven.plugins.android.configuration.SimpleVersionElementParser;
/**
* @author Wang Xuerui - idontknw.wang@gmail.com
*/
public class SimpleVersionElementParserTest
{
@Test
public void simple() throws MojoExecutionException
{
assertArrayEquals( new int[] { 2, 14, 748, 3647 }, new SimpleVersionElementParser().parseVersionElements( "2.14.748.3647" ) );
assertArrayEquals( new int[] { 2147, 483, 64, 7 }, new SimpleVersionElementParser().parseVersionElements( "2147.483.64.7" ) );
assertArrayEquals( new int[] { 2, 1, 4, 7, 4, 8, 3, 6, 4, 7 }, new SimpleVersionElementParser().parseVersionElements( "2.1.4.7.4.8.3.6.4.7" ) );
}
@Test
public void mixed() throws MojoExecutionException
{
assertArrayEquals( new int[] { 4, 1, 16, 8, 1946 }, new SimpleVersionElementParser().parseVersionElements( "4.1.16.8-SNAPSHOT.1946" ) );
assertArrayEquals( new int[] { 1, 2, 15, 8, 1946 }, new SimpleVersionElementParser().parseVersionElements( "1.2.15.8-SNAPSHOT.1946" ) );
assertArrayEquals( new int[] { 2, 1, 6, 1246 }, new SimpleVersionElementParser().parseVersionElements( "2.1.6-SNAPSHOT.1246" ) );
}
}
| {
"content_hash": "3b965c3a08375637db1484e628bae1e5",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 152,
"avg_line_length": 44.96774193548387,
"alnum_prop": 0.703012912482066,
"repo_name": "simpligility/android-maven-plugin",
"id": "a7f9b55cc7cee0e8bbd5796a94b24d8627afe3d4",
"size": "1394",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/com/simpligility/maven/plugins/android/configuration/SimpleVersionElementParserTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AIDL",
"bytes": "3480"
},
{
"name": "Java",
"bytes": "3111833"
}
],
"symlink_target": ""
} |
package scrambleplugin;
import org.newdawn.slick.SlickException;
import com.valarion.gameengine.events.menu.OptionsMenu;
import com.valarion.gameengine.events.menu.ingamemenu.MenuExit;
import com.valarion.gameengine.events.rpgmaker.FlowEventInterface;
import com.valarion.gameengine.gamestates.SubState;
/**
* Ingame menu.
* @author Rubén Tomás Gracia
*
*/
public class PauseMenu extends OptionsMenu {
public PauseMenu(SubState instance) throws SlickException {
super(true, instance, OptionsMenu.XPosition.right,
OptionsMenu.YPosition.top, new FlowEventInterface[] {
new MenuExit() });
loadEvent(null,instance);
}
} | {
"content_hash": "9e8711de615384b2be0660f54dae19c0",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 66,
"avg_line_length": 27.666666666666668,
"alnum_prop": 0.7560240963855421,
"repo_name": "valarion/JAGE",
"id": "83ebee6e977663f0f3455687120f255f90ed1043",
"size": "1995",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "JAGEgradle/JAGEscrambleplugin/src/main/java/scrambleplugin/PauseMenu.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "51"
},
{
"name": "Java",
"bytes": "659892"
}
],
"symlink_target": ""
} |
<html>
<head>
<title>User agent detail - Alcatel_A205G-B/1.0 ObigoInternetBrowser/Q05A[TF014404009534395004115512532586563]</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="section">
<h1 class="header center orange-text">User agent detail</h1>
<div class="row center">
<h5 class="header light">
Alcatel_A205G-B/1.0 ObigoInternetBrowser/Q05A[TF014404009534395004115512532586563]
</h5>
</div>
</div>
<div class="section">
<table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th colspan="2"></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Parse time</th><th>Actions</th></tr><tr><th colspan="14" class="green lighten-3">Source result (test suite)</th></tr><tr><td>whichbrowser/parser<br /><small>/tests/data/mobile/header-wap.yaml</small></td><td>Obigo Q 5A</td><td> </td><td> </td><td style="border-left: 1px solid #555">Alcatel</td><td>A205G-B</td><td>mobile:feature</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td></td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-test">Detail</a>
<!-- Modal Structure -->
<div id="modal-test" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>Testsuite result detail</h4>
<p><pre><code class="php">Array
(
[headers] => Array
(
[User-Agent] => Alcatel_A205G-B/1.0 ObigoInternetBrowser/Q05A[TF014404009534395004115512532586563]
[X-Wap-Profile] => http://www-ccpp.tcl-ta.com/files/Alcatel_A205G-B.rdf
)
[result] => Array
(
[browser] => Array
(
[name] => Obigo Q
[version] => Array
(
[value] => 5
[alias] => 5A
)
[type] => browser
)
[device] => Array
(
[type] => mobile
[subtype] => feature
[manufacturer] => Alcatel
[model] => A205G-B
)
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><th colspan="14" class="green lighten-3">Providers</th></tr><tr><td>BrowscapPhp<br /><small>6012</small></td>
<td colspan="12" class="center-align red lighten-1">
<strong>No result found</strong>
</td>
</tr><tr><td>DonatjUAParser<br /><small>v0.5.0</small></td><td>Alcatel </td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-f1436016-fdf1-4aea-b4be-1d7c99ab0661">Detail</a>
<!-- Modal Structure -->
<div id="modal-f1436016-fdf1-4aea-b4be-1d7c99ab0661" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>DonatjUAParser result detail</h4>
<p><pre><code class="php">Array
(
[platform] =>
[browser] => Alcatel
[version] =>
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>NeutrinoApiCom<br /><small></small></td><td>Obigo </td><td><i class="material-icons">close</i></td><td>JVM </td><td style="border-left: 1px solid #555"></td><td></td><td>mobile-browser</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.18402</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-9b0fa449-ec1b-40c8-8b1c-9486eb3b9cbc">Detail</a>
<!-- Modal Structure -->
<div id="modal-9b0fa449-ec1b-40c8-8b1c-9486eb3b9cbc" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>NeutrinoApiCom result detail</h4>
<p><pre><code class="php">stdClass Object
(
[mobile_screen_height] => 92
[is_mobile] => 1
[type] => mobile-browser
[mobile_brand] =>
[mobile_model] =>
[version] =>
[is_android] =>
[browser_name] => Obigo
[operating_system_family] => JVM
[operating_system_version] =>
[is_ios] =>
[producer] => Obigo Ltd
[operating_system] => JVM (Platform Micro Edition)
[mobile_screen_width] => 128
[mobile_browser] =>
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>PiwikDeviceDetector<br /><small>3.5.2</small></td><td>Obigo Q05A</td><td> </td><td> </td><td style="border-left: 1px solid #555">Alcatel</td><td>A205G-B</td><td>smartphone</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.008</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-21638055-738d-46ba-a1b1-f5114bc26475">Detail</a>
<!-- Modal Structure -->
<div id="modal-21638055-738d-46ba-a1b1-f5114bc26475" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>PiwikDeviceDetector result detail</h4>
<p><pre><code class="php">Array
(
[client] => Array
(
[type] => browser
[name] => Obigo
[short_name] => OB
[version] => Q05A
[engine] =>
)
[operatingSystem] => Array
(
)
[device] => Array
(
[brand] => AL
[brandName] => Alcatel
[model] => A205G-B
[device] => 1
[deviceName] => smartphone
)
[bot] =>
[extra] => Array
(
[isBot] =>
[isBrowser] => 1
[isFeedReader] =>
[isMobileApp] =>
[isPIM] =>
[isLibrary] =>
[isMediaPlayer] =>
[isCamera] =>
[isCarBrowser] =>
[isConsole] =>
[isFeaturePhone] =>
[isPhablet] =>
[isPortableMediaPlayer] =>
[isSmartDisplay] =>
[isSmartphone] => 1
[isTablet] =>
[isTV] =>
[isDesktop] =>
[isMobile] => 1
[isTouchEnabled] =>
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>SinergiBrowserDetector<br /><small>6.0.0</small></td>
<td colspan="12" class="center-align red lighten-1">
<strong>No result found</strong>
</td>
</tr><tr><td>UAParser<br /><small>v3.4.5</small></td><td>Obigo </td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.007</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-346c1a98-5fd3-454f-b6c8-350f2f505d8b">Detail</a>
<!-- Modal Structure -->
<div id="modal-346c1a98-5fd3-454f-b6c8-350f2f505d8b" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>UAParser result detail</h4>
<p><pre><code class="php">UAParser\Result\Client Object
(
[ua] => UAParser\Result\UserAgent Object
(
[major] =>
[minor] =>
[patch] =>
[family] => Obigo
)
[os] => UAParser\Result\OperatingSystem Object
(
[major] =>
[minor] =>
[patch] =>
[patchMinor] =>
[family] => Other
)
[device] => UAParser\Result\Device Object
(
[brand] => Generic
[model] => Feature Phone
[family] => Generic Feature Phone
)
[originalUserAgent] => Alcatel_A205G-B/1.0 ObigoInternetBrowser/Q05A[TF014404009534395004115512532586563]
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>UserAgentStringCom<br /><small></small></td>
<td colspan="12" class="center-align red lighten-1">
<strong>No result found</strong>
</td>
</tr><tr><td>WhatIsMyBrowserCom<br /><small></small></td><td>Obigo Browser </td><td> </td><td> </td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.40104</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-9795f66f-7271-430e-973a-a5c0e14dc35a">Detail</a>
<!-- Modal Structure -->
<div id="modal-9795f66f-7271-430e-973a-a5c0e14dc35a" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>WhatIsMyBrowserCom result detail</h4>
<p><pre><code class="php">stdClass Object
(
[operating_system_name] =>
[simple_sub_description_string] =>
[simple_browser_string] => Obigo Browser
[browser_version] =>
[extra_info] => Array
(
)
[operating_platform] =>
[extra_info_table] => Array
(
)
[layout_engine_name] =>
[detected_addons] => Array
(
)
[operating_system_flavour_code] =>
[hardware_architecture] =>
[operating_system_flavour] =>
[operating_system_frameworks] => Array
(
)
[browser_name_code] => obigo-browser
[operating_system_version] =>
[simple_operating_platform_string] =>
[is_abusive] =>
[layout_engine_version] =>
[browser_capabilities] => Array
(
)
[operating_platform_vendor_name] =>
[operating_system] =>
[operating_system_version_full] =>
[operating_platform_code] =>
[browser_name] => Obigo Browser
[operating_system_name_code] =>
[user_agent] => Alcatel_A205G-B/1.0 ObigoInternetBrowser/Q05A[TF014404009534395004115512532586563]
[browser_version_full] =>
[browser] => Obigo Browser
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>WhichBrowser<br /><small>2.0.10</small></td><td>Obigo Q 5A</td><td> </td><td> </td><td style="border-left: 1px solid #555">Alcatel</td><td>A205G-B</td><td>mobile:feature</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.021</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-342c8d32-4765-40a8-8a5c-af3a38d19ae4">Detail</a>
<!-- Modal Structure -->
<div id="modal-342c8d32-4765-40a8-8a5c-af3a38d19ae4" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>WhichBrowser result detail</h4>
<p><pre><code class="php">Array
(
[browser] => Array
(
[name] => Obigo Q
[version] => Array
(
[value] => 5
[alias] => 5A
)
[type] => browser
)
[device] => Array
(
[type] => mobile
[subtype] => feature
[manufacturer] => Alcatel
[model] => A205G-B
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>Woothee<br /><small>v1.2.0</small></td>
<td colspan="12" class="center-align red lighten-1">
<strong>No result found</strong>
</td>
</tr><tr><td>Wurfl<br /><small>1.6.4</small></td><td>Teleca Obigo Q05A</td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555"></td><td></td><td>Feature Phone</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.012</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-1a1aee36-7ce7-4111-a391-8e2c501f1532">Detail</a>
<!-- Modal Structure -->
<div id="modal-1a1aee36-7ce7-4111-a391-8e2c501f1532" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>Wurfl result detail</h4>
<p><pre><code class="php">Array
(
[virtual] => Array
(
[is_android] => false
[is_ios] => false
[is_windows_phone] => false
[is_app] => false
[is_full_desktop] => false
[is_largescreen] => false
[is_mobile] => true
[is_robot] => false
[is_smartphone] => false
[is_touchscreen] => false
[is_wml_preferred] => false
[is_xhtmlmp_preferred] => true
[is_html_preferred] => false
[advertised_device_os] =>
[advertised_device_os_version] =>
[advertised_browser] => Teleca Obigo
[advertised_browser_version] => Q05A
[complete_device_name] =>
[form_factor] => Feature Phone
[is_phone] => true
[is_app_webview] => false
)
[all] => Array
(
[brand_name] =>
[model_name] =>
[unique] => true
[ununiqueness_handler] =>
[is_wireless_device] => true
[device_claims_web_support] => false
[has_qwerty_keyboard] => false
[can_skip_aligned_link_row] => true
[uaprof] =>
[uaprof2] =>
[uaprof3] =>
[nokia_series] => 0
[nokia_edition] => 0
[device_os] =>
[mobile_browser] =>
[mobile_browser_version] =>
[device_os_version] =>
[pointing_method] =>
[release_date] => 2002_july
[marketing_name] =>
[model_extra_info] =>
[nokia_feature_pack] => 0
[can_assign_phone_number] => true
[is_tablet] => false
[manufacturer_name] =>
[is_bot] => false
[is_google_glass] => false
[proportional_font] => false
[built_in_back_button_support] => false
[card_title_support] => true
[softkey_support] => false
[table_support] => true
[numbered_menus] => false
[menu_with_select_element_recommended] => false
[menu_with_list_of_links_recommended] => true
[icons_on_menu_items_support] => false
[break_list_of_links_with_br_element_recommended] => true
[access_key_support] => false
[wrap_mode_support] => false
[times_square_mode_support] => false
[deck_prefetch_support] => false
[elective_forms_recommended] => true
[wizards_recommended] => false
[image_as_link_support] => false
[insert_br_element_after_widget_recommended] => false
[wml_can_display_images_and_text_on_same_line] => false
[wml_displays_image_in_center] => false
[opwv_wml_extensions_support] => false
[wml_make_phone_call_string] => wtai://wp/mc;
[chtml_display_accesskey] => false
[emoji] => false
[chtml_can_display_images_and_text_on_same_line] => false
[chtml_displays_image_in_center] => false
[imode_region] => none
[chtml_make_phone_call_string] => tel:
[chtml_table_support] => false
[xhtml_honors_bgcolor] => false
[xhtml_supports_forms_in_table] => false
[xhtml_support_wml2_namespace] => false
[xhtml_autoexpand_select] => false
[xhtml_select_as_dropdown] => false
[xhtml_select_as_radiobutton] => false
[xhtml_select_as_popup] => false
[xhtml_display_accesskey] => false
[xhtml_supports_invisible_text] => false
[xhtml_supports_inline_input] => false
[xhtml_supports_monospace_font] => false
[xhtml_supports_table_for_layout] => false
[xhtml_supports_css_cell_table_coloring] => false
[xhtml_format_as_css_property] => false
[xhtml_format_as_attribute] => false
[xhtml_nowrap_mode] => false
[xhtml_marquee_as_css_property] => false
[xhtml_readable_background_color1] => #FFFFFF
[xhtml_readable_background_color2] => #FFFFFF
[xhtml_allows_disabled_form_elements] => false
[xhtml_document_title_support] => true
[xhtml_preferred_charset] => utf8
[opwv_xhtml_extensions_support] => false
[xhtml_make_phone_call_string] => tel:
[xhtmlmp_preferred_mime_type] => application/vnd.wap.xhtml+xml
[xhtml_table_support] => true
[xhtml_send_sms_string] => none
[xhtml_send_mms_string] => none
[xhtml_file_upload] => not_supported
[cookie_support] => true
[accept_third_party_cookie] => true
[xhtml_supports_iframe] => none
[xhtml_avoid_accesskeys] => false
[xhtml_can_embed_video] => none
[ajax_support_javascript] => false
[ajax_manipulate_css] => false
[ajax_support_getelementbyid] => false
[ajax_support_inner_html] => false
[ajax_xhr_type] => none
[ajax_manipulate_dom] => false
[ajax_support_events] => false
[ajax_support_event_listener] => false
[ajax_preferred_geoloc_api] => none
[xhtml_support_level] => 1
[preferred_markup] => html_wi_oma_xhtmlmp_1_0
[wml_1_1] => true
[wml_1_2] => false
[wml_1_3] => false
[html_wi_w3_xhtmlbasic] => true
[html_wi_oma_xhtmlmp_1_0] => true
[html_wi_imode_html_1] => false
[html_wi_imode_html_2] => false
[html_wi_imode_html_3] => false
[html_wi_imode_html_4] => false
[html_wi_imode_html_5] => false
[html_wi_imode_htmlx_1] => false
[html_wi_imode_htmlx_1_1] => false
[html_wi_imode_compact_generic] => false
[html_web_3_2] => false
[html_web_4_0] => false
[voicexml] => false
[multipart_support] => false
[total_cache_disable_support] => false
[time_to_live_support] => false
[resolution_width] => 128
[resolution_height] => 92
[columns] => 11
[max_image_width] => 120
[max_image_height] => 92
[rows] => 6
[physical_screen_width] => 27
[physical_screen_height] => 27
[dual_orientation] => false
[density_class] => 1.0
[wbmp] => true
[bmp] => false
[epoc_bmp] => false
[gif_animated] => true
[jpg] => true
[png] => true
[tiff] => false
[transparent_png_alpha] => false
[transparent_png_index] => false
[svgt_1_1] => false
[svgt_1_1_plus] => false
[greyscale] => false
[gif] => true
[colors] => 256
[webp_lossy_support] => false
[webp_lossless_support] => false
[post_method_support] => true
[basic_authentication_support] => true
[empty_option_value_support] => true
[emptyok] => false
[nokia_voice_call] => false
[wta_voice_call] => false
[wta_phonebook] => false
[wta_misc] => false
[wta_pdc] => false
[https_support] => true
[phone_id_provided] => false
[max_data_rate] => 9
[wifi] => false
[sdio] => false
[vpn] => false
[has_cellular_radio] => true
[max_deck_size] => 10000
[max_url_length_in_requests] => 256
[max_url_length_homepage] => 0
[max_url_length_bookmark] => 0
[max_url_length_cached_page] => 0
[max_no_of_connection_settings] => 0
[max_no_of_bookmarks] => 0
[max_length_of_username] => 0
[max_length_of_password] => 0
[max_object_size] => 0
[downloadfun_support] => false
[directdownload_support] => false
[inline_support] => false
[oma_support] => false
[ringtone] => false
[ringtone_3gpp] => false
[ringtone_midi_monophonic] => false
[ringtone_midi_polyphonic] => false
[ringtone_imelody] => false
[ringtone_digiplug] => false
[ringtone_compactmidi] => false
[ringtone_mmf] => false
[ringtone_rmf] => false
[ringtone_xmf] => false
[ringtone_amr] => false
[ringtone_awb] => false
[ringtone_aac] => false
[ringtone_wav] => false
[ringtone_mp3] => false
[ringtone_spmidi] => false
[ringtone_qcelp] => false
[ringtone_voices] => 1
[ringtone_df_size_limit] => 0
[ringtone_directdownload_size_limit] => 0
[ringtone_inline_size_limit] => 0
[ringtone_oma_size_limit] => 0
[wallpaper] => false
[wallpaper_max_width] => 0
[wallpaper_max_height] => 0
[wallpaper_preferred_width] => 0
[wallpaper_preferred_height] => 0
[wallpaper_resize] => none
[wallpaper_wbmp] => false
[wallpaper_bmp] => false
[wallpaper_gif] => false
[wallpaper_jpg] => false
[wallpaper_png] => false
[wallpaper_tiff] => false
[wallpaper_greyscale] => false
[wallpaper_colors] => 2
[wallpaper_df_size_limit] => 0
[wallpaper_directdownload_size_limit] => 0
[wallpaper_inline_size_limit] => 0
[wallpaper_oma_size_limit] => 0
[screensaver] => false
[screensaver_max_width] => 0
[screensaver_max_height] => 0
[screensaver_preferred_width] => 0
[screensaver_preferred_height] => 0
[screensaver_resize] => none
[screensaver_wbmp] => false
[screensaver_bmp] => false
[screensaver_gif] => false
[screensaver_jpg] => false
[screensaver_png] => false
[screensaver_greyscale] => false
[screensaver_colors] => 2
[screensaver_df_size_limit] => 0
[screensaver_directdownload_size_limit] => 0
[screensaver_inline_size_limit] => 0
[screensaver_oma_size_limit] => 0
[picture] => false
[picture_max_width] => 0
[picture_max_height] => 0
[picture_preferred_width] => 0
[picture_preferred_height] => 0
[picture_resize] => none
[picture_wbmp] => false
[picture_bmp] => false
[picture_gif] => false
[picture_jpg] => false
[picture_png] => false
[picture_greyscale] => false
[picture_colors] => 2
[picture_df_size_limit] => 0
[picture_directdownload_size_limit] => 0
[picture_inline_size_limit] => 0
[picture_oma_size_limit] => 0
[video] => false
[oma_v_1_0_forwardlock] => false
[oma_v_1_0_combined_delivery] => false
[oma_v_1_0_separate_delivery] => false
[streaming_video] => false
[streaming_3gpp] => false
[streaming_mp4] => false
[streaming_mov] => false
[streaming_video_size_limit] => 0
[streaming_real_media] => none
[streaming_flv] => false
[streaming_3g2] => false
[streaming_vcodec_h263_0] => -1
[streaming_vcodec_h263_3] => -1
[streaming_vcodec_mpeg4_sp] => -1
[streaming_vcodec_mpeg4_asp] => -1
[streaming_vcodec_h264_bp] => -1
[streaming_acodec_amr] => none
[streaming_acodec_aac] => none
[streaming_wmv] => none
[streaming_preferred_protocol] => rtsp
[streaming_preferred_http_protocol] => none
[wap_push_support] => false
[connectionless_service_indication] => false
[connectionless_service_load] => false
[connectionless_cache_operation] => false
[connectionoriented_unconfirmed_service_indication] => false
[connectionoriented_unconfirmed_service_load] => false
[connectionoriented_unconfirmed_cache_operation] => false
[connectionoriented_confirmed_service_indication] => false
[connectionoriented_confirmed_service_load] => false
[connectionoriented_confirmed_cache_operation] => false
[utf8_support] => false
[ascii_support] => false
[iso8859_support] => false
[expiration_date] => false
[j2me_cldc_1_0] => false
[j2me_cldc_1_1] => false
[j2me_midp_1_0] => false
[j2me_midp_2_0] => false
[doja_1_0] => false
[doja_1_5] => false
[doja_2_0] => false
[doja_2_1] => false
[doja_2_2] => false
[doja_3_0] => false
[doja_3_5] => false
[doja_4_0] => false
[j2me_jtwi] => false
[j2me_mmapi_1_0] => false
[j2me_mmapi_1_1] => false
[j2me_wmapi_1_0] => false
[j2me_wmapi_1_1] => false
[j2me_wmapi_2_0] => false
[j2me_btapi] => false
[j2me_3dapi] => false
[j2me_locapi] => false
[j2me_nokia_ui] => false
[j2me_motorola_lwt] => false
[j2me_siemens_color_game] => false
[j2me_siemens_extension] => false
[j2me_heap_size] => 0
[j2me_max_jar_size] => 0
[j2me_storage_size] => 0
[j2me_max_record_store_size] => 0
[j2me_screen_width] => 0
[j2me_screen_height] => 0
[j2me_canvas_width] => 0
[j2me_canvas_height] => 0
[j2me_bits_per_pixel] => 0
[j2me_audio_capture_enabled] => false
[j2me_video_capture_enabled] => false
[j2me_photo_capture_enabled] => false
[j2me_capture_image_formats] => none
[j2me_http] => false
[j2me_https] => false
[j2me_socket] => false
[j2me_udp] => false
[j2me_serial] => false
[j2me_gif] => false
[j2me_gif89a] => false
[j2me_jpg] => false
[j2me_png] => false
[j2me_bmp] => false
[j2me_bmp3] => false
[j2me_wbmp] => false
[j2me_midi] => false
[j2me_wav] => false
[j2me_amr] => false
[j2me_mp3] => false
[j2me_mp4] => false
[j2me_imelody] => false
[j2me_rmf] => false
[j2me_au] => false
[j2me_aac] => false
[j2me_realaudio] => false
[j2me_xmf] => false
[j2me_wma] => false
[j2me_3gpp] => false
[j2me_h263] => false
[j2me_svgt] => false
[j2me_mpeg4] => false
[j2me_realvideo] => false
[j2me_real8] => false
[j2me_realmedia] => false
[j2me_left_softkey_code] => 0
[j2me_right_softkey_code] => 0
[j2me_middle_softkey_code] => 0
[j2me_select_key_code] => 0
[j2me_return_key_code] => 0
[j2me_clear_key_code] => 0
[j2me_datefield_no_accepts_null_date] => false
[j2me_datefield_broken] => false
[receiver] => false
[sender] => false
[mms_max_size] => 0
[mms_max_height] => 0
[mms_max_width] => 0
[built_in_recorder] => false
[built_in_camera] => false
[mms_jpeg_baseline] => false
[mms_jpeg_progressive] => false
[mms_gif_static] => false
[mms_gif_animated] => false
[mms_png] => false
[mms_bmp] => false
[mms_wbmp] => false
[mms_amr] => false
[mms_wav] => false
[mms_midi_monophonic] => false
[mms_midi_polyphonic] => false
[mms_midi_polyphonic_voices] => 0
[mms_spmidi] => false
[mms_mmf] => false
[mms_mp3] => false
[mms_evrc] => false
[mms_qcelp] => false
[mms_ota_bitmap] => false
[mms_nokia_wallpaper] => false
[mms_nokia_operatorlogo] => false
[mms_nokia_3dscreensaver] => false
[mms_nokia_ringingtone] => false
[mms_rmf] => false
[mms_xmf] => false
[mms_symbian_install] => false
[mms_jar] => false
[mms_jad] => false
[mms_vcard] => false
[mms_vcalendar] => false
[mms_wml] => false
[mms_wbxml] => false
[mms_wmlc] => false
[mms_video] => false
[mms_mp4] => false
[mms_3gpp] => false
[mms_3gpp2] => false
[mms_max_frame_rate] => 0
[nokiaring] => false
[picturemessage] => false
[operatorlogo] => false
[largeoperatorlogo] => false
[callericon] => false
[nokiavcard] => false
[nokiavcal] => false
[sckl_ringtone] => false
[sckl_operatorlogo] => false
[sckl_groupgraphic] => false
[sckl_vcard] => false
[sckl_vcalendar] => false
[text_imelody] => false
[ems] => false
[ems_variablesizedpictures] => false
[ems_imelody] => false
[ems_odi] => false
[ems_upi] => false
[ems_version] => 0
[siemens_ota] => false
[siemens_logo_width] => 101
[siemens_logo_height] => 29
[siemens_screensaver_width] => 101
[siemens_screensaver_height] => 50
[gprtf] => false
[sagem_v1] => false
[sagem_v2] => false
[panasonic] => false
[sms_enabled] => true
[wav] => false
[mmf] => false
[smf] => false
[mld] => false
[midi_monophonic] => false
[midi_polyphonic] => false
[sp_midi] => false
[rmf] => false
[xmf] => false
[compactmidi] => false
[digiplug] => false
[nokia_ringtone] => false
[imelody] => false
[au] => false
[amr] => false
[awb] => false
[aac] => false
[mp3] => false
[voices] => 1
[qcelp] => false
[evrc] => false
[flash_lite_version] =>
[fl_wallpaper] => false
[fl_screensaver] => false
[fl_standalone] => false
[fl_browser] => false
[fl_sub_lcd] => false
[full_flash_support] => false
[css_supports_width_as_percentage] => true
[css_border_image] => none
[css_rounded_corners] => none
[css_gradient] => none
[css_spriting] => false
[css_gradient_linear] => none
[is_transcoder] => false
[transcoder_ua_header] => user-agent
[rss_support] => false
[pdf_support] => false
[progressive_download] => false
[playback_vcodec_h263_0] => -1
[playback_vcodec_h263_3] => -1
[playback_vcodec_mpeg4_sp] => -1
[playback_vcodec_mpeg4_asp] => -1
[playback_vcodec_h264_bp] => -1
[playback_real_media] => none
[playback_3gpp] => false
[playback_3g2] => false
[playback_mp4] => false
[playback_mov] => false
[playback_acodec_amr] => none
[playback_acodec_aac] => none
[playback_df_size_limit] => 0
[playback_directdownload_size_limit] => 0
[playback_inline_size_limit] => 0
[playback_oma_size_limit] => 0
[playback_acodec_qcelp] => false
[playback_wmv] => none
[hinted_progressive_download] => false
[html_preferred_dtd] => xhtml_mp1
[viewport_supported] => false
[viewport_width] =>
[viewport_userscalable] =>
[viewport_initial_scale] =>
[viewport_maximum_scale] =>
[viewport_minimum_scale] =>
[mobileoptimized] => false
[handheldfriendly] => false
[canvas_support] => none
[image_inlining] => false
[is_smarttv] => false
[is_console] => false
[nfc_support] => false
[ux_full_desktop] => false
[jqm_grade] => none
[is_sencha_touch_ok] => false
[controlcap_is_smartphone] => default
[controlcap_is_ios] => default
[controlcap_is_android] => default
[controlcap_is_robot] => default
[controlcap_is_app] => default
[controlcap_advertised_device_os] => default
[controlcap_advertised_device_os_version] => default
[controlcap_advertised_browser] => default
[controlcap_advertised_browser_version] => default
[controlcap_is_windows_phone] => default
[controlcap_is_full_desktop] => default
[controlcap_is_largescreen] => default
[controlcap_is_mobile] => default
[controlcap_is_touchscreen] => default
[controlcap_is_wml_preferred] => default
[controlcap_is_xhtmlmp_preferred] => default
[controlcap_is_html_preferred] => default
[controlcap_form_factor] => default
[controlcap_complete_device_name] => default
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr></table>
</div>
<div class="section">
<h1 class="header center orange-text">About this comparison</h1>
<div class="row center">
<h5 class="header light">
The primary goal of this project is simple<br />
I wanted to know which user agent parser is the most accurate in each part - device detection, bot detection and so on...<br />
<br />
The secondary goal is to provide a source for all user agent parsers to improve their detection based on this results.<br />
<br />
You can also improve this further, by suggesting ideas at <a href="https://github.com/ThaDafinser/UserAgentParserComparison">ThaDafinser/UserAgentParserComparison</a><br />
<br />
The comparison is based on the abstraction by <a href="https://github.com/ThaDafinser/UserAgentParser">ThaDafinser/UserAgentParser</a>
</h5>
</div>
</div>
<div class="card">
<div class="card-content">
Comparison created <i>2016-02-13 13:28:32</i> | by
<a href="https://github.com/ThaDafinser">ThaDafinser</a>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/list.js/1.1.1/list.min.js"></script>
<script>
$(document).ready(function(){
// the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
$('.modal-trigger').leanModal();
});
</script>
</body>
</html> | {
"content_hash": "8153afa025c08eb036658bf84600e5c9",
"timestamp": "",
"source": "github",
"line_count": 978,
"max_line_length": 760,
"avg_line_length": 39.70858895705521,
"alnum_prop": 0.5122183597270503,
"repo_name": "ThaDafinser/UserAgentParserComparison",
"id": "ab24d2c1bc84530b497e6eb33e0e99079c0fa8c7",
"size": "38836",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "v4/user-agent-detail/2f/46/2f46f96b-cef2-4f96-9847-bb9fb8cbe19c.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2060859160"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.