text stringlengths 2 1.04M | meta dict |
|---|---|
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_C_COMPILER arm-linux-gnueabihf-gcc)
set(CMAKE_CXX_COMPILER arm-linux-gnueabihf-g++)
#Set target environment directory
set(CMAKE_FIND_ROOT_PATH $ENV{INSTALLDIR}/arm-linux-gnueabihf/libc/usr) | {
"content_hash": "4c1faef608a7b3ebf504081a489a85f8",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 72,
"avg_line_length": 33,
"alnum_prop": 0.7922077922077922,
"repo_name": "Deepnekroz/kaa",
"id": "759cf5859d15cc12a06793ecaa39ea3df70bfeb1",
"size": "833",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "client/client-multi/client-cpp/toolchains/rpi.cmake",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "19815"
},
{
"name": "Arduino",
"bytes": "22520"
},
{
"name": "Batchfile",
"bytes": "21336"
},
{
"name": "C",
"bytes": "6226813"
},
{
"name": "C++",
"bytes": "1729698"
},
{
"name": "CMake",
"bytes": "74342"
},
{
"name": "CSS",
"bytes": "23111"
},
{
"name": "HTML",
"bytes": "6338"
},
{
"name": "Java",
"bytes": "10478878"
},
{
"name": "JavaScript",
"bytes": "4669"
},
{
"name": "Makefile",
"bytes": "15221"
},
{
"name": "Objective-C",
"bytes": "305678"
},
{
"name": "Python",
"bytes": "128276"
},
{
"name": "Shell",
"bytes": "185517"
},
{
"name": "Thrift",
"bytes": "21163"
},
{
"name": "XSLT",
"bytes": "4062"
}
],
"symlink_target": ""
} |
@implementation ZKRArticleItem
+ (NSDictionary *)mj_replacedKeyFromPropertyName
{
return @{
@"open_type" : @"special_info.open_type",
@"icon_url" : @"special_info.icon_url",
@"discussionTitle" : @"special_info.discussion.title",
@"discussionApi_url" : @"special_info.discussion.api_url",
};
}
@end
| {
"content_hash": "fe4f0005c26a1d6f64db13026f146b69",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 71,
"avg_line_length": 29.384615384615383,
"alnum_prop": 0.5602094240837696,
"repo_name": "GLChan/rekaz",
"id": "9a0b4cf2342b7ffed373a0b27020c250fd153d90",
"size": "545",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "rekaz/Zaker-C/Zaker-C/Classes/Subscription(订阅)/Model/ZKRArticleItem.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "1140187"
},
{
"name": "Shell",
"bytes": "8303"
}
],
"symlink_target": ""
} |
import React, { Component } from "react";
import TodoItem from "./TodoItem";
class TodoItems extends Component {
constructor(props) {
super(props);
this.state = {items: []};
this.handleCheck = this.handleCheck.bind(this);
this.handleEdit = this.handleEdit.bind(this);
this.handleDelete = this.handleDelete.bind(this);
this.handleAdd = this.handleAdd.bind(this);
this.handleDeleteAll = this.handleDeleteAll.bind(this);
}
handleCheck(index, checked) {
this.setState((prevState, props) => {
prevState.items[index].checked = checked;
return {
items: prevState.items
};
});
}
handleEdit(index, task) {
this.setState((prevState, props) => {
prevState.items[index].task = task;
return {
items: prevState.items
};
});
}
handleDelete(index) {
this.setState((prevState, props) => {
delete prevState.items[index];
return {
items: prevState.items
};
});
}
handleAdd() {
this.setState((prevState, props) => {
prevState.items.push({task: "", checked: false});
return {
items: prevState.items
}
});
}
handleDeleteAll() {
this.props.onDelete(this.props.index);
}
render() {
return (
<div>
{this.state.items.map((item, index) => {
return (
<TodoItem key={index} item={item} index={index} onCheck={this.handleCheck}
onEdit={this.handleEdit} onDelete={this.handleDelete} />
);
})}
<input className="btn btn-primary add-todo-item" type="button" value="Add New Item"
onClick={this.handleAdd} />
<input className="btn btn-danger" type="button" value="Delete TODO"
onClick={this.handleDeleteAll} />
</div>
);
}
}
export default TodoItems; | {
"content_hash": "798739f07ea0acd8d62c0ff7486d4d34",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 91,
"avg_line_length": 25.410958904109588,
"alnum_prop": 0.5865229110512129,
"repo_name": "fredyw/react-todo",
"id": "119e34af73f301a1b5649918e50324903ab3b63c",
"size": "1855",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/TodoItems.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "365"
},
{
"name": "HTML",
"bytes": "1211"
},
{
"name": "JavaScript",
"bytes": "6783"
}
],
"symlink_target": ""
} |
FROM phusion/baseimage:0.9.17
MAINTAINER Nikolay Volosatov <bamx23@gmail.com>
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update && \
apt-get -y install python-software-properties software-properties-common && \
add-apt-repository ppa:yandex-load/main && \
apt-get update && \
apt-get -y install yandex-load-tank-base && \
apt-get -y remove python-software-properties software-properties-common && \
apt-get -y autoremove && \
apt-get clean && \
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
COPY start.sh /
RUN chmod +x start.sh
COPY key.prv /root/.ssh/id_rsa
VOLUME ["/data", "/config"]
ENV TANK_LOAD="load.ini"
CMD ["/sbin/my_init", "--", "/start.sh"]
| {
"content_hash": "932a4cc16fc6a21cc8cb9190572cbfdf",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 81,
"avg_line_length": 27.88,
"alnum_prop": 0.6714490674318508,
"repo_name": "BamX/taggy-api",
"id": "bb271e877d8a871a4bbfb88d23635244a0c71ce1",
"size": "697",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tank/build/Dockerfile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "47458"
},
{
"name": "CSS",
"bytes": "1411"
},
{
"name": "HTML",
"bytes": "2970"
},
{
"name": "Makefile",
"bytes": "1247"
},
{
"name": "Nginx",
"bytes": "1676"
},
{
"name": "Python",
"bytes": "1019"
},
{
"name": "Shell",
"bytes": "605"
}
],
"symlink_target": ""
} |
package configs
import (
"bytes"
"encoding/json"
"os/exec"
)
type Rlimit struct {
Type int `json:"type"`
Hard uint64 `json:"hard"`
Soft uint64 `json:"soft"`
}
// IDMap represents UID/GID Mappings for User Namespaces.
type IDMap struct {
ContainerID int `json:"container_id"`
HostID int `json:"host_id"`
Size int `json:"size"`
}
// Seccomp represents syscall restrictions
// By default, only the native architecture of the kernel is allowed to be used
// for syscalls. Additional architectures can be added by specifying them in
// Architectures.
type Seccomp struct {
DefaultAction Action `json:"default_action"`
Architectures []string `json:"architectures"`
Syscalls []*Syscall `json:"syscalls"`
}
// An action to be taken upon rule match in Seccomp
type Action int
const (
Kill Action = iota + 1
Errno
Trap
Allow
Trace
)
// A comparison operator to be used when matching syscall arguments in Seccomp
type Operator int
const (
EqualTo Operator = iota + 1
NotEqualTo
GreaterThan
GreaterThanOrEqualTo
LessThan
LessThanOrEqualTo
MaskEqualTo
)
// A rule to match a specific syscall argument in Seccomp
type Arg struct {
Index uint `json:"index"`
Value uint64 `json:"value"`
ValueTwo uint64 `json:"value_two"`
Op Operator `json:"op"`
}
// An rule to match a syscall in Seccomp
type Syscall struct {
Name string `json:"name"`
Action Action `json:"action"`
Args []*Arg `json:"args"`
}
// TODO Windows. Many of these fields should be factored out into those parts
// which are common across platforms, and those which are platform specific.
// Config defines configuration options for executing a process inside a contained environment.
type Config struct {
// NoPivotRoot will use MS_MOVE and a chroot to jail the process into the container's rootfs
// This is a common option when the container is running in ramdisk
NoPivotRoot bool `json:"no_pivot_root"`
// ParentDeathSignal specifies the signal that is sent to the container's process in the case
// that the parent process dies.
ParentDeathSignal int `json:"parent_death_signal"`
// PivotDir allows a custom directory inside the container's root filesystem to be used as pivot, when NoPivotRoot is not set.
// When a custom PivotDir not set, a temporary dir inside the root filesystem will be used. The pivot dir needs to be writeable.
// This is required when using read only root filesystems. In these cases, a read/writeable path can be (bind) mounted somewhere inside the root filesystem to act as pivot.
PivotDir string `json:"pivot_dir"`
// Path to a directory containing the container's root filesystem.
Rootfs string `json:"rootfs"`
// Readonlyfs will remount the container's rootfs as readonly where only externally mounted
// bind mounts are writtable.
Readonlyfs bool `json:"readonlyfs"`
// Specifies the mount propagation flags to be applied to /.
RootPropagation int `json:"rootPropagation"`
// Mounts specify additional source and destination paths that will be mounted inside the container's
// rootfs and mount namespace if specified
Mounts []*Mount `json:"mounts"`
// The device nodes that should be automatically created within the container upon container start. Note, make sure that the node is marked as allowed in the cgroup as well!
Devices []*Device `json:"devices"`
MountLabel string `json:"mount_label"`
// Hostname optionally sets the container's hostname if provided
Hostname string `json:"hostname"`
// Namespaces specifies the container's namespaces that it should setup when cloning the init process
// If a namespace is not provided that namespace is shared from the container's parent process
Namespaces Namespaces `json:"namespaces"`
// Capabilities specify the capabilities to keep when executing the process inside the container
// All capbilities not specified will be dropped from the processes capability mask
Capabilities []string `json:"capabilities"`
// Networks specifies the container's network setup to be created
Networks []*Network `json:"networks"`
// Routes can be specified to create entries in the route table as the container is started
Routes []*Route `json:"routes"`
// Cgroups specifies specific cgroup settings for the various subsystems that the container is
// placed into to limit the resources the container has available
Cgroups *Cgroup `json:"cgroups"`
// AppArmorProfile specifies the profile to apply to the process running in the container and is
// change at the time the process is execed
AppArmorProfile string `json:"apparmor_profile"`
// ProcessLabel specifies the label to apply to the process running in the container. It is
// commonly used by selinux
ProcessLabel string `json:"process_label"`
// Rlimits specifies the resource limits, such as max open files, to set in the container
// If Rlimits are not set, the container will inherit rlimits from the parent process
Rlimits []Rlimit `json:"rlimits"`
// OomScoreAdj specifies the adjustment to be made by the kernel when calculating oom scores
// for a process. Valid values are between the range [-1000, '1000'], where processes with
// higher scores are preferred for being killed.
// More information about kernel oom score calculation here: https://lwn.net/Articles/317814/
OomScoreAdj int `json:"oom_score_adj"`
// AdditionalGroups specifies the gids that should be added to supplementary groups
// in addition to those that the user belongs to.
AdditionalGroups []string `json:"additional_groups"`
// UidMappings is an array of User ID mappings for User Namespaces
UidMappings []IDMap `json:"uid_mappings"`
// GidMappings is an array of Group ID mappings for User Namespaces
GidMappings []IDMap `json:"gid_mappings"`
// MaskPaths specifies paths within the container's rootfs to mask over with a bind
// mount pointing to /dev/null as to prevent reads of the file.
MaskPaths []string `json:"mask_paths"`
// ReadonlyPaths specifies paths within the container's rootfs to remount as read-only
// so that these files prevent any writes.
ReadonlyPaths []string `json:"readonly_paths"`
// Sysctl is a map of properties and their values. It is the equivalent of using
// sysctl -w my.property.name value in Linux.
Sysctl map[string]string `json:"sysctl"`
// Seccomp allows actions to be taken whenever a syscall is made within the container.
// A number of rules are given, each having an action to be taken if a syscall matches it.
// A default action to be taken if no rules match is also given.
Seccomp *Seccomp `json:"seccomp"`
// NoNewPrivileges controls whether processes in the container can gain additional privileges.
NoNewPrivileges bool `json:"no_new_privileges"`
// Hooks are a collection of actions to perform at various container lifecycle events.
// Hooks are not able to be marshaled to json but they are also not needed to.
Hooks *Hooks `json:"-"`
// Version is the version of opencontainer specification that is supported.
Version string `json:"version"`
// Labels are user defined metadata that is stored in the config and populated on the state
Labels []string `json:"labels"`
}
type Hooks struct {
// Prestart commands are executed after the container namespaces are created,
// but before the user supplied command is executed from init.
Prestart []Hook
// Poststart commands are executed after the container init process starts.
Poststart []Hook
// Poststop commands are executed after the container init process exits.
Poststop []Hook
}
// HookState is the payload provided to a hook on execution.
type HookState struct {
Version string `json:"version"`
ID string `json:"id"`
Pid int `json:"pid"`
Root string `json:"root"`
}
type Hook interface {
// Run executes the hook with the provided state.
Run(HookState) error
}
// NewFunctionHooks will call the provided function when the hook is run.
func NewFunctionHook(f func(HookState) error) FuncHook {
return FuncHook{
run: f,
}
}
type FuncHook struct {
run func(HookState) error
}
func (f FuncHook) Run(s HookState) error {
return f.run(s)
}
type Command struct {
Path string `json:"path"`
Args []string `json:"args"`
Env []string `json:"env"`
Dir string `json:"dir"`
}
// NewCommandHooks will execute the provided command when the hook is run.
func NewCommandHook(cmd Command) CommandHook {
return CommandHook{
Command: cmd,
}
}
type CommandHook struct {
Command
}
func (c Command) Run(s HookState) error {
b, err := json.Marshal(s)
if err != nil {
return err
}
cmd := exec.Cmd{
Path: c.Path,
Args: c.Args,
Env: c.Env,
Stdin: bytes.NewReader(b),
}
return cmd.Run()
}
| {
"content_hash": "1b2259018b12cfb7eaa3e0e5f492570a",
"timestamp": "",
"source": "github",
"line_count": 258,
"max_line_length": 175,
"avg_line_length": 33.74031007751938,
"alnum_prop": 0.7449741527857553,
"repo_name": "runcom/runc",
"id": "0325d58a8d4c6b73cf87cb32bda78ca16cc71bc1",
"size": "8705",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "libcontainer/configs/config.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "10190"
},
{
"name": "Go",
"bytes": "543942"
},
{
"name": "Makefile",
"bytes": "1325"
},
{
"name": "Protocol Buffer",
"bytes": "3167"
},
{
"name": "Shell",
"bytes": "1736"
}
],
"symlink_target": ""
} |
<div layout="row" flex>
<md-input-container flex="none" style="width: 50px;">
<label>Id</label>
<input ng-model="$ctrl.model.id" type="number" ng-blur="$ctrl.model.ngChange()">
</md-input-container>
<md-input-container flex="25">
<label>Text</label>
<input ng-model="$ctrl.model.text" ng-blur="$ctrl.model.ngChange()">
</md-input-container>
<md-input-container flex>
<label>Description</label>
<input ng-model="$ctrl.model.description" ng-blur="$ctrl.model.ngChange()">
</md-input-container>
</div>
| {
"content_hash": "8190189c800d3f832cc33753e1d10a68",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 88,
"avg_line_length": 40.785714285714285,
"alnum_prop": 0.6182136602451839,
"repo_name": "toddbadams/wine-trivia",
"id": "7956a222bac08237513c913eec8a9a72deda53e7",
"size": "571",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "app/features/questions/selectionEditor.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "32801"
},
{
"name": "JavaScript",
"bytes": "84681"
}
],
"symlink_target": ""
} |
#include "CCBundle.h"
using namespace std;
#define CCBUNDLE_SHORT 1
#define CCBUNDLE_UNSIGNEDSHORT 2
#define CCBUNDLE_INT 3
#define CCBUNDLE_UNSIGNEDINT 4
#define CCBUNDLE_FLOAT 5
#define CCBUNDLE_DOUBLE 6
#define CCBUNDLE_STRING 7
#define CCBUNDLE_BUNDLE 8
#define CCBUNDLE_OBJECT 9
#define CCBUNDLE_PARAM 10
#define MAP_DATAS std::map<std::string, _ccBUNDLEVALUE>
NS_CC_BEGIN
CCBundle::CCBundle()
{
}
CCBundle::~CCBundle()
{
MAP_DATAS::iterator iter = m_mDatas.begin();
for(; iter != m_mDatas.end(); ++iter)
{
removeValue(iter->second);
}
m_mDatas.clear();
}
CCBundle* CCBundle::create()
{
CCBundle* pRet = new CCBundle();
if( pRet )
{
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
CCObject* CCBundle::copyWithZone(CCZone* pZone)
{
CCZone *pNewZone = NULL;
CCBundle *pRet = NULL;
if( pZone && pZone->m_pCopyObject )
{
pRet = (CCBundle*)(pZone->m_pCopyObject);
}
else
{
pRet = new CCBundle();
pNewZone = new CCZone(pRet);
}
MAP_DATAS::iterator iter = m_mDatas.begin();
for(; iter != m_mDatas.end(); ++iter)
{
switch(iter->second.nType)
{
case CCBUNDLE_SHORT:
pRet->putShort(iter->first.c_str(), *((short*)(iter->second.pValue)));
break;
case CCBUNDLE_UNSIGNEDSHORT:
pRet->putUShort(iter->first.c_str(), *((unsigned short*)(iter->second.pValue)));
break;
case CCBUNDLE_INT:
pRet->putInt(iter->first.c_str(), *((int*)(iter->second.pValue)));
break;
case CCBUNDLE_UNSIGNEDINT:
pRet->putUInt(iter->first.c_str(), *((unsigned int*)(iter->second.pValue)));
break;
case CCBUNDLE_FLOAT:
pRet->putFloat(iter->first.c_str(), *((float*)(iter->second.pValue)));
break;
case CCBUNDLE_DOUBLE:
pRet->putDouble(iter->first.c_str(), *((double*)(iter->second.pValue)));
break;
case CCBUNDLE_STRING:
pRet->putString(iter->first.c_str(), (char*)(iter->second.pValue));
break;
case CCBUNDLE_BUNDLE:
pRet->putBundle(iter->first.c_str(), (CCBundle*)((CCBundle*)(iter->second.pValue))->copy());
break;
case CCBUNDLE_OBJECT:
pRet->putObject(iter->first.c_str(), ((CCObject*)(iter->second.pValue))->copy());
break;
case CCBUNDLE_PARAM:
pRet->putParam(iter->first.c_str(), iter->second.pValue);
break;
default:
break;
}
}
CC_SAFE_DELETE(pNewZone);
return pRet;
}
void CCBundle::removeValue(const _ccBUNDLEVALUE& tValue)
{
switch(tValue.nType)
{
case CCBUNDLE_SHORT:
delete (short*)(tValue.pValue);
break;
case CCBUNDLE_UNSIGNEDSHORT:
delete (unsigned short*)(tValue.pValue);
break;
case CCBUNDLE_INT:
delete (int*)(tValue.pValue);
break;
case CCBUNDLE_UNSIGNEDINT:
delete (unsigned int*)(tValue.pValue);
break;
case CCBUNDLE_FLOAT:
delete (float*)(tValue.pValue);
break;
case CCBUNDLE_DOUBLE:
delete (double*)(tValue.pValue);
break;
case CCBUNDLE_STRING:
delete[] (char*)(tValue.pValue);
break;
case CCBUNDLE_BUNDLE:
((CCBundle*)(tValue.pValue))->release();
break;
case CCBUNDLE_OBJECT:
((CCObject*)(tValue.pValue))->release();
break;
case CCBUNDLE_PARAM:
break;
default:
break;
}
}
void CCBundle::removeValueByKey(const char* key)
{
MAP_DATAS::iterator itr = m_mDatas.find(key);
if( itr != m_mDatas.end() )
{
removeValue(itr->second);
m_mDatas.erase(itr->first);
}
}
void CCBundle::putShort(const char* key, short value)
{
removeValueByKey(key);
short* ret = new short(value);
_ccBUNDLEVALUE tag = { CCBUNDLE_SHORT, ret };
m_mDatas.insert(make_pair(key, tag));
}
void CCBundle::putUShort(const char* key, unsigned short value)
{
removeValueByKey(key);
unsigned short* ret = new unsigned short(value);
_ccBUNDLEVALUE tag = { CCBUNDLE_UNSIGNEDSHORT, ret };
m_mDatas.insert(make_pair(key, tag));
}
void CCBundle::putInt(const char* key, int value)
{
removeValueByKey(key);
int* ret = new int(value);
_ccBUNDLEVALUE tag = { CCBUNDLE_INT, ret };
m_mDatas.insert(make_pair(key, tag));
}
void CCBundle::putUInt(const char* key, unsigned int value)
{
removeValueByKey(key);
unsigned int* ret = new unsigned int(value);
_ccBUNDLEVALUE tag = { CCBUNDLE_UNSIGNEDINT, ret };
m_mDatas.insert(make_pair(key, tag));
}
void CCBundle::putFloat(const char* key, float value)
{
removeValueByKey(key);
float* ret = new float(value);
_ccBUNDLEVALUE tag = { CCBUNDLE_FLOAT, ret };
m_mDatas.insert(make_pair(key, tag));
}
void CCBundle::putDouble(const char* key, double value)
{
removeValueByKey(key);
double* ret = new double(value);
_ccBUNDLEVALUE tag = { CCBUNDLE_DOUBLE, ret };
m_mDatas.insert(make_pair(key, tag));
}
void CCBundle::putString(const char* key, const char* value)
{
removeValueByKey(key);
size_t ulen = strlen(value);
char* ret = new char[ulen + 1];
memcpy(ret, value, ulen);
ret[ulen] = '\0';
_ccBUNDLEVALUE tag = { CCBUNDLE_STRING, ret };
m_mDatas.insert(make_pair(key, tag));
}
void CCBundle::putBundle(const char* key, CCBundle* value)
{
removeValueByKey(key);
value->retain();
_ccBUNDLEVALUE tag = { CCBUNDLE_BUNDLE, value };
m_mDatas.insert(make_pair(key, tag));
}
void CCBundle::putObject(const char* key, CCObject* value)
{
removeValueByKey(key);
value->retain();
_ccBUNDLEVALUE tag = { CCBUNDLE_OBJECT, value };
m_mDatas.insert(make_pair(key, tag));
}
void CCBundle::putParam(const char* key, void* value)
{
removeValueByKey(key);
_ccBUNDLEVALUE tag = { CCBUNDLE_PARAM, value };
m_mDatas.insert(make_pair(key, tag));
}
short CCBundle::getShort(const char* key)
{
MAP_DATAS::iterator iter = m_mDatas.find(key);
if( iter != m_mDatas.end() )
{
if( iter->second.nType == CCBUNDLE_SHORT )
{
return *((short*)(iter->second.pValue));
}
}
return 0;
}
unsigned short CCBundle::getUShort(const char* key)
{
MAP_DATAS::iterator iter = m_mDatas.find(key);
if( iter != m_mDatas.end() )
{
if( iter->second.nType == CCBUNDLE_UNSIGNEDSHORT )
{
return *((unsigned short*)(iter->second.pValue));
}
}
return 0;
}
int CCBundle::getInt(const char* key)
{
MAP_DATAS::iterator iter = m_mDatas.find(key);
if( iter != m_mDatas.end() )
{
if( iter->second.nType == CCBUNDLE_INT )
{
return *((int*)(iter->second.pValue));
}
}
return 0;
}
unsigned int CCBundle::getUInt(const char* key)
{
MAP_DATAS::iterator iter = m_mDatas.find(key);
if( iter != m_mDatas.end() )
{
if( iter->second.nType == CCBUNDLE_UNSIGNEDINT )
{
return *((unsigned int*)(iter->second.pValue));
}
}
return 0;
}
float CCBundle::getFloat(const char* key)
{
MAP_DATAS::iterator iter = m_mDatas.find(key);
if( iter != m_mDatas.end() )
{
if( iter->second.nType == CCBUNDLE_FLOAT )
{
return *((float*)(iter->second.pValue));
}
}
return 0;
}
double CCBundle::getDouble(const char* key)
{
MAP_DATAS::iterator iter = m_mDatas.find(key);
if( iter != m_mDatas.end() )
{
if( iter->second.nType == CCBUNDLE_DOUBLE )
{
return *((double*)(iter->second.pValue));
}
}
return 0;
}
const char* CCBundle::getString(const char* key)
{
MAP_DATAS::iterator iter = m_mDatas.find(key);
if( iter != m_mDatas.end() )
{
if( iter->second.nType == CCBUNDLE_STRING )
{
return (char*)(iter->second.pValue);
}
}
return NULL;
}
CCBundle* CCBundle::getBundle(const char* key)
{
MAP_DATAS::iterator iter = m_mDatas.find(key);
if( iter != m_mDatas.end() )
{
if( iter->second.nType == CCBUNDLE_BUNDLE )
{
return (CCBundle*)(iter->second.pValue);
}
}
return NULL;
}
CCObject* CCBundle::getObject(const char* key)
{
MAP_DATAS::iterator iter = m_mDatas.find(key);
if( iter != m_mDatas.end() )
{
if( iter->second.nType == CCBUNDLE_OBJECT )
{
return (CCObject*)(iter->second.pValue);
}
}
return NULL;
}
void* CCBundle::getParam(const char* key)
{
MAP_DATAS::iterator iter = m_mDatas.find(key);
if( iter != m_mDatas.end() )
{
if( iter->second.nType == CCBUNDLE_PARAM )
{
return iter->second.pValue;
}
}
return NULL;
}
NS_CC_END
| {
"content_hash": "15f195b4cff374d0ca715399d4846df1",
"timestamp": "",
"source": "github",
"line_count": 365,
"max_line_length": 95,
"avg_line_length": 21.482191780821918,
"alnum_prop": 0.6662415508225992,
"repo_name": "Jason-lee-c/CocosBase",
"id": "4053c8fad0d83df48ab7616f7e76a2a7282bdf8b",
"size": "9153",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "CocosBase/CCBundle.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2365"
},
{
"name": "C++",
"bytes": "170892"
},
{
"name": "Java",
"bytes": "1897"
},
{
"name": "Objective-C",
"bytes": "12541"
},
{
"name": "Shell",
"bytes": "2932"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace ProxyManager\Proxy;
/**
* Virtual Proxy - a lazy initializing object wrapping around the proxied subject
*
* @author Marco Pivetta <ocramius@gmail.com>
* @license MIT
*/
interface VirtualProxyInterface extends LazyLoadingInterface, ValueHolderInterface
{
}
| {
"content_hash": "1a24fabe127525c3fede26d73998598d",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 82,
"avg_line_length": 20.4,
"alnum_prop": 0.7679738562091504,
"repo_name": "cloudfoundry/php-buildpack",
"id": "9160c2eb2aca583d4aeb4b597a739615bd8ec01c",
"size": "306",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "fixtures/symfony_5_local_deps/vendor/ocramius/proxy-manager/src/ProxyManager/Proxy/VirtualProxyInterface.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1724"
},
{
"name": "CSS",
"bytes": "27696"
},
{
"name": "Go",
"bytes": "73324"
},
{
"name": "HTML",
"bytes": "24121"
},
{
"name": "JavaScript",
"bytes": "20500"
},
{
"name": "Makefile",
"bytes": "295"
},
{
"name": "PHP",
"bytes": "541348"
},
{
"name": "Python",
"bytes": "584757"
},
{
"name": "Ruby",
"bytes": "1102"
},
{
"name": "SCSS",
"bytes": "15480"
},
{
"name": "Shell",
"bytes": "20264"
},
{
"name": "Smalltalk",
"bytes": "8"
},
{
"name": "Twig",
"bytes": "86464"
}
],
"symlink_target": ""
} |
package org.jetbrains.plugins.scala.codeInspection.targetNameAnnotation
import com.intellij.java.analysis.JavaAnalysisBundle
import org.jetbrains.plugins.scala.codeInspection.ScalaInspectionTestBase
import org.jetbrains.plugins.scala.{LatestScalaVersions, ScalaVersion}
class MultipleTargetNameAnnotationsInspectionTest extends ScalaInspectionTestBase {
override protected val classOfInspection = classOf[MultipleTargetNameAnnotationsInspection]
override protected val description = MultipleTargetNameAnnotationsInspection.message
override protected def supportedIn(version: ScalaVersion): Boolean =
version >= LatestScalaVersions.Scala_3_0
private val hint = JavaAnalysisBundle.message("remove.annotation")
def testEnumCase(): Unit = {
val code =
s"""import scala.annotation.targetName
|
|enum E:
| case A
| $START@targetName("first")$END
| $START@targetName("second")$END
| $START@targetName("third")$END
| case B
| case C
|""".stripMargin
checkTextHasError(code)
val expected =
"""import scala.annotation.targetName
|
|enum E:
| case A
| @targetName("second")
| @targetName("third")
| case B
| case C
|""".stripMargin
testQuickFix(code, expected, hint)
}
def testEnumCaseWithConstructor(): Unit = {
val code =
s"""import scala.annotation.targetName
|
|enum E:
| case A
| $START@targetName("first")$END
| $START@targetName("second")$END
| $START@targetName("third")$END
| case B(i: Int)
| case C
|""".stripMargin
checkTextHasError(code)
val expected =
"""import scala.annotation.targetName
|
|enum E:
| case A
| @targetName("second")
| @targetName("third")
| case B(i: Int)
| case C
|""".stripMargin
testQuickFix(code, expected, hint)
}
def testEnum(): Unit = {
val code =
s"""import scala.annotation.targetName
|
|$START@targetName("first")$END
|$START@targetName("second")$END
|$START@targetName("third")$END
|enum E:
| case A, B
|""".stripMargin
checkTextHasError(code)
val expected =
"""import scala.annotation.targetName
|
|@targetName("second")
|@targetName("third")
|enum E:
| case A, B
|""".stripMargin
testQuickFix(code, expected, hint)
}
def testTrait(): Unit = {
val code =
s"""import scala.annotation.targetName
|
|$START@targetName("first")$END
|$START@targetName("second")$END
|$START@targetName("third")$END
|trait T
|""".stripMargin
checkTextHasError(code)
val expected =
"""import scala.annotation.targetName
|
|@targetName("second")
|@targetName("third")
|trait T
|""".stripMargin
testQuickFix(code, expected, hint)
}
def testObject(): Unit = {
val code =
s"""import scala.annotation.targetName
|
|$START@targetName("first")$END
|$START@targetName("second")$END
|$START@targetName("third")$END
|object O
|""".stripMargin
checkTextHasError(code)
val expected =
"""import scala.annotation.targetName
|
|@targetName("second")
|@targetName("third")
|object O
|""".stripMargin
testQuickFix(code, expected, hint)
}
def testClass(): Unit = {
val code =
s"""import scala.annotation.targetName
|
|$START@targetName("first")$END
|$START@targetName("second")$END
|$START@targetName("third")$END
|class C
|""".stripMargin
checkTextHasError(code)
val expected =
"""import scala.annotation.targetName
|
|@targetName("second")
|@targetName("third")
|class C
|""".stripMargin
testQuickFix(code, expected, hint)
}
def testValDecl(): Unit = {
val code =
s"""import scala.annotation.targetName
|
|class C:
| $START@targetName("first")$END
| $START@targetName("second")$END
| $START@targetName("third")$END
| val v: Int
|""".stripMargin
checkTextHasError(code)
val expected =
"""import scala.annotation.targetName
|
|class C:
| @targetName("second")
| @targetName("third")
| val v: Int
|""".stripMargin
testQuickFix(code, expected, hint)
}
def testValDef(): Unit = {
val code =
s"""import scala.annotation.targetName
|
|class C:
| $START@targetName("first")$END
| $START@targetName("second")$END
| $START@targetName("third")$END
| val v: Int = 42
|""".stripMargin
checkTextHasError(code)
val expected =
"""import scala.annotation.targetName
|
|class C:
| @targetName("second")
| @targetName("third")
| val v: Int = 42
|""".stripMargin
testQuickFix(code, expected, hint)
}
def testVarDecl(): Unit = {
val code =
s"""import scala.annotation.targetName
|
|class C:
| $START@targetName("first")$END
| $START@targetName("second")$END
| $START@targetName("third")$END
| var v: Int
|""".stripMargin
checkTextHasError(code)
val expected =
"""import scala.annotation.targetName
|
|class C:
| @targetName("second")
| @targetName("third")
| var v: Int
|""".stripMargin
testQuickFix(code, expected, hint)
}
def testVarDef(): Unit = {
val code =
s"""import scala.annotation.targetName
|
|class C:
| $START@targetName("first")$END
| $START@targetName("second")$END
| $START@targetName("third")$END
| var v: Int = 42
|""".stripMargin
checkTextHasError(code)
val expected =
"""import scala.annotation.targetName
|
|class C:
| @targetName("second")
| @targetName("third")
| var v: Int = 42
|""".stripMargin
testQuickFix(code, expected, hint)
}
def testDefDecl(): Unit = {
val code =
s"""import scala.annotation.targetName
|
|class C:
| $START@targetName("first")$END
| $START@targetName("second")$END
| $START@targetName("third")$END
| def f(i: Int): Int
|""".stripMargin
checkTextHasError(code)
val expected =
"""import scala.annotation.targetName
|
|class C:
| @targetName("second")
| @targetName("third")
| def f(i: Int): Int
|""".stripMargin
testQuickFix(code, expected, hint)
}
def testDefDef(): Unit = {
val code =
s"""import scala.annotation.targetName
|
|class C:
| $START@targetName("first")$END
| $START@targetName("second")$END
| $START@targetName("third")$END
| def f(i: Int): Int = i * 2
|""".stripMargin
checkTextHasError(code)
val expected =
"""import scala.annotation.targetName
|
|class C:
| @targetName("second")
| @targetName("third")
| def f(i: Int): Int = i * 2
|""".stripMargin
testQuickFix(code, expected, hint)
}
def testGiven(): Unit = {
val code =
s"""import scala.annotation.targetName
|
|$START@targetName("first")$END
|$START@targetName("second")$END
|$START@targetName("third")$END
|given foo(using i: Int): String = " " * i
|""".stripMargin
checkTextHasError(code)
val expected =
"""import scala.annotation.targetName
|
|@targetName("second")
|@targetName("third")
|given foo(using i: Int): String = " " * i
|""".stripMargin
testQuickFix(code, expected, hint)
}
def testTypeAliasDecl(): Unit = {
val code =
s"""import scala.annotation.targetName
|
|trait T:
| $START@targetName("first")$END
| $START@targetName("second")$END
| $START@targetName("third")$END
| type TT
|""".stripMargin
checkTextHasError(code)
val expected =
"""import scala.annotation.targetName
|
|trait T:
| @targetName("second")
| @targetName("third")
| type TT
|""".stripMargin
testQuickFix(code, expected, hint)
}
def testTypeAliasDef(): Unit = {
val code =
s"""import scala.annotation.targetName
|
|trait T:
| $START@targetName("first")$END
| $START@targetName("second")$END
| $START@targetName("third")$END
| type TT = Long
|""".stripMargin
checkTextHasError(code)
val expected =
"""import scala.annotation.targetName
|
|trait T:
| @targetName("second")
| @targetName("third")
| type TT = Long
|""".stripMargin
testQuickFix(code, expected, hint)
}
def testClassParam(): Unit = {
val code =
s"""import scala.annotation.targetName
|
|class C(i: Int, $START@targetName("first")$END $START@targetName("second")$END $START@targetName("third")$END s: String)
|""".stripMargin
checkTextHasError(code)
val expected =
"""import scala.annotation.targetName
|
|class C(i: Int, @targetName("second") @targetName("third") s: String)
|""".stripMargin
testQuickFix(code, expected, hint)
}
def testTraitParam(): Unit = {
val code =
s"""import scala.annotation.targetName
|
|trait T(i: Int, $START@targetName("first")$END $START@targetName("second")$END $START@targetName("third")$END s: String)
|""".stripMargin
checkTextHasError(code)
val expected =
"""import scala.annotation.targetName
|
|trait T(i: Int, @targetName("second") @targetName("third") s: String)
|""".stripMargin
testQuickFix(code, expected, hint)
}
def testEnumParam(): Unit = {
val code =
s"""import scala.annotation.targetName
|
|enum E(i: Int, $START@targetName("first")$END $START@targetName("second")$END $START@targetName("third")$END s: String):
| case A extends E(42, "foo")
|""".stripMargin
checkTextHasError(code)
val expected =
"""import scala.annotation.targetName
|
|enum E(i: Int, @targetName("second") @targetName("third") s: String):
| case A extends E(42, "foo")
|""".stripMargin
testQuickFix(code, expected, hint)
}
def testEnumCaseParam(): Unit = {
val code =
s"""import scala.annotation.targetName
|
|enum E:
| case A(i: Int, $START@targetName("first")$END $START@targetName("second")$END $START@targetName("third")$END s: String)
|""".stripMargin
checkTextHasError(code)
val expected =
"""import scala.annotation.targetName
|
|enum E:
| case A(i: Int, @targetName("second") @targetName("third") s: String)
|""".stripMargin
testQuickFix(code, expected, hint)
}
def testDefParam(): Unit = {
val code =
s"""import scala.annotation.targetName
|
|def foo(i: Int, $START@targetName("first")$END $START@targetName("second")$END $START@targetName("third")$END s: String): Int
|""".stripMargin
checkTextHasError(code)
val expected =
"""import scala.annotation.targetName
|
|def foo(i: Int, @targetName("second") @targetName("third") s: String): Int
|""".stripMargin
testQuickFix(code, expected, hint)
}
def testGivenParam(): Unit = {
val code =
s"""import scala.annotation.targetName
|
|given foo($START@targetName("first")$END $START@targetName("second")$END $START@targetName("third")$END s: String): Int
|""".stripMargin
checkTextHasError(code)
val expected =
"""import scala.annotation.targetName
|
|given foo(@targetName("second") @targetName("third") s: String): Int
|""".stripMargin
testQuickFix(code, expected, hint)
}
def testSingleAnnotation(): Unit = {
val code =
"""import scala.annotation.targetName
|
|class A(val value: Int):
| @targetName("multiply")
| def *(that: A): A = this.value * that.value
|""".stripMargin
checkTextHasNoErrors(code)
}
def testNoAnnotations(): Unit = {
val code =
"""class A(val value: Int):
| def *(that: A): A = this.value * that.value
|""".stripMargin
checkTextHasNoErrors(code)
}
}
| {
"content_hash": "479821e3948c2fb0e1038988f2a504e9",
"timestamp": "",
"source": "github",
"line_count": 479,
"max_line_length": 135,
"avg_line_length": 27.338204592901878,
"alnum_prop": 0.5581519663993891,
"repo_name": "JetBrains/intellij-scala",
"id": "714e8213d7899bceddc14d9d455333bce9f51197",
"size": "13095",
"binary": false,
"copies": "1",
"ref": "refs/heads/idea223.x",
"path": "scala/scala-impl/test/org/jetbrains/plugins/scala/codeInspection/targetNameAnnotation/MultipleTargetNameAnnotationsInspectionTest.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "106688"
},
{
"name": "Java",
"bytes": "1165562"
},
{
"name": "Lex",
"bytes": "45405"
},
{
"name": "Scala",
"bytes": "18656869"
}
],
"symlink_target": ""
} |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'settings.ui'
#
# Created: Thu Jun 14 13:03:23 2012
# by: PyQt4 UI code generator 4.9.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_Settings(object):
def setupUi(self, Settings):
Settings.setObjectName(_fromUtf8("Settings"))
Settings.resize(700, 500)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(Settings.sizePolicy().hasHeightForWidth())
Settings.setSizePolicy(sizePolicy)
Settings.setMinimumSize(QtCore.QSize(700, 500))
Settings.setMaximumSize(QtCore.QSize(700, 500))
self.centralWidget = QtGui.QWidget(Settings)
self.centralWidget.setStyleSheet(_fromUtf8("/* sets background color */\n"
"QWidget {\n"
"background-color:rgba(255,255,255,0);\n"
"}\n"
"QWidget#centralWidget{\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:1, x2:0, y2:0, stop:0 rgba(220, 232, 243, 255), stop:0.35545 rgba(247, 247, 247, 255), stop:0.635071 rgba(247, 247, 247, 255), stop:0.933649 rgba(220, 232, 243, 255));\n"
"}\n"
"QToolTip {\n"
" border: 1px solid rgb(188, 189, 207);\n"
" padding: 0.1px;\n"
" border-radius:1px;\n"
" color: rgb(188, 189, 207);\n"
" background-color: rgb(255, 255, 255);\n"
" background-origin:padding-box;\n"
" opacity: 100;\n"
" }\n"
"\n"
"\n"
"\n"
"QLineEdit {\n"
" border: 1px inset rgb(188, 189, 207);\n"
" border-radius: 5px;\n"
" padding: 0 3px;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:1, x2:0, y2:0, stop:0.0545455 rgba(237, 240, 243, 255), stop:0.35545 rgba(247, 247, 247, 255), stop:0.635071 rgba(247, 247, 247, 255), stop:0.933649 rgba(237, 240, 243, 255));\n"
" }\n"
"\n"
"QGroupBox {\n"
" border-radius: 5px;\n"
" border:2px groove rgb(188, 198, 207);\n"
" background-color: rgba(255, 255, 255, 0);\n"
" margin: 6px;\n"
"\n"
"}\n"
"QGroupBox::title {\n"
" subcontrol-origin: margin;\n"
" subcontrol-position: top left; /* position at the top center */\n"
" padding: 0 3px;\n"
" border:2px groove rgb(188, 198, 207);\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:1, x2:0, y2:0, stop:0.208531 rgba(212, 223, 232, 255), stop:0.905213 rgba(239, 251, 254, 255));\n"
" font: 11pt \"Arial\";\n"
" border-radius: 5px;\n"
"}\n"
"\n"
"QLabel{\n"
" border-bottom:1px solid;\n"
" border-bottom-color: rgb(188, 198, 207);\n"
" background-color: rgba(255, 255, 255, 0);\n"
" border-radius: 5px;\n"
" padding: 0 0px;\n"
"}\n"
"\n"
"\n"
" QPushButton {\n"
" border: 2px outset rgb(188, 198, 207);\n"
" border-radius: 5px;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:1, x2:0, y2:0, stop:0 rgba(220, 232, 243, 255), stop:0.35545 rgba(247, 247, 247, 255), stop:0.635071 rgba(247, 247, 247, 255), stop:0.933649 rgba(220, 232, 243, 255));\n"
" \n"
" }\n"
"\n"
" QPushButton:pressed {\n"
" border: 2px inset rgb(188, 198, 207);\n"
" background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
" stop: 0 #dadbde, stop: 1 #f6f7fa);\n"
" }\n"
"\n"
"QListWidget{\n"
"border: 1px groove rgb(188, 198, 207);\n"
"}"))
self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
self.tabWidget = QtGui.QTabWidget(self.centralWidget)
self.tabWidget.setGeometry(QtCore.QRect(10, 10, 661, 431))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.tabWidget.sizePolicy().hasHeightForWidth())
self.tabWidget.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(13)
self.tabWidget.setFont(font)
self.tabWidget.setFocusPolicy(QtCore.Qt.NoFocus)
self.tabWidget.setStyleSheet(_fromUtf8("QTabWidget::pane { /* The tab widget frame */\n"
" border-top: 2px groove rgb(188, 198, 207);\n"
" \n"
" background-color: qlineargradient(spread:pad, x1:1, y1:0, x2:0, y2:0, stop:0.0181818 rgba(233, 240, 243, 255), stop:0.372727 rgba(247, 247, 247, 255), stop:0.659091 rgba(247, 247, 247, 255), stop:1 rgba(233, 240, 243, 255));\n"
" border: 1px inset rgb(188, 189, 207);\n"
" border-radius: 5px;\n"
"\n"
" }\n"
"\n"
" QTabWidget::tab-bar {\n"
" left: 5px; /* move to the right by 5px */\n"
" }\n"
"\n"
" /* Style the tab using the tab sub-control. Note that\n"
" it reads QTabBar _not_ QTabWidget */\n"
" QTabBar::tab {\n"
" \n"
" background-color: qlineargradient(spread:pad, x1:0, y1:1, x2:0, y2:0, stop:0.208531 rgba(199, 209, 217, 255), stop:0.905213 rgba(239, 251, 254, 255));\n"
" /*background-color: qlineargradient(spread:pad, x1:0, y1:1, x2:0, y2:0, stop:0 rgba(118, 212, 230, 255), stop:1 rgba(255, 255, 255, 255));*/\n"
" border: 2px groove rgb(188, 198, 207);\n"
" border-bottom-color: rgb(188, 198, 207); /* same as the pane color */\n"
" border-top-left-radius: 4px;\n"
" border-top-right-radius: 4px;\n"
" min-width: 17ex;\n"
" padding: 2px;\n"
" }\n"
"\n"
" QTabBar::tab:selected, QTabBar::tab:hover {\n"
" \n"
" background-color: qlineargradient(spread:pad, x1:0, y1:1, x2:0, y2:0, stop:0.208531 rgba(212, 223, 232, 255), stop:0.905213 rgba(239, 251, 254, 255));\n"
" }\n"
"\n"
" QTabBar::tab:selected {\n"
" border-color: rgb(188, 198, 207);\n"
" border-bottom-color: rgb(188, 198, 207); /* same as pane color */\n"
" }\n"
"\n"
" QTabBar::tab:!selected {\n"
" margin-top: 2px; /* make non-selected tabs look smaller */\n"
" }\n"
"\n"
""))
self.tabWidget.setObjectName(_fromUtf8("tabWidget"))
self.user = QtGui.QWidget()
self.user.setObjectName(_fromUtf8("user"))
self.label = QtGui.QLabel(self.user)
self.label.setGeometry(QtCore.QRect(10, 35, 131, 19))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
self.label.setFont(font)
self.label.setStyleSheet(_fromUtf8(""))
self.label.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.label.setObjectName(_fromUtf8("label"))
self.label_2 = QtGui.QLabel(self.user)
self.label_2.setGeometry(QtCore.QRect(10, 85, 141, 19))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(11)
self.label_2.setFont(font)
self.label_2.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.text_user = QtGui.QLineEdit(self.user)
self.text_user.setGeometry(QtCore.QRect(160, 30, 231, 25))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
self.text_user.setFont(font)
self.text_user.setObjectName(_fromUtf8("text_user"))
self.text_pass = QtGui.QLineEdit(self.user)
self.text_pass.setGeometry(QtCore.QRect(160, 80, 231, 25))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
self.text_pass.setFont(font)
self.text_pass.setEchoMode(QtGui.QLineEdit.PasswordEchoOnEdit)
self.text_pass.setObjectName(_fromUtf8("text_pass"))
self.check_amm_DB = QtGui.QCheckBox(self.user)
self.check_amm_DB.setGeometry(QtCore.QRect(160, 130, 231, 24))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.check_amm_DB.sizePolicy().hasHeightForWidth())
self.check_amm_DB.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
self.check_amm_DB.setFont(font)
self.check_amm_DB.setFocusPolicy(QtCore.Qt.NoFocus)
self.check_amm_DB.setObjectName(_fromUtf8("check_amm_DB"))
self.tabWidget.addTab(self.user, _fromUtf8(""))
self.databases = QtGui.QWidget()
self.databases.setObjectName(_fromUtf8("databases"))
self.Registra = QtGui.QPushButton(self.databases)
self.Registra.setGeometry(QtCore.QRect(450, 30, 101, 51))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.Registra.sizePolicy().hasHeightForWidth())
self.Registra.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(13)
self.Registra.setFont(font)
self.Registra.setFocusPolicy(QtCore.Qt.NoFocus)
self.Registra.setObjectName(_fromUtf8("Registra"))
self.EliminaButton = QtGui.QPushButton(self.databases)
self.EliminaButton.setGeometry(QtCore.QRect(450, 150, 101, 51))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.EliminaButton.sizePolicy().hasHeightForWidth())
self.EliminaButton.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(13)
self.EliminaButton.setFont(font)
self.EliminaButton.setFocusPolicy(QtCore.Qt.NoFocus)
self.EliminaButton.setObjectName(_fromUtf8("EliminaButton"))
self.ModificaButton = QtGui.QPushButton(self.databases)
self.ModificaButton.setGeometry(QtCore.QRect(450, 90, 101, 51))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.ModificaButton.sizePolicy().hasHeightForWidth())
self.ModificaButton.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(13)
self.ModificaButton.setFont(font)
self.ModificaButton.setFocusPolicy(QtCore.Qt.NoFocus)
self.ModificaButton.setObjectName(_fromUtf8("ModificaButton"))
self.list_DB = QtGui.QTreeWidget(self.databases)
self.list_DB.setGeometry(QtCore.QRect(160, 20, 256, 361))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(12)
self.list_DB.setFont(font)
self.list_DB.setFocusPolicy(QtCore.Qt.NoFocus)
self.list_DB.setStyleSheet(_fromUtf8("QFrame{\n"
" \n"
" background-color: qlineargradient(spread:pad, x1:1, y1:0, x2:0, y2:0, stop:0.0181818 rgba(233, 240, 243, 255), stop:0.372727 rgba(247, 247, 247, 255), stop:0.659091 rgba(247, 247, 247, 255), stop:1 rgba(233, 240, 243, 255));\n"
" border: 1px inset rgb(188, 189, 207);\n"
" border-radius: 5px;\n"
"}"))
self.list_DB.setObjectName(_fromUtf8("list_DB"))
self.list_DB.headerItem().setText(0, _fromUtf8("1"))
self.list_DB.header().setVisible(False)
self.list_DB.header().setDefaultSectionSize(250)
self.list_DB.header().setMinimumSectionSize(250)
self.tabWidget.addTab(self.databases, _fromUtf8(""))
self.tab = QtGui.QWidget()
self.tab.setStyleSheet(_fromUtf8("QFrame{\n"
" \n"
" background-color: qlineargradient(spread:pad, x1:1, y1:0, x2:0, y2:0, stop:0.0181818 rgba(233, 240, 243, 255), stop:0.372727 rgba(247, 247, 247, 255), stop:0.659091 rgba(247, 247, 247, 255), stop:1 rgba(233, 240, 243, 255));\n"
" border: 1px inset rgb(188, 189, 207);\n"
" border-radius: 5px;\n"
"}"))
self.tab.setObjectName(_fromUtf8("tab"))
self.groupBox = QtGui.QGroupBox(self.tab)
self.groupBox.setGeometry(QtCore.QRect(10, 50, 211, 341))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(12)
self.groupBox.setFont(font)
self.groupBox.setObjectName(_fromUtf8("groupBox"))
self.list_funzioni = QtGui.QTreeWidget(self.groupBox)
self.list_funzioni.setGeometry(QtCore.QRect(10, 30, 191, 291))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
self.list_funzioni.setFont(font)
self.list_funzioni.setFocusPolicy(QtCore.Qt.NoFocus)
self.list_funzioni.setVerticalScrollMode(QtGui.QAbstractItemView.ScrollPerPixel)
self.list_funzioni.setObjectName(_fromUtf8("list_funzioni"))
self.list_funzioni.headerItem().setText(0, _fromUtf8("1"))
self.list_funzioni.header().setVisible(False)
self.list_funzioni.header().setDefaultSectionSize(185)
self.list_funzioni.header().setMinimumSectionSize(185)
self.groupBox_2 = QtGui.QGroupBox(self.tab)
self.groupBox_2.setGeometry(QtCore.QRect(220, 50, 211, 341))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(12)
self.groupBox_2.setFont(font)
self.groupBox_2.setObjectName(_fromUtf8("groupBox_2"))
self.list_esp = QtGui.QTreeWidget(self.groupBox_2)
self.list_esp.setGeometry(QtCore.QRect(10, 30, 191, 341))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
self.list_esp.setFont(font)
self.list_esp.setFocusPolicy(QtCore.Qt.NoFocus)
self.list_esp.setVerticalScrollMode(QtGui.QAbstractItemView.ScrollPerPixel)
self.list_esp.setObjectName(_fromUtf8("list_esp"))
self.list_esp.headerItem().setText(0, _fromUtf8("1"))
self.list_esp.header().setVisible(False)
self.list_esp.header().setDefaultSectionSize(185)
self.list_esp.header().setMinimumSectionSize(185)
self.groupBox_3 = QtGui.QGroupBox(self.tab)
self.groupBox_3.setGeometry(QtCore.QRect(430, 50, 211, 341))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(12)
self.groupBox_3.setFont(font)
self.groupBox_3.setObjectName(_fromUtf8("groupBox_3"))
self.list_amm = QtGui.QTreeWidget(self.groupBox_3)
self.list_amm.setGeometry(QtCore.QRect(10, 30, 191, 341))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
self.list_amm.setFont(font)
self.list_amm.setFocusPolicy(QtCore.Qt.NoFocus)
self.list_amm.setVerticalScrollMode(QtGui.QAbstractItemView.ScrollPerPixel)
self.list_amm.setObjectName(_fromUtf8("list_amm"))
self.list_amm.headerItem().setText(0, _fromUtf8("1"))
self.list_amm.header().setVisible(False)
self.list_amm.header().setDefaultSectionSize(185)
self.list_amm.header().setMinimumSectionSize(185)
self.comboBox = QtGui.QComboBox(self.tab)
self.comboBox.setGeometry(QtCore.QRect(120, 10, 241, 25))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
self.comboBox.setFont(font)
self.comboBox.setFocusPolicy(QtCore.Qt.NoFocus)
self.comboBox.setStyleSheet(_fromUtf8("\n"
"QFrame{\n"
" \n"
" background-color: qlineargradient(spread:pad, x1:1, y1:0, x2:0, y2:0, stop:0.0181818 rgba(233, 240, 243, 255), stop:0.372727 rgba(247, 247, 247, 255), stop:0.659091 rgba(247, 247, 247, 255), stop:1 rgba(233, 240, 243, 255));\n"
" border: 1px inset rgb(188, 189, 207);\n"
" border-radius: 5px;\n"
"}\n"
"QComboBox{\n"
" border: 1px inset rgb(188, 189, 207);\n"
" border-radius: 5px;\n"
" padding: 0 3px;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:1, x2:0, y2:0, stop:0.0545455 rgba(237, 240, 243, 255), stop:0.35545 rgba(247, 247, 247, 255), stop:0.635071 rgba(247, 247, 247, 255), stop:0.933649 rgba(237, 240, 243, 255));\n"
"}\n"
"\n"
" QComboBox:editable {\n"
" \n"
" background-color: rgb(222, 232, 245);\n"
" }\n"
"\n"
" QComboBox:!editable, QComboBox::drop-down:editable {\n"
"background-color: qlineargradient(spread:pad, x1:0, y1:1, x2:0, y2:0, stop:0 rgba(220, 226, 229, 255), stop:0.254545 rgba(247, 247, 247, 255), stop:0.722727 rgba(247, 247, 247, 255), stop:1 rgba(220, 226, 229, 255));\n"
"color:black;\n"
" }\n"
"\n"
" /* QComboBox gets the \"on\" state when the popup is open */\n"
" QComboBox:!editable:on, QComboBox::drop-down:editable:on {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:1, x2:0, y2:0, stop:0 rgba(220, 226, 229, 255), stop:0.254545 rgba(247, 247, 247, 255), stop:0.722727 rgba(247, 247, 247, 255), stop:1 rgba(220, 226, 229, 255));\n"
"color:black;\n"
" }\n"
"\n"
" QComboBox:on { /* shift the text when the popup opens */\n"
" padding-top: 3px;\n"
" padding-left: 4px;\n"
" }\n"
"\n"
"\n"
""))
self.comboBox.setObjectName(_fromUtf8("comboBox"))
self.label_3 = QtGui.QLabel(self.tab)
self.label_3.setGeometry(QtCore.QRect(10, 10, 101, 25))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(12)
self.label_3.setFont(font)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.Applica = QtGui.QPushButton(self.tab)
self.Applica.setGeometry(QtCore.QRect(437, 7, 98, 35))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(12)
self.Applica.setFont(font)
self.Applica.setFocusPolicy(QtCore.Qt.NoFocus)
self.Applica.setObjectName(_fromUtf8("Applica"))
self.CreaNuovo = QtGui.QPushButton(self.tab)
self.CreaNuovo.setGeometry(QtCore.QRect(540, 7, 98, 35))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(12)
self.CreaNuovo.setFont(font)
self.CreaNuovo.setFocusPolicy(QtCore.Qt.NoFocus)
self.CreaNuovo.setObjectName(_fromUtf8("CreaNuovo"))
self.tabWidget.addTab(self.tab, _fromUtf8(""))
self.AnnullaButton = QtGui.QPushButton(self.centralWidget)
self.AnnullaButton.setGeometry(QtCore.QRect(467, 450, 111, 41))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(13)
self.AnnullaButton.setFont(font)
self.AnnullaButton.setFocusPolicy(QtCore.Qt.NoFocus)
self.AnnullaButton.setObjectName(_fromUtf8("AnnullaButton"))
self.OKButton = QtGui.QPushButton(self.centralWidget)
self.OKButton.setGeometry(QtCore.QRect(587, 450, 101, 41))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(13)
self.OKButton.setFont(font)
self.OKButton.setFocusPolicy(QtCore.Qt.NoFocus)
self.OKButton.setObjectName(_fromUtf8("OKButton"))
Settings.setCentralWidget(self.centralWidget)
self.retranslateUi(Settings)
self.tabWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(Settings)
def retranslateUi(self, Settings):
Settings.setWindowTitle(QtGui.QApplication.translate("Settings", "Settings", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("Settings", "User", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("Settings", "Password", None, QtGui.QApplication.UnicodeUTF8))
self.check_amm_DB.setText(QtGui.QApplication.translate("Settings", "Amministratore del Sistema", None, QtGui.QApplication.UnicodeUTF8))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.user), QtGui.QApplication.translate("Settings", "User", None, QtGui.QApplication.UnicodeUTF8))
self.Registra.setText(QtGui.QApplication.translate("Settings", "Registra", None, QtGui.QApplication.UnicodeUTF8))
self.EliminaButton.setText(QtGui.QApplication.translate("Settings", "Elimina", None, QtGui.QApplication.UnicodeUTF8))
self.ModificaButton.setText(QtGui.QApplication.translate("Settings", "Modifica", None, QtGui.QApplication.UnicodeUTF8))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.databases), QtGui.QApplication.translate("Settings", "Databases", None, QtGui.QApplication.UnicodeUTF8))
self.groupBox.setTitle(QtGui.QApplication.translate("Settings", "Funzionalità", None, QtGui.QApplication.UnicodeUTF8))
self.groupBox_2.setTitle(QtGui.QApplication.translate("Settings", "Backoffice", None, QtGui.QApplication.UnicodeUTF8))
self.groupBox_3.setTitle(QtGui.QApplication.translate("Settings", "Zone Analysis", None, QtGui.QApplication.UnicodeUTF8))
self.label_3.setText(QtGui.QApplication.translate("Settings", "Profilo", None, QtGui.QApplication.UnicodeUTF8))
self.Applica.setText(QtGui.QApplication.translate("Settings", "Applica", None, QtGui.QApplication.UnicodeUTF8))
self.CreaNuovo.setText(QtGui.QApplication.translate("Settings", "Crea Nuovo", None, QtGui.QApplication.UnicodeUTF8))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), QtGui.QApplication.translate("Settings", "Profilo", None, QtGui.QApplication.UnicodeUTF8))
self.AnnullaButton.setText(QtGui.QApplication.translate("Settings", "Annulla", None, QtGui.QApplication.UnicodeUTF8))
self.OKButton.setText(QtGui.QApplication.translate("Settings", "OK", None, QtGui.QApplication.UnicodeUTF8))
| {
"content_hash": "c4e1affa8dab5b0944ab5b3413b8b106",
"timestamp": "",
"source": "github",
"line_count": 431,
"max_line_length": 238,
"avg_line_length": 49.97911832946636,
"alnum_prop": 0.6639431781254352,
"repo_name": "arpho/mmasgis5",
"id": "3b3355373f6adfb6e10c9c9280e00253b438385f",
"size": "21542",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mmasgis/Ui_settings.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "617"
},
{
"name": "C++",
"bytes": "856"
},
{
"name": "CSS",
"bytes": "17115"
},
{
"name": "JavaScript",
"bytes": "21348"
},
{
"name": "Prolog",
"bytes": "1548"
},
{
"name": "Python",
"bytes": "13348612"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<myDoc>
<head>
<its:rules xmlns:its="http://www.w3.org/2005/11/its" version="2.0"
xmlns:xlink="http://www.w3.org/1999/xlink" xlink:type="simple" xlink:href="Translate_global_rules_XML.xml"/>
</head>
<body>
<par id="100" title="Text">The <trmark id="notran">World Wide Web Consortium</trmark> is making the World Wide Web worldwide!</par>
</body>
</myDoc>
| {
"content_hash": "c0a2172d570ee5d85417b32c895c28ca",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 133,
"avg_line_length": 38.8,
"alnum_prop": 0.6752577319587629,
"repo_name": "renatb/ITS2.0-WICS-converter",
"id": "780570ba11421d3b00fec271c644a6fe7dde2976",
"size": "388",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/input/WICS_samples/XML-to-HTML/Translate_global.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "34139"
},
{
"name": "JavaScript",
"bytes": "2036"
},
{
"name": "Perl",
"bytes": "485294"
}
],
"symlink_target": ""
} |
<?php
/**
* Cash on delivery payment method model
*/
class Mage_Payment_Model_Method_Cashondelivery extends Mage_Payment_Model_Method_Abstract
{
/**
* Payment method code
*
* @var string
*/
protected $_code = 'cashondelivery';
/**
* Cash On Delivery payment block paths
*
* @var string
*/
protected $_formBlockType = 'payment/form_cashondelivery';
protected $_infoBlockType = 'payment/info';
/**
* Get instructions text from config
*
* @return string
*/
public function getInstructions()
{
return trim($this->getConfigData('instructions'));
}
}
| {
"content_hash": "5608d214aa6d91895bbcee07a7d6d0a3",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 89,
"avg_line_length": 18.8,
"alnum_prop": 0.6003039513677811,
"repo_name": "garasiya/magento1910",
"id": "fa139b8405c582d001d6ad37814ddd5307c8c754",
"size": "1597",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "app/code/core/Mage/Payment/Model/Method/Cashondelivery.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ActionScript",
"bytes": "19946"
},
{
"name": "ApacheConf",
"bytes": "6705"
},
{
"name": "Batchfile",
"bytes": "1036"
},
{
"name": "CSS",
"bytes": "1753629"
},
{
"name": "HTML",
"bytes": "5223902"
},
{
"name": "JavaScript",
"bytes": "1103124"
},
{
"name": "PHP",
"bytes": "44372061"
},
{
"name": "PowerShell",
"bytes": "1028"
},
{
"name": "Ruby",
"bytes": "288"
},
{
"name": "Shell",
"bytes": "2036"
},
{
"name": "XSLT",
"bytes": "2135"
}
],
"symlink_target": ""
} |
layout: post
title: "Disclosure & Sam Smith - Hotline Bling Cover"
modified:
categories: Music
excerpt:
tags: [Music]
image:
feature:
date: 2015-09-16T15:45:20-07:00
---
<iframe width="100%" height="450" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/224157146&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&visual=true"></iframe>
| {
"content_hash": "a74b4021eca4bc3017ff007ae7ecb918",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 288,
"avg_line_length": 41.90909090909091,
"alnum_prop": 0.7527114967462039,
"repo_name": "patricknyu/patricknyu.github.io",
"id": "c830fcb5bc00d3cf47a5e59e4ee9bd167e3acbf5",
"size": "465",
"binary": false,
"copies": "1",
"ref": "refs/heads/temp",
"path": "_posts/Music/2015-09-16-disclosure-and-sam-smith-hotline-bling-cover.markdown",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "53327"
},
{
"name": "HTML",
"bytes": "805078"
},
{
"name": "JavaScript",
"bytes": "189608"
},
{
"name": "Perl",
"bytes": "71244"
},
{
"name": "Ruby",
"bytes": "2676"
},
{
"name": "TeX",
"bytes": "231832"
}
],
"symlink_target": ""
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ru.dmerkushov.confighelper;
/**
*
* @author Dmitriy Merkushov
*/
public class ConfigHelperException extends Exception {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance of
* <code>ConfigHelperException</code> without detail message.
*/
public ConfigHelperException () {
}
/**
* Constructs an instance of
* <code>ConfigHelperException</code> with the specified detail message.
*
* @param msg the detail message.
*/
public ConfigHelperException (String msg) {
super (msg);
}
/**
* Constructs an instance of
* <code>ConfigHelperException</code> with the specified cause.
*
* @param cause the cause (which is saved for later retrieval by the
* Exception.getCause() method). (A null value is permitted, and indicates
* that the cause is nonexistent or unknown.)
*/
public ConfigHelperException (Throwable cause) {
super (cause);
}
/**
* Constructs an instance of
* <code>ConfigHelperException</code> with the specified detail message and
* cause.
*
* @param msg the detail message.
* @param cause the cause (which is saved for later retrieval by the
* Exception.getCause() method). (A null value is permitted, and indicates
* that the cause is nonexistent or unknown.)
*/
public ConfigHelperException (String msg, Throwable cause) {
super (msg, cause);
}
}
| {
"content_hash": "1fb2fb93428d683182698b56a1407f93",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 76,
"avg_line_length": 26.142857142857142,
"alnum_prop": 0.7083333333333334,
"repo_name": "dmerkushov/config-helper",
"id": "a557c32ec633f73baa236b748d72219bc8997e50",
"size": "1464",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/ru/dmerkushov/confighelper/ConfigHelperException.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "5739"
}
],
"symlink_target": ""
} |
Mister Lemons is a lemonade stand simulator. Its evolution is partly an
exercise in building the game, but mostly an exercise in learning various JS
development techniques.
## PSA to myself
`glide` does not like symlinks.
## TODO
- [x] clean auth/auth.go out of auth/service.go
- [x] add logging to auth middleware
- [x] handle sql nullable type
- [x] test remaining endpoints
- [x] make login store last login time
- [x] fix the dockerfile for vendor
- [x] js: get front end loading
- [x] js: remove immutable
- [x] js: inline "container" elements
- [x] js: build "modules"
- [x] js: be sure moment, lodash, router, redux, sagas all in
- [x] js: revise state shape
- [ ] xx: integrate authentication / login
- [x] js: remove signup (add when needed)
- [x] go: login endpoint returns user
- [x] js: debug user fetch from login
- [x] js: debug routes & such
- [x] go: restructure around passed-in cfg & db (closures)
- [x] go: restructure to be top-level
- [ ] go: store status endpoint
- [ ] turn dynamic
- [ ] calculate sales
- [ ] adjust inventory
- [ ] ledger model (or just roll up?)
- [ ] js: store status panel
- [ ] weather model
## Rethink:
- [ ] Store status
- [ ] Cash position
- [ ] Sales
- [ ] Per day at first
- [ ] Nice per-hour chart might be nice eventually
- [ ] Changes when time moves
- [ ] Expenses
- [ ] Yesterday's total
- [ ] Today's itemized expenses
- [ ] Expenses can change between turns
- [ ] Inventory
- [ ] Prepared lemonade
- [ ] Ingredients
- [ ] Can change between turns
- [ ] Weather
- [ ] Day #
- [ ] Forecast
- [ ] Yesterday
## Projected Play
1. See store status:
- Yesterday's sales
- Yesterday's expenses
- Weather for yesterday, today
2. Take turn:
- Purchase
- See prices
- See current on hand
- See projected on hand
- See projected cost
- Button to add qty
- Button to commit *
- Brew
- See current on hand
- See projected on hand
- Button to add qty
- See cost per unit
- Set price
- Button to commit *
- Run the day
UI:
- daily report: weather, sales, yesterday's expenses
- "activity panel"
| {
"content_hash": "1df7d7cc2b5325446746f87479370244",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 76,
"avg_line_length": 25.988095238095237,
"alnum_prop": 0.6404031149793862,
"repo_name": "ggerrietts/lemons",
"id": "42bf0c4a4f095294f0f0af55a47ced1098bf1321",
"size": "2200",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "404"
},
{
"name": "Go",
"bytes": "16428"
},
{
"name": "HTML",
"bytes": "1773"
},
{
"name": "JavaScript",
"bytes": "25982"
},
{
"name": "Python",
"bytes": "733"
},
{
"name": "Shell",
"bytes": "650"
}
],
"symlink_target": ""
} |
/*
* Base structure
*/
/* Move down content because we have a fixed navbar that is 50px tall */
body {
padding-top: 50px;
}
/*
* Global add-ons
*/
.sub-header {
padding-bottom: 10px;
border-bottom: 1px solid #eee;
}
/*
* Top navigation
* Hide default border to remove 1px line.
*/
.navbar-fixed-top {
border: 0;
}
/*
* Sidebar
*/
/* Hide for mobile, show later */
.sidebar {
display: none;
}
@media (min-width: 768px) {
.sidebar {
position: fixed;
top: 51px;
bottom: 0;
left: 0;
z-index: 1000;
display: block;
padding: 10px;
overflow-x: auto;
overflow-y: auto; /* Scrollable contents if viewport is shorter than content. */
background-color: #f5f5f5;
border-right: 1px solid #eee;
}
}
/* Sidebar navigation */
.nav-sidebar {
margin-right: -21px; /* 20px padding + 1px border */
margin-bottom: 20px;
margin-left: -20px;
}
.nav-sidebar > li > a {
padding-right: 20px;
padding-left: 20px;
}
.nav-sidebar > .active > a,
.nav-sidebar > .active > a:hover,
.nav-sidebar > .active > a:focus {
color: #fff;
background-color: #428bca;
}
/*
* Main content
*/
.main {
padding: 20px;
}
@media (min-width: 768px) {
.main {
padding-right: 40px;
padding-left: 40px;
}
}
.main .page-header {
margin-top: 0;
}
/*
* Placeholder dashboard ideas
*/
.placeholders {
margin-bottom: 30px;
text-align: center;
}
.placeholders h4 {
margin-bottom: 0;
}
.placeholder {
margin-bottom: 20px;
}
.placeholder img {
display: inline-block;
border-radius: 50%;
}
| {
"content_hash": "816fb21f3c9d38e3b228e1dd8a407fe8",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 84,
"avg_line_length": 14.80952380952381,
"alnum_prop": 0.6192926045016077,
"repo_name": "raoul2000/cam-browser2",
"id": "e4b23b917087ea737ae1ca43163d05b7f60cf3b3",
"size": "1555",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web/page/layout-bs-1.css",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1030"
},
{
"name": "CSS",
"bytes": "3613"
},
{
"name": "HTML",
"bytes": "23815"
},
{
"name": "JavaScript",
"bytes": "10724"
},
{
"name": "PHP",
"bytes": "122571"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Linq;
using LCL.Web.BootstrapMvc.BootstrapModels;
using LCL.Web.BootstrapMvc.Enums;
namespace LCL.Web.BootstrapMvc
{
/// <summary>
/// Provides methods to generate HTML code for Twitter Bootstrap.
/// </summary>
public class BootstrapHelper
{
#region Fields
/// <summary>
/// Represents the instance of the <see cref="HtmlHelper"/> associated with this <see cref="BootstrapMvcPage"/>.
/// </summary>
protected readonly HtmlHelper Html;
/// <summary>
/// Represents the instance of the <see cref="UrlHelper"/> associated with this <see cref="BootstrapMvcPage"/>.
/// </summary>
protected readonly UrlHelper Url;
/// <summary>
/// Represents the instance of the <see cref="BootstrapMvcPage"/> associated to this <see cref="BootstrapHelper"/>
/// </summary>
protected readonly BootstrapMvcPage Page;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of the Bootstrap helper.
/// </summary>
/// <param name="page">The current view</param>
public BootstrapHelper(BootstrapMvcPage page)
{
Page = page;
Html = page.Html;
Url = page.Url;
}
#endregion
#region Internal Helpers
/// <summary>
/// Checks if an Url is matching the current view.
/// </summary>
/// <param name="url">Url to check</param>
internal bool IsCurrentUrl(string url)
{
var currentUrl = Html.ViewContext.RequestContext.HttpContext.Request.Url;
if (currentUrl == null) return false;
return currentUrl.AbsoluteUri.Equals(url) || currentUrl.AbsolutePath.Equals(url);
}
#endregion
#region Typography
/// <summary>
/// Creates an HTML abbreviation with it's corresponding definition.
/// </summary>
/// <param name="title">Definition of the abbreviation.</param>
/// <param name="value">The abbreviation.</param>
public MvcHtmlString Abbreviation(string title, string value)
{
return Abbreviation(title, value, false);
}
/// <summary>
/// Creates an HTML abbreviation with it's corresponding definition.
/// </summary>
/// <param name="title">Definition of the abbreviation.</param>
/// <param name="value">The abbreviation.</param>
/// <param name="isReduced">
/// Defines if the abbreviation uses the <c>initialism</c> class for a slightly
/// smaller font-size.
/// </param>
public MvcHtmlString Abbreviation(string title, string value, bool isReduced)
{
var abbr = new TagBuilderExt("abbr", value);
if (isReduced)
abbr.AddCssClass("initialism");
abbr.MergeAttribute("title", title);
return abbr.ToMvcHtmlString();
}
/// <summary>
/// Creates an HTML block-quote.
/// </summary>
/// <param name="quote">The quote.</param>
/// <param name="author">The author.</param>
/// <param name="source">The source.</param>
/// <param name="sourceTitle">
/// The <paramref name="source"/> title.
/// </param>
public MvcHtmlString BlockQuote(string quote, string author, string source, string sourceTitle)
{
return BlockQuote(quote, author, source, sourceTitle, false);
}
/// <summary>
/// Creates an HTML block-quote.
/// </summary>
/// <param name="quote">The quote.</param>
/// <param name="author">The author.</param>
/// <param name="source">The source.</param>
/// <param name="sourceTitle">
/// The <paramref name="source"/> title.
/// </param>
/// <param name="isPulledRight">
/// Set to <see langword="true"/> for a floated, right-aligned
/// blockquote.
/// </param>
public MvcHtmlString BlockQuote(string quote, string author, string source, string sourceTitle, bool isPulledRight)
{
var blockquote = new TagBuilderExt("blockquote");
if (isPulledRight)
blockquote.AddCssClass("pull-right");
var cite = new TagBuilderExt("cite", source);
cite.MergeAttribute("title", sourceTitle);
blockquote.CreateChildTag("p", quote);
blockquote.CreateChildTag("small").InnerHtml = String.Concat(author, " ", cite.ToString());
return blockquote.ToMvcHtmlString();
}
/// <summary>
/// Begins a new list tag
/// </summary>
/// <param name="listType">Type of the desired list.</param>
/// <returns>
///
/// </returns>
public BootstrapMvcList BeginList(ListType listType)
{
var list = new BootstrapMvcList(Html.ViewContext);
list.BeginList(listType);
return list;
}
/// <summary>
/// Creates a list with the associated elements.
/// </summary>
/// <param name="listType">The type of the list.</param>
/// <param name="elements">The elements of the list.</param>
public MvcHtmlString List(ListType listType, IEnumerable<string> elements)
{
if (elements == null) return null;
var root = BootstrapMvcList.GetRootTagBuilder(listType);
foreach (var element in elements)
{
root.CreateChildTag("li", element);
}
return root.ToMvcHtmlString();
}
/// <summary>
/// Creates a list of terms with their associated descriptions.
/// </summary>
/// <param name="isHorizontal">
/// Make terms and descriptions in the description list line up side-by-side.
/// </param>
public BootstrapMvcList BeginDescriptionList(bool isHorizontal)
{
var list = new BootstrapMvcList(Html.ViewContext);
list.BeginDescriptionList(isHorizontal);
return list;
}
/// <summary>
/// Creates a description list with the associated descriptions
/// </summary>
/// <param name="isHorizontal">
/// Make terms and descriptions in line up side-by-side.
/// </param>
/// <param name="elements">
/// The dictionary of descriptions by title (key) and description
/// (value).
/// </param>
public MvcHtmlString DescriptionList(bool isHorizontal, IDictionary<string, string> elements)
{
if (elements == null) return null;
var root = new TagBuilderExt("dl");
if (isHorizontal)
root.AddCssClass("dl-horizontal");
foreach (var element in elements)
{
root.CreateChildTag("dt", element.Key);
root.CreateChildTag("dd", element.Value);
}
return root.ToMvcHtmlString();
}
/// <summary>
/// Creates an emphasized paragraph
/// </summary>
/// <param name="text">Content of the emphasized paragraph</param>
/// <param name="emphasisType">Type of the emphasis</param>
public MvcHtmlString EmphasizedParagraph(string text, EmphasisType emphasisType)
{
var p = new TagBuilderExt("p");
switch (emphasisType)
{
case EmphasisType.Muted:
p.AddCssClass("muted");
break;
case EmphasisType.Warning:
p.AddCssClass("text-warning");
break;
case EmphasisType.Error:
p.AddCssClass("text-error");
break;
case EmphasisType.Info:
p.AddCssClass("text-info");
break;
case EmphasisType.Success:
p.AddCssClass("text-success");
break;
default:
throw new ArgumentOutOfRangeException("emphasisType");
}
p.SetInnerText(text);
return p.ToMvcHtmlString();
}
/// <summary>
/// Makes a paragraph using the lead class to make it stand out.
/// </summary>
/// <param name="text">Content of the paragraph</param>
public MvcHtmlString LeadBody(string text)
{
var p = new TagBuilderExt("p");
p.AddCssClass("lead");
p.SetInnerText(text);
return p.ToMvcHtmlString();
}
#endregion
#region Buttons
private TagBuilderExt CreateBaseButton(string tagName, ButtonStyle buttonStyle, ButtonSize buttonSize, bool isDisabled)
{
var tag = new TagBuilderExt(tagName);
tag.AddCssClass("btn");
switch (buttonStyle)
{
case ButtonStyle.Primary:
tag.AddCssClass("btn-primary");
break;
case ButtonStyle.Info:
tag.AddCssClass("btn-info");
break;
case ButtonStyle.Success:
tag.AddCssClass("btn-success");
break;
case ButtonStyle.Warning:
tag.AddCssClass("btn-warning");
break;
case ButtonStyle.Danger:
tag.AddCssClass("btn-danger");
break;
case ButtonStyle.Inverse:
tag.AddCssClass("btn-inverse");
break;
case ButtonStyle.Link:
tag.AddCssClass("btn-link");
break;
}
switch (buttonSize)
{
case ButtonSize.Large:
tag.AddCssClass("btn-large");
break;
case ButtonSize.Small:
tag.AddCssClass("btn-small");
break;
case ButtonSize.Mini:
tag.AddCssClass("btn-mini");
break;
}
if (isDisabled)
tag.AddCssClass("disabled");
return tag;
}
#region Link buttons
/// <summary>
/// Creates an "a" tag styled as a button.
/// </summary>
/// <param name="text">Inner text of the tag.</param>
/// <param name="href">Link destination.</param>
/// <param name="buttonType">The button style type.</param>
/// <param name="buttonSize">The button size.</param>
/// <param name="isDisabled">
/// Makes the button looks unclickable by fading them back 50%. True to
/// disable, False to enable.
/// </param>
public MvcHtmlString LinkButton(string text, string href, ButtonStyle buttonType, ButtonSize buttonSize, bool isDisabled)
{
var tag = CreateBaseButton("a", buttonType, buttonSize, isDisabled);
tag.SetInnerText(text);
tag.MergeAttribute("href", href);
return tag.ToMvcHtmlString();
}
/// <summary>
/// Creates an "a" tag with a default button style and size.
/// </summary>
/// <param name="text">Inner text of the tag.</param>
/// <param name="href">Link destination.</param>
public MvcHtmlString LinkButton(string text, string href)
{
return LinkButton(text, href, ButtonStyle.Default, ButtonSize.Default, false);
}
#endregion
#region Submit buttons
/// <summary>
/// Creates a submit button tag with the given style and size.
/// </summary>
/// <param name="text">Inner text of the tag.</param>
/// <param name="buttonStyle">The button style type.</param>
/// <param name="buttonSize">The button size.</param>
/// <param name="isDisabled">
/// Make buttons look unclickable by fading them back 50%. True to
/// disable, False to enable.
/// </param>
public MvcHtmlString SubmitButton(string text, ButtonStyle buttonStyle, ButtonSize buttonSize, bool isDisabled)
{
var tag = CreateBaseButton("button", buttonStyle, buttonSize, isDisabled);
tag.MergeAttribute("type", "submit");
tag.SetInnerText(text);
return tag.ToMvcHtmlString();
}
/// <summary>
/// Creates a submit button tag with a default style and size.
/// </summary>
/// <param name="text">Inner text of the tag.</param>
public MvcHtmlString SubmitButton(string text)
{
return SubmitButton(text, ButtonStyle.Default, ButtonSize.Default, false);
}
#endregion
#region Input buttons
/// <summary>
/// Creates an input button tag with the given style and size.
/// </summary>
/// <param name="text">Inner text of the tag.</param>
/// <param name="buttonStyle">The button style type.</param>
/// <param name="buttonSize">The button size.</param>
/// <param name="isDisabled">
/// Make buttons look unclickable by fading them back 50%. True to
/// disable, False to enable.
/// </param>
public MvcHtmlString InputButton(string text, ButtonStyle buttonStyle, ButtonSize buttonSize, bool isDisabled)
{
var tag = CreateBaseButton("input", buttonStyle, buttonSize, isDisabled);
tag.MergeAttribute("type", "button");
tag.SetInnerText(text);
return tag.ToMvcHtmlString();
}
/// <summary>
/// Creates an input button tag with a default style and size.
/// </summary>
/// <param name="text">Inner text of the tag.</param>
public MvcHtmlString InputButton(string text)
{
return InputButton(text, ButtonStyle.Default, ButtonSize.Default, false);
}
#endregion
#region Input Submit buttons
/// <summary>
/// Creates an input submit button tag with the given style and size.
/// </summary>
/// <param name="text">Inner text of the tag.</param>
/// <param name="buttonStyle">The button style type.</param>
/// <param name="buttonSize">The button size.</param>
/// <param name="isDisabled">
/// Make buttons look unclickable by fading them back 50%. True to
/// disable, False to enable.
/// </param>
public MvcHtmlString InputSubmitButton(string text, ButtonStyle buttonStyle, ButtonSize buttonSize, bool isDisabled)
{
var tag = CreateBaseButton("input", buttonStyle, buttonSize, isDisabled);
tag.MergeAttribute("type", "submit");
tag.SetInnerText(text);
return tag.ToMvcHtmlString();
}
/// <summary>
/// Creates an input submit button tag with a default style and size.
/// </summary>
/// <param name="text">Inner text of the tag.</param>
public MvcHtmlString InputSubmitButton(string text)
{
return InputSubmitButton(text, ButtonStyle.Default, ButtonSize.Default, false);
}
#endregion
#endregion
#region Images
/// <summary>
/// Define an image
/// </summary>
/// <param name="source">the url for the image</param>
/// <param name="alt">alternate text for the image</param>
/// <param name="imageType">type of image</param>
public MvcHtmlString Image(string source, string alt, ImageType imageType)
{
var img = new TagBuilderExt("img");
img.MergeAttribute("alt", alt);
img.MergeAttribute("src", source);
switch (imageType)
{
case ImageType.Rounded:
img.AddCssClass("img-rounded");
break;
case ImageType.Circle:
img.AddCssClass("img-circle");
break;
case ImageType.Polaroid:
img.AddCssClass("img-polaroid");
break;
default:
throw new ArgumentOutOfRangeException("imageType");
}
return img.ToMvcHtmlString();
}
/// <summary>
/// Define an Image(source as the alternate text).
/// </summary>
/// <param name="source">url and alternate text</param>
/// <param name="imageType">type of image</param>
public MvcHtmlString Image(string source, ImageType imageType)
{
return Image(source, source, imageType);
}
#endregion
#region Menu
/// <summary>
/// Creates a menu (<c>navbar</c>) that can contains menu components.
/// </summary>
/// <param name="menuType">The menu type</param>
/// <param name="isInversed">
/// Reverse the <c>navbar</c> colors: True to reverse, False (default) for
/// normal.
/// </param>
public BootstrapMvcMenu BeginMenu(MenuType menuType, bool isInversed)
{
var menu = new BootstrapMvcMenu(Html.ViewContext);
menu.BeginMenu(menuType, isInversed);
return menu;
}
/// <summary>
/// Creates a menu (<c>navbar</c>) that can contains menu components.
/// </summary>
/// <param name="menuType">The menu type</param>
public BootstrapMvcMenu BeginMenu(MenuType menuType)
{
return BeginMenu(menuType, false);
}
/// <summary>
/// Creates a basic default menu (<c>navbar</c>) that can contains menu
/// components.
/// </summary>
public BootstrapMvcMenu BeginMenu()
{
return BeginMenu(MenuType.Basic, false);
}
/// <summary>
/// Creates a menu <paramref name="title"/> (have to be used inside a
/// navbar menu).
/// </summary>
/// <param name="title">Title of the menu</param>
/// <param name="action">The name of the a action</param>
/// <param name="controller">The name of the controller</param>
/// <param name="routeValues">
/// An object that contains the parameters for a route. The parameters
/// are retrieved through reflection by examining the properties of the
/// object. The object is typically created by using object initializer
/// syntax.
/// </param>
public MvcHtmlString MenuTitle(string title, string action, string controller, object routeValues)
{
return MenuTitle(title, Url.Action(action, controller, routeValues));
}
/// <summary>
/// Creates a menu <paramref name="title"/> (have to be used inside a
/// navbar menu).
/// </summary>
/// <param name="title">Title of the menu</param>
/// <param name="action">The action name</param>
/// <param name="controller">The controller name</param>
public MvcHtmlString MenuTitle(string title, string action, string controller)
{
return MenuTitle(title, Url.Action(action, controller));
}
/// <summary>
/// Creates a menu <paramref name="title"/> (have to be used inside a
/// navbar menu).
/// </summary>
/// <param name="title">Title of the menu</param>
/// <param name="url">A Fully quallified URL</param>
public MvcHtmlString MenuTitle(string title, string url)
{
var a = new TagBuilderExt("a", title);
a.AddCssClass("brand");
a.MergeAttribute("href", url);
return a.ToMvcHtmlString();
}
/// <summary>
/// Begins a menu items container.
/// </summary>
public BootstrapMvcMenuItemsContainer BeginMenuItems()
{
var menuItems = new BootstrapMvcMenuItemsContainer(Html.ViewContext);
menuItems.BeginMenuItems();
return menuItems;
}
/// <summary>
/// Creates one menu link entry with the specified
/// <paramref name="title"/> and link.
/// </summary>
/// <param name="title">The title of the menu link</param>
/// <param name="action">The name of the action</param>
/// <param name="controller">The name of the controller</param>
/// <param name="routeValues">
/// An object that contains the parameters for a route. The parameters
/// are retrieved through reflection by examining the properties of the
/// object. The object is typically created by using object initializer
/// syntax.
/// </param>
public MvcHtmlString MenuLink(string title, string action, string controller, object routeValues)
{
return MenuLink(title, Url.Action(action, controller, routeValues));
}
/// <summary>
/// Creates one menu link entry with the specified
/// <paramref name="title"/> and link.
/// </summary>
/// <param name="title">The title of the menu link</param>
/// <param name="action">The name of the action</param>
/// <param name="controller">The name of the controller</param>
public MvcHtmlString MenuLink(string title, string action, string controller)
{
return MenuLink(title, Url.Action(action, controller));
}
/// <summary>
/// Creates one menu link entry with the specified
/// <paramref name="title"/> and link.
/// </summary>
/// <param name="title">The title of the menu link</param>
/// <param name="url">The fully quallified URL</param>
public MvcHtmlString MenuLink(string title, string url)
{
var listItem = new TagBuilderExt("li");
if (IsCurrentUrl(url))
listItem.AddCssClass("active");
var link = new TagBuilderExt("a");
link.MergeAttribute("href", url);
link.SetInnerText(title);
listItem.AddChildTag(link);
return listItem.ToMvcHtmlString();
}
/// <summary>
/// Creates a vertical menu-item separator
/// </summary>
public MvcHtmlString MenuItemSeparator()
{
var tag = new TagBuilderExt("li");
tag.AddCssClass("divider-vertical");
return tag.ToMvcHtmlString();
}
/// <summary>
/// Begins a menu form. Have to be used inside a Bootstrap MVC Menu.
/// </summary>
/// <param name="menuFormType">The form type</param>
/// <param name="horizontalAlignment">
/// The horizontal alignment applied on the form
/// </param>
public BootstrapMenuForm BeginMenuForm(MenuFormType menuFormType, HorizontalAlignment horizontalAlignment)
{
var menuForm = new BootstrapMenuForm(Html.ViewContext);
menuForm.BeginList(menuFormType, horizontalAlignment);
return menuForm;
}
/// <summary>
/// Begins a default menu form. Have to be used inside a Bootstrap MVC
/// Menu.
/// </summary>
/// <param name="horizontalAlignment">
/// The horizontal alignment applied on the form
/// </param>
public BootstrapMenuForm BeginMenuForm(HorizontalAlignment horizontalAlignment)
{
return BeginMenuForm(MenuFormType.Default, horizontalAlignment);
}
/// <summary>
/// Begins a menu form with a default left alignment. Have to be used
/// inside a Bootstrap MVC Menu.
/// </summary>
/// <param name="menuFormType">The form type</param>
public BootstrapMenuForm BeginMenuForm(MenuFormType menuFormType)
{
return BeginMenuForm(menuFormType, HorizontalAlignment.Left);
}
/// <summary>
/// Begins a default menu form with a default left alignment. Have to be
/// used inside a Bootstrap MVC Menu.
/// </summary>
public BootstrapMenuForm BeginMenuForm()
{
return BeginMenuForm(MenuFormType.Default, HorizontalAlignment.Left);
}
#endregion
#region Breadcrumbs
/// <summary>
/// Begins a breadcrumbs container that can be filled with breadcrumb
/// links.
/// </summary>
/// <returns>
///
/// </returns>
public BootstrapBreadcrumb BeginBreadCrumb()
{
var breadCrumb = new BootstrapBreadcrumb(Html.ViewContext);
breadCrumb.BeginBreadcrumb();
return breadCrumb;
}
/// <summary>
/// Creates an automatic breadcrumb based on the navigation history.
/// </summary>
/// <param name="maximumElements">
/// The maximum number of breadcrumbs to be displayed.
/// </param>
/// <param name="divider">The divider used between breadcrumbs.</param>
/// <returns>
///
/// </returns>
public MvcHtmlString Breadcrumb(int maximumElements, string divider)
{
var breadcrumbTag = new TagBuilderExt("ul");
breadcrumbTag.AddCssClass("breadcrumb");
var navHistory = Page.NavigationHistory.ToArray();
var linksToDisplay = navHistory.Skip(Math.Max(0, navHistory.Count() - maximumElements)).Take(maximumElements);
var visitedPages = linksToDisplay as IList<VisitedPage> ?? linksToDisplay.ToList();
var lastElement = visitedPages.Last();
foreach (var visitedPage in visitedPages)
{
if (visitedPage == lastElement)
divider = null;
breadcrumbTag.InnerHtml += BreadcrumbLink(visitedPage.Title, visitedPage.Uri.AbsoluteUri, divider);
}
return breadcrumbTag.ToMvcHtmlString();
}
/// <summary>
/// Creates one breadcrumb link entry with the specified
/// <paramref name="title"/> and link.
/// </summary>
/// <param name="title">The title of the breadcrumb link</param>
/// <param name="action">The name of the action</param>
/// <param name="controller">The name of the controller</param>
/// <param name="routeValues">
/// An object that contains the parameters for a route. The parameters
/// are retrieved through reflection by examining the properties of the
/// object. The object is typically created by using object initializer
/// syntax.
/// </param>
/// <param name="divider">
/// Specify the divider created after the link. Set to "null" or empty
/// for no divider.
/// </param>
public MvcHtmlString BreadcrumbLink(string title, string action, string controller, object routeValues, string divider)
{
return BreadcrumbLink(title, Url.Action(action, controller, routeValues), divider);
}
/// <summary>
/// Creates one breadcrumb link entry with the specified
/// <paramref name="title"/> and link.
/// </summary>
/// <param name="title">The title of the breadcrumb link</param>
/// <param name="action">The name of the action</param>
/// <param name="controller">The name of the controller</param>
/// <param name="divider">
/// Specify the divider created after the link. Set to "null" or empty
/// for no divider.
/// </param>
public MvcHtmlString BreadcrumbLink(string title, string action, string controller, string divider)
{
return BreadcrumbLink(title, Url.Action(action, controller), divider);
}
/// <summary>
/// Creates one breadcrumb link entry with the specified
/// <paramref name="title"/> and link.
/// </summary>
/// <param name="title">The title of the breadcrumb link</param>
/// <param name="url">The fully quallified URL</param>
/// <param name="divider">
/// Specify the divider created after the link. Set to "null" or empty
/// for no divider.
/// </param>
public MvcHtmlString BreadcrumbLink(string title, string url, string divider)
{
var listItem = new TagBuilderExt("li");
if (IsCurrentUrl(url))
{
listItem.AddCssClass("active");
listItem.SetInnerText(title);
}
else
{
var link = new TagBuilderExt("a");
link.MergeAttribute("href", url);
link.SetInnerText(title);
listItem.AddChildTag(link);
}
if (!string.IsNullOrEmpty(divider))
{
var dividerTag = new TagBuilderExt("span", divider);
dividerTag.AddCssClass("divider");
listItem.AddChildTag(dividerTag);
}
return listItem.ToMvcHtmlString();
}
#endregion
#region Progress bars
/// <summary>
/// Creates a Bootstrap progress-bar with a defined
/// <paramref name="style"/>, <paramref name="color"/> and
/// <paramref name="progress"/>.
/// </summary>
/// <param name="style">The style of the progress bar</param>
/// <param name="color">The color of the progress bar</param>
/// <param name="progress">The current progress percentage</param>
public MvcHtmlString ProgressBar(ProgressBarStyle style, ProgressBarColor color, double progress)
{
var progressTag = new TagBuilderExt("div");
progressTag.AddCssClass("progress");
switch (color)
{
case ProgressBarColor.Info:
progressTag.AddCssClass("progress-info");
break;
case ProgressBarColor.Success:
progressTag.AddCssClass("progress-success");
break;
case ProgressBarColor.Warning:
progressTag.AddCssClass("progress-warning");
break;
case ProgressBarColor.Danger:
progressTag.AddCssClass("progress-danger");
break;
}
switch (style)
{
case ProgressBarStyle.Animated:
progressTag.AddCssClass("active");
break;
case ProgressBarStyle.Striped:
progressTag.AddCssClass("progress-striped");
break;
}
var barTag = progressTag.CreateChildTag("div");
barTag.AddCssClass("bar");
barTag.MergeAttribute("style", string.Format("width: {0}%", progress));
return progressTag.ToMvcHtmlString();
}
/// <summary>
/// Creates a Bootstrap progress-bar with a defined
/// <paramref name="style"/>, a default color and
/// <paramref name="progress"/>.
/// </summary>
/// <param name="style">The style of the progress bar</param>
/// <param name="progress">The current progress percentage</param>
public MvcHtmlString ProgressBar(ProgressBarStyle style, double progress)
{
return ProgressBar(style, ProgressBarColor.Default, progress);
}
/// <summary>
/// Creates a Bootstrap progress-bar with a default
/// style, a specified <paramref name="color"/> and
/// <paramref name="progress"/>.
/// </summary>
/// <param name="color">The color of the progress bar</param>
/// <param name="progress">The current progress percentage</param>
public MvcHtmlString ProgressBar(ProgressBarColor color, double progress)
{
return ProgressBar(ProgressBarStyle.Default, color, progress);
}
/// <summary>
/// Creates a Bootstrap progress-bar with a default color and style.
/// </summary>
/// <param name="progress">The current progress percentage</param>
public MvcHtmlString ProgressBar(double progress)
{
return ProgressBar(ProgressBarStyle.Default, ProgressBarColor.Default, progress);
}
#endregion
#region Forms
#endregion
}
/// <summary>
/// Provides methods to generate HTML code for Twitter Bootstrap on a generic view.
/// </summary>
/// <typeparam name="TModel">The generic page-view view-model</typeparam>
public class BootstrapHelper<TModel> : BootstrapHelper
where TModel : class
{
private BootstrapMvcPage _page;
private HtmlHelper<TModel> _html;
/// <summary>
/// Creates a new instance of the Bootstrap helper.
/// </summary>
/// <param name="page">The current view.</param>
public BootstrapHelper(BootstrapMvcPage<TModel> page) : base(page)
{
_page = page;
_html = page.Html;
}
}
}
| {
"content_hash": "7eb6e353856827eed4cb0123df44b816",
"timestamp": "",
"source": "github",
"line_count": 874,
"max_line_length": 129,
"avg_line_length": 39.483981693363845,
"alnum_prop": 0.5457996464690371,
"repo_name": "luomingui/LCLFramework",
"id": "24c933fa3ab662650d3a1706d58f050081a1572f",
"size": "34511",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LCLDemo/LCL.Web.BootstrapMvc/BootstrapHelper.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "303"
},
{
"name": "Batchfile",
"bytes": "2385"
},
{
"name": "C#",
"bytes": "1463270"
},
{
"name": "CSS",
"bytes": "3088"
},
{
"name": "HTML",
"bytes": "3945"
},
{
"name": "JavaScript",
"bytes": "14028"
},
{
"name": "PowerShell",
"bytes": "979"
},
{
"name": "XSLT",
"bytes": "58161"
}
],
"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/html; charset=utf-8" />
<title>mango.application.mdss.listdir — mango 0.9.8 documentation</title>
<link rel="stylesheet" href="../_static/default.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../',
VERSION: '0.9.8',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<link rel="top" title="mango 0.9.8 documentation" href="../index.html" />
<link rel="up" title="Mass Data Storage System (mango.application.mdss)" href="../application_mdss.html" />
<link rel="next" title="mango.application.mdss.mkdir" href="mango.application.mdss.mkdir.html" />
<link rel="prev" title="mango.application.mdss.isdir" href="mango.application.mdss.isdir.html" />
</head>
<body>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="mango.application.mdss.mkdir.html" title="mango.application.mdss.mkdir"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="mango.application.mdss.isdir.html" title="mango.application.mdss.isdir"
accesskey="P">previous</a> |</li>
<li><a href="../index.html">mango 0.9.8 documentation</a> »</li>
<li><a href="../application_mdss.html" accesskey="U">Mass Data Storage System (<tt class="docutils literal"><span class="pre">mango.application.mdss</span></tt>)</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<div class="section" id="mango-application-mdss-listdir">
<h1>mango.application.mdss.listdir<a class="headerlink" href="#mango-application-mdss-listdir" title="Permalink to this headline">¶</a></h1>
<dl class="function">
<dt id="mango.application.mdss.listdir">
<tt class="descclassname">mango.application.mdss.</tt><tt class="descname">listdir</tt><big>(</big><em>dir=None</em>, <em>project=None</em>, <em>all=False</em>, <em>appendType=False</em>, <em>dereference=False</em><big>)</big><a class="reference internal" href="../_modules/mango/application/mdss.html#listdir"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#mango.application.mdss.listdir" title="Permalink to this definition">¶</a></dt>
<dd><p>Lists file(s) in specified MDSS directory.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first simple">
<li><strong>dir</strong> (<a class="reference external" href="http://docs.python.org/2/library/functions.html#str" title="(in Python v2.7)"><tt class="xref py py-obj docutils literal"><span class="pre">str</span></tt></a>) – MDSS directory path for which files are listed.</li>
<li><strong>project</strong> (<a class="reference external" href="http://docs.python.org/2/library/functions.html#str" title="(in Python v2.7)"><tt class="xref py py-obj docutils literal"><span class="pre">str</span></tt></a>) – NCI project identifier string, if <tt class="samp docutils literal"><span class="pre">None</span></tt>, uses default
project (as returned from the <a class="reference internal" href="mango.application.mdss.getDefaultProject.html#mango.application.mdss.getDefaultProject" title="mango.application.mdss.getDefaultProject"><tt class="xref py py-func docutils literal"><span class="pre">getDefaultProject()</span></tt></a> function).</li>
<li><strong>all</strong> (<a class="reference external" href="http://docs.python.org/2/library/functions.html#bool" title="(in Python v2.7)"><tt class="xref py py-obj docutils literal"><span class="pre">bool</span></tt></a> or <a class="reference external" href="http://docs.python.org/2/library/functions.html#str" title="(in Python v2.7)"><tt class="xref py py-obj docutils literal"><span class="pre">str</span></tt></a>) – If <tt class="samp docutils literal"><span class="pre">True</span></tt> or <tt class="samp docutils literal"><span class="pre">"all"</span></tt> lists files/directories whose names begin with ‘.’.
If <tt class="samp docutils literal"><span class="pre">almost-all</span></tt> lists files/directories whose names begin with ‘.’ but not
the <tt class="samp docutils literal"><span class="pre">"."</span></tt> and <tt class="samp docutils literal"><span class="pre">".."</span></tt> entries.</li>
<li><strong>appendType</strong> (<a class="reference external" href="http://docs.python.org/2/library/functions.html#bool" title="(in Python v2.7)"><tt class="xref py py-obj docutils literal"><span class="pre">bool</span></tt></a>) – If <tt class="samp docutils literal"><span class="pre">True</span></tt> each name in the listing will have a character appended
which indicates the type of <em>file</em>.</li>
<li><strong>dereference</strong> (<a class="reference external" href="http://docs.python.org/2/library/functions.html#bool" title="(in Python v2.7)"><tt class="xref py py-obj docutils literal"><span class="pre">bool</span></tt></a>) – If <tt class="samp docutils literal"><span class="pre">True</span></tt> symbolic links are dereferenced in the listing.</li>
</ul>
</td>
</tr>
<tr class="field-even field"><th class="field-name">Return type:</th><td class="field-body"><p class="first"><a class="reference external" href="http://docs.python.org/2/library/functions.html#list" title="(in Python v2.7)"><tt class="xref py py-obj docutils literal"><span class="pre">list</span></tt></a> of <a class="reference external" href="http://docs.python.org/2/library/functions.html#str" title="(in Python v2.7)"><tt class="xref py py-obj docutils literal"><span class="pre">str</span></tt></a></p>
</td>
</tr>
<tr class="field-odd field"><th class="field-name">Returns:</th><td class="field-body"><p class="first last">MDSS directory listing.</p>
</td>
</tr>
</tbody>
</table>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar">
<div class="sphinxsidebarwrapper">
<h4>Previous topic</h4>
<p class="topless"><a href="mango.application.mdss.isdir.html"
title="previous chapter">mango.application.mdss.isdir</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="mango.application.mdss.mkdir.html"
title="next chapter">mango.application.mdss.mkdir</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../_sources/generated/mango.application.mdss.listdir.txt"
rel="nofollow">Show Source</a></li>
</ul>
<div id="searchbox" style="display: none">
<h3>Quick search</h3>
<form class="search" action="../search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
<p class="searchtip" style="font-size: 90%">
Enter search terms or a module, class or function name.
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="mango.application.mdss.mkdir.html" title="mango.application.mdss.mkdir"
>next</a> |</li>
<li class="right" >
<a href="mango.application.mdss.isdir.html" title="mango.application.mdss.isdir"
>previous</a> |</li>
<li><a href="../index.html">mango 0.9.8 documentation</a> »</li>
<li><a href="../application_mdss.html" >Mass Data Storage System (<tt class="docutils literal"><span class="pre">mango.application.mdss</span></tt>)</a> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2014, Department of Applied Mathematics, The Australian National University.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.2.3.
</div>
</body>
</html> | {
"content_hash": "921c67060094feb7e1b26f877c731161",
"timestamp": "",
"source": "github",
"line_count": 151,
"max_line_length": 650,
"avg_line_length": 62.88079470198676,
"alnum_prop": 0.6474986835176408,
"repo_name": "pymango/pymango",
"id": "3b92ab77c99ca749ecd2de0e8fc39918d10e82eb",
"size": "9497",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/sphinx_html/generated/mango.application.mdss.listdir.html",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CMake",
"bytes": "1621"
},
{
"name": "Python",
"bytes": "652240"
}
],
"symlink_target": ""
} |
using TweetLib.Browser.CEF.Interfaces;
using Xilium.CefGlue;
namespace TweetImpl.CefGlue.Adapters {
sealed class CefMenuModelAdapter : IMenuModelAdapter<CefMenuModel> {
public static CefMenuModelAdapter Instance { get; } = new ();
public int GetItemCount(CefMenuModel model) {
return model.Count;
}
public void AddCommand(CefMenuModel model, int command, string name) {
model.AddItem(command, name);
}
public int GetCommandAt(CefMenuModel model, int index) {
return model.GetCommandIdAt(index);
}
public void AddCheckCommand(CefMenuModel model, int command, string name) {
model.AddCheckItem(command, name);
}
public void SetChecked(CefMenuModel model, int command, bool isChecked) {
model.SetChecked(command, isChecked);
}
public void AddSeparator(CefMenuModel model) {
model.AddSeparator();
}
public bool IsSeparatorAt(CefMenuModel model, int index) {
return model.GetItemTypeAt(index) == CefMenuItemType.Separator;
}
public void RemoveAt(CefMenuModel model, int index) {
model.RemoveAt(index);
}
}
}
| {
"content_hash": "33146ac4f499d0c8f988fae6c278bb07",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 77,
"avg_line_length": 26.8,
"alnum_prop": 0.7434701492537313,
"repo_name": "chylex/TweetDuck",
"id": "5fb26ba69af646946ac5bbf6042fe1d8a8b37f16",
"size": "1072",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "linux/TweetImpl.CefGlue/Adapters/CefMenuModelAdapter.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "122"
},
{
"name": "C#",
"bytes": "568526"
},
{
"name": "CSS",
"bytes": "101678"
},
{
"name": "F#",
"bytes": "43385"
},
{
"name": "HTML",
"bytes": "46603"
},
{
"name": "Inno Setup",
"bytes": "17552"
},
{
"name": "JavaScript",
"bytes": "198552"
},
{
"name": "PowerShell",
"bytes": "1856"
},
{
"name": "Shell",
"bytes": "795"
}
],
"symlink_target": ""
} |
require 'test/unit'
require 'iz'
class TestUrl < Test::Unit::TestCase
def valid_urls
['http://google.com', 'https://google.com', 'http://www.foo.bar', 'https://foo.io', '//google.com.uk']
end
def invalid_urls
[nil, false, -1, '', '1112', 'g', '10101a', 'http://google', 'https://google', 'www.google']
end
def test_that_urls_return_true
valid_urls.each do |url|
assert Iz.url?(url)
end
end
def test_that_invalid_urls_return_false
invalid_urls.each do |url|
assert !Iz.url?(url)
end
end
end
| {
"content_hash": "5b90da615a57895e666b75c780ca9083",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 106,
"avg_line_length": 21.88,
"alnum_prop": 0.6106032906764168,
"repo_name": "johnotander/iz",
"id": "b2694f4692fb137bf354c9839db1beb28dc65d0f",
"size": "547",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/test_url.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "9133"
}
],
"symlink_target": ""
} |
"""
Find all undefined reference targets and attempt to determine
if they are code by emulation behaviorial analysis.
(This module works best very late in the analysis passes)
"""
import envi
import vivisect
import vivisect.exc as v_exc
from envi.archs.i386.opconst import *
import vivisect.impemu.monitor as viv_imp_monitor
import logging
from vivisect.const import *
logger = logging.getLogger(__name__)
class watcher(viv_imp_monitor.EmulationMonitor):
def __init__(self, vw, tryva):
viv_imp_monitor.EmulationMonitor.__init__(self)
self.vw = vw
self.tryva = tryva
self.hasret = False
self.mndist = {}
self.insn_count = 0
self.lastop = None
self.badcode = False
self.badops = vw.arch.archGetBadOps()
def logAnomaly(self, emu, eip, msg):
self.badcode = True
emu.stopEmu()
def looksgood(self):
if not self.hasret or self.badcode:
return False
# if there is 1 mnem that makes up over 50% of all instructions then flag it as invalid
for mnem, count in self.mndist.items():
if round(float( float(count) / float(self.insn_count)), 3) >= .67 and self.insn_count > 4:
return False
return True
def iscode(self):
op = self.lastop
if not self.lastop:
return False
if not (op.iflags & envi.IF_RET) and not (op.iflags & envi.IF_BRANCH) and not (op.iflags & envi.IF_CALL):
return False
for mnem, count in self.mndist.items():
# XXX - CONFIG OPTION
if round(float( float(count) / float(self.insn_count)), 3) >= .60:
return False
return True
def prehook(self, emu, op, eip):
if op.mnem == "out": # FIXME arch specific. see above idea.
emu.stopEmu()
raise v_exc.BadOutInstruction(op.va)
if op in self.badops:
emu.stopEmu()
raise v_exc.BadOpBytes(op.va)
if op.iflags & envi.IF_RET:
self.hasret = True
emu.stopEmu()
self.lastop = op
loc = self.vw.getLocation(eip)
if loc is not None:
va, size, ltype, linfo = loc
if ltype != vivisect.LOC_OP:
emu.stopEmu()
raise Exception("HIT LOCTYPE %d AT 0x%.8x" % (ltype, va))
cnt = self.mndist.get(op.mnem, 0)
self.mndist[op.mnem] = cnt + 1
self.insn_count += 1
# FIXME do we need a way to terminate emulation here?
def apicall(self, emu, op, pc, api, argv):
# if the call is to a noret API we are done
if self.vw.isNoReturnVa(pc):
self.hasret = True
emu.stopEmu()
def analyze(vw):
flist = vw.getFunctions()
tried = set()
while True:
docode = []
bcode = []
vatodo = []
vatodo = [ va for va, name in vw.getNames() if vw.getLocation(va) is None ]
vatodo.extend( [tova for fromva, tova, reftype, rflags in vw.getXrefs(rtype=REF_PTR) if vw.getLocation(tova) is None] )
for va in set(vatodo):
loc = vw.getLocation(va)
if loc is not None:
if loc[L_LTYPE] == LOC_STRING:
vw.makeString(va)
tried.add(va)
elif loc[L_LTYPE] == LOC_UNI:
vw.makeUnicode(va)
tried.add(va)
continue
if vw.isDeadData(va):
continue
# Make sure it's executable
if not vw.isExecutable(va):
continue
# Skip it if we've tried it already.
if va in tried:
continue
tried.add(va)
emu = vw.getEmulator()
wat = watcher(vw, va)
emu.setEmulationMonitor(wat)
try:
emu.runFunction(va, maxhit=1)
except Exception:
continue
if wat.looksgood():
docode.append(va)
# flag to tell us to be greedy w/ finding code
# XXX - visi is going to hate this..
elif wat.iscode() and vw.greedycode:
bcode.append(va)
else:
if vw.isProbablyUnicode(va):
vw.makeUnicode(va)
elif vw.isProbablyString(va):
vw.makeString(va)
if len(docode) == 0:
break
docode.sort()
for va in docode:
if vw.getLocation(va) is not None:
continue
try:
logger.debug('discovered new function: 0x%x', va)
vw.makeFunction(va)
except:
continue
bcode.sort()
for va in bcode:
if vw.getLocation(va) is not None:
continue
# TODO: consider elevating to functions?
vw.makeCode(va)
dlist = vw.getFunctions()
newfuncs = set(dlist) - set(flist)
for fva in newfuncs:
vw.setVaSetRow('EmucodeFunctions', (fva,))
vw.vprint("emucode: %d new functions defined (now total: %d)" % (len(dlist)-len(flist), len(dlist)))
| {
"content_hash": "91b16e68fd4769663c478d3f73237f28",
"timestamp": "",
"source": "github",
"line_count": 180,
"max_line_length": 127,
"avg_line_length": 29,
"alnum_prop": 0.5344827586206896,
"repo_name": "bat-serjo/vivisect",
"id": "e936c2cd52c9cae12cc3b5f87694125eae398d2a",
"size": "5220",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vivisect/analysis/generic/emucode.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "167795"
},
{
"name": "CSS",
"bytes": "15980"
},
{
"name": "Makefile",
"bytes": "355"
},
{
"name": "Python",
"bytes": "11662904"
},
{
"name": "Shell",
"bytes": "476"
}
],
"symlink_target": ""
} |
package org.springframework.jms;
/**
* Runtime exception mirroring the JMS TransactionRolledBackException.
* @author Les Hazlewood
* @since 1.1
* @see javax.jms.TransactionRolledBackException
*/
public class TransactionRolledBackException extends JmsException {
public TransactionRolledBackException(javax.jms.TransactionRolledBackException cause) {
super(cause);
}
}
| {
"content_hash": "8a51c36ac3c473725e2fbaa1a537302e",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 88,
"avg_line_length": 22.470588235294116,
"alnum_prop": 0.7958115183246073,
"repo_name": "dachengxi/spring1.1.1_source",
"id": "8cfde399e21bf633cd50a9ee0ae460a4734c9d2b",
"size": "1002",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/org/springframework/jms/TransactionRolledBackException.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "163"
},
{
"name": "FreeMarker",
"bytes": "8024"
},
{
"name": "HTML",
"bytes": "34675"
},
{
"name": "Java",
"bytes": "5934573"
}
],
"symlink_target": ""
} |
namespace UnitTests.Grains
{
using System;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using Orleans.Serialization;
using UnitTests.GrainInterfaces;
public class MessageSerializationGrain : Grain, IMessageSerializationGrain
{
public Task<object> EchoObject(object input) => Task.FromResult(input);
public async Task GetUnserializableObjectChained()
{
// Find a grain on another silo.
IMessageSerializationGrain otherGrain;
var id = this.GetPrimaryKeyLong();
var currentSiloIdentity = await this.GetSiloIdentity();
while (true)
{
otherGrain = this.GrainFactory.GetGrain<IMessageSerializationGrain>(++id);
var otherIdentity = await otherGrain.GetSiloIdentity();
if (!string.Equals(otherIdentity, currentSiloIdentity))
{
break;
}
}
// Message that grain in a way which should fail.
await otherGrain.EchoObject(new SimpleType(35));
}
public Task<string> GetSiloIdentity()
{
return Task.FromResult(this.RuntimeIdentity);
}
}
[Serializable]
public struct SimpleType
{
static SimpleType()
{
SerializationManager.Register(typeof(SimpleType));
}
public SimpleType(int num)
{
this.Number = num;
}
public int Number { get; }
}
/// <summary>
/// Serializer which can serialize <see cref="SimpleType"/> but cannot deserialize it.
/// </summary>
[Serializable]
public class OneWaySerializer : IExternalSerializer
{
public const string FailureMessage = "Can't do it, sorry.";
public void Initialize(Logger logger)
{
}
public bool IsSupportedType(Type itemType) => itemType == typeof(SimpleType);
public object DeepCopy(object source, ICopyContext context)
{
return source;
}
public void Serialize(object item, ISerializationContext context, Type expectedType)
{
var typed = (SimpleType)item;
context.StreamWriter.Write(typed.Number);
}
public object Deserialize(Type expectedType, IDeserializationContext context)
{
throw new NotSupportedException(FailureMessage);
}
}
} | {
"content_hash": "f6eb8effc5989aeb5a510a8aad06e03f",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 92,
"avg_line_length": 28.352272727272727,
"alnum_prop": 0.5955911823647294,
"repo_name": "centur/orleans",
"id": "80b0eb2c691e5d8ff83ad6522197a5bdd10c03cc",
"size": "2497",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/TestGrains/MessageSerializationGrain.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "29232"
},
{
"name": "C#",
"bytes": "7635010"
},
{
"name": "F#",
"bytes": "3764"
},
{
"name": "GLSL",
"bytes": "74"
},
{
"name": "Groovy",
"bytes": "1226"
},
{
"name": "HTML",
"bytes": "234868"
},
{
"name": "PLpgSQL",
"bytes": "53084"
},
{
"name": "PowerShell",
"bytes": "117797"
},
{
"name": "Protocol Buffer",
"bytes": "1683"
},
{
"name": "Smalltalk",
"bytes": "1436"
},
{
"name": "Visual Basic",
"bytes": "22676"
}
],
"symlink_target": ""
} |
//
// SOMusic.m
// SODownloadExample
//
// Created by scfhao on 16/5/3.
// Copyright © 2016年 http://scfhao.coding.me/blog/ All rights reserved.
// SOMusic.{h, m}: 对要下载的模型的封装,示例如何让自己的模型类支持 SODownloader 进行下载。
#import "SOMusic.h"
#import "SOLog.h"
#import "SODownloader.h"
#import "SOSimulateDB.h"
#import "SODownloader+MusicDownloader.h"
@interface SOMusic ()
@property (assign, nonatomic) NSInteger index;
@end
@implementation SOMusic
@synthesize so_downloadProgress, so_downloadState = _so_downloadState, so_downloadError, so_downloadSpeed = _so_downloadSpeed;
// 这个数组模拟应用从网络中获取到一个可下载文件列表
+ (NSArray <SOMusic *>*)allMusicList {
NSMutableArray *musicList = [[NSMutableArray alloc]initWithCapacity:TestMusicCount];
for (NSInteger index = 0; index < TestMusicCount; index++) {
[musicList addObject:[self musicAtIndex:index]];
}
return [musicList copy];
}
+ (instancetype)musicAtIndex:(NSInteger)index {
// 这样可以获取到之前已经添加到 SODownloader 中的一个下载模型
SOMusic *musicAlreadyInDownloader = (SOMusic *)[[SODownloader musicDownloader]filterItemUsingFilter:^BOOL(id<SODownloadItem> _Nonnull item) {
SOMusic *music = (SOMusic *)item;
return music.index == index;
}];
// 判断一下 SODownloader 里是否已经存在一个同样的模型,如果存在就返回那个已有的,不存在就可以重新创建一个
if (musicAlreadyInDownloader) {
return musicAlreadyInDownloader;
} else {
return [[self alloc]initWithIndex:index];
}
}
- (instancetype)initWithIndex:(NSInteger)index {
self = [super init];
if (self) {
self.index = index;
}
return self;
}
- (NSString *)savePath {
return [[[[self class]musicDownloadFolder]stringByAppendingPathComponent:@(self.index).stringValue]stringByAppendingPathExtension:@"mp3"];
}
+ (NSString *)musicDownloadFolder {
NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
NSString *downloadFolder = [documents stringByAppendingPathComponent:@"musics"];
[self handleDownloadFolder:downloadFolder];
return downloadFolder;
}
/// 处理下载文件夹:1.保证文件夹存在。 2.为此文件夹设置备份属性,避免占用过多用户iCloud容量。
+ (void)handleDownloadFolder:(NSString *)folder {
BOOL isDir = NO;
BOOL folderExist = [[NSFileManager defaultManager]fileExistsAtPath:folder isDirectory:&isDir];
if (!folderExist || !isDir) {
[[NSFileManager defaultManager]createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:nil error:nil];
NSURL *fileURL = [NSURL fileURLWithPath:folder];
[fileURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
}
}
- (void)setSo_downloadState:(SODownloadState)so_downloadState {
_so_downloadState = so_downloadState;
switch (so_downloadState) {
case SODownloadStateNormal:
if ([[NSFileManager defaultManager]fileExistsAtPath:[self savePath]]) {
// 清理下载的文件
[[NSFileManager defaultManager]removeItemAtPath:[self savePath] error:nil];
}
break;
default:
break;
}
SOCustomDebugLog(@"<Progress>", @"%@", @(self.so_downloadProgress.fractionCompleted).stringValue);
[SOSimulateDB save:self];
}
#pragma mark - SODownloadItem必须实现的方法
/// 这个方法返回该模型对应的文件的下载地址
- (NSURL *)so_downloadURL {
switch (self.index) {
case 0: return [NSURL URLWithString:@"https://userfilecenter.oss-cn-hangzhou.aliyuncs.com/5c2dacce9bd1160017fb1dc9/ca018999ebed44f19482d74691da8118.mp4"];
case 1: return [NSURL URLWithString:@"https://userfilecenter.oss-cn-hangzhou.aliyuncs.com/5c2e135419b90933783e4127/dc405321267046c1b1d2d6e9d187d0d7.mp4"];
case 2: return [NSURL URLWithString:@"https://userfilecentertest.oss-cn-hangzhou.aliyuncs.com/5caeea8324aa9a000e937be7/8e6ee1b4c0db4f19b4dac4a585c6c35d.mp4"];
default: return nil;
}
}
#pragma mark - SODownloadItem建议实现的方法
/**
实现下面这两个方法用于判断两个对象相等。这两个方法一般不会被直接调用,而是间接的调用,比如在集合(NSArray、NSSet等)中的相关方法(比如indexOfObject、containsObject等)中被间接调用。
了解更多关于这两个方法的内容可以看我写的这个 [WiKi](https://github.com/scfhao/SODownloader/wiki/%E4%BF%9D%E8%AF%81%E4%B8%8B%E8%BD%BD%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%94%AF%E4%B8%80%E6%80%A7)
*/
- (BOOL)isEqual:(id)object {
if (![object isKindOfClass:[SOMusic class]]) {
return [super isEqual:object];
}
// 如果self和object代表同一个对象,比如这两个对象内存地址不同,但是所有的属性值都相等,对于 SODownloader 来说,就是下载地址相同时返回 YES,否则返回 NO。
SOMusic *music = (SOMusic *)object;
return self.index == music.index;
}
/**
为相等的对象返回相同的hash值,为不相等的对象返回不同的hash值。
*/
- (NSUInteger)hash {
return [@(self.index) hash];
}
/**
这个方法和下载没关系,当你在打印一个对象的时候,打印出来的是一个对象的类名和内存地址,没有可读性。实现了这个方法后,当用%@形式打印一个对象,或者用 po 调试命令打印对象时,打印出来的就不再是指针,而是你的 description 方法返回的字符串,这样你就可以知道你的对象的内容。
*/
- (NSString *)description {
return [NSString stringWithFormat:@"[Music:%@]", @(self.index).stringValue];
}
- (instancetype)initWithCoder:(NSCoder *)coder {
self = [super init];
if (self) {
self.index = [coder decodeIntegerForKey:NSStringFromSelector(@selector(index))];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeInteger:self.index forKey:NSStringFromSelector(@selector(index))];
}
@end
| {
"content_hash": "985cfe01b5c617da473806242aa63e1a",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 170,
"avg_line_length": 36.020833333333336,
"alnum_prop": 0.716406400616927,
"repo_name": "scfhao/SODownloader",
"id": "918780d2d382bed785b5395408ba9a8a0b9f0829",
"size": "6190",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Example/SODownloader/SOMusic.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2047"
},
{
"name": "Objective-C",
"bytes": "97813"
},
{
"name": "Ruby",
"bytes": "1769"
}
],
"symlink_target": ""
} |
package net.geocentral.geometria.view;
import java.awt.Frame;
import javax.swing.BoxLayout;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import net.geocentral.geometria.action.GScaleAction;
import net.geocentral.geometria.util.GDictionary;
import net.geocentral.geometria.util.GGraphicsFactory;
import net.geocentral.geometria.util.GValueInputPane;
import net.geocentral.geometria.util.GGraphicsFactory.LocationType;
import org.apache.log4j.Logger;
public class GScaleDialog extends JDialog implements GHelpOkCancelDialog {
private int option = CANCEL_OPTION;
private GScaleAction action;
private JTextField p1TextField;
private JTextField p2TextField;
private GValueInputPane factorInputPane;
private boolean result = false;
private static Logger logger = Logger.getLogger("net.geocentral.geometria");
public GScaleDialog(Frame ownerFrame, GScaleAction action) {
super(ownerFrame, true);
this.action = action;
logger.info("");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setResizable(false);
layoutComponents();
pack();
GGraphicsFactory.getInstance().setLocation(this, ownerFrame, LocationType.CENTER);
setTitle(GDictionary.get("ScaleFigure"));
}
private void layoutComponents() {
logger.info("");
getContentPane().setLayout(
new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
JPanel topPane = GGraphicsFactory.getInstance().createTitledBorderPane(
GDictionary.get("ReferencePoints"));
topPane.setLayout(new BoxLayout(topPane, BoxLayout.X_AXIS));
p1TextField = GGraphicsFactory.getInstance().createLabelInput(null);
JPanel leftInputPane = GGraphicsFactory.getInstance()
.createContainerAdjustBottom(p1TextField);
topPane.add(leftInputPane);
JPanel centerInputPane = GGraphicsFactory.getInstance()
.createImagePane("/images/Scale.png");
topPane.add(centerInputPane);
p2TextField = GGraphicsFactory.getInstance().createLabelInput(null);
JPanel rightInputPane = GGraphicsFactory.getInstance()
.createContainerAdjustBottom(p2TextField);
topPane.add(rightInputPane);
getContentPane().add(topPane);
factorInputPane = GGraphicsFactory.getInstance()
.createVariableInputPane(null, GDictionary.get("ScalingFactor"));
getContentPane().add(factorInputPane);
JPanel helpOkCancelPane = GGraphicsFactory.getInstance()
.createHelpOkCancelPane(this, action.getHelpId());
getContentPane().add(helpOkCancelPane);
}
public void prefill(String pLabel1, String pLabel2) {
logger.info(pLabel1 + ", " + pLabel2);
p1TextField.setText(pLabel1);
p2TextField.setText(pLabel2);
}
public void ok() {
logger.info("");
action.setInput(p1TextField.getText().trim(),
p2TextField.getText().trim(), factorInputPane.getInput());
try {
action.validateApply();
}
catch (Exception exception) {
GGraphicsFactory.getInstance().showErrorDialog(
this, exception.getMessage());
return;
}
option = OK_OPTION;
result = true;
dispose();
}
public void cancel() {
logger.info("");
dispose();
}
public int getOption() {
return option;
}
public boolean getResult() {
return result;
}
private static final long serialVersionUID = 1L;
}
| {
"content_hash": "6780fdcae227d5be41a79b0926c91d85",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 90,
"avg_line_length": 32.92857142857143,
"alnum_prop": 0.6748915401301518,
"repo_name": "stelian56/geometria",
"id": "e7e16361e197bc62a1cd495bd81d1cc71ec87e11",
"size": "3939",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "archive/3.2/src/net/geocentral/geometria/view/GScaleDialog.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "3099"
},
{
"name": "CSS",
"bytes": "12559"
},
{
"name": "HTML",
"bytes": "3587"
},
{
"name": "Haskell",
"bytes": "2310"
},
{
"name": "Java",
"bytes": "2090798"
},
{
"name": "JavaScript",
"bytes": "1279407"
},
{
"name": "PHP",
"bytes": "6915"
},
{
"name": "Shell",
"bytes": "3129"
}
],
"symlink_target": ""
} |
START_ATF_NAMESPACE
typedef _devicemodeW *PDEVMODEW;
END_ATF_NAMESPACE
| {
"content_hash": "f9193688bd19465416b60fb5eed25c55",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 36,
"avg_line_length": 25,
"alnum_prop": 0.7866666666666666,
"repo_name": "goodwinxp/Yorozuya",
"id": "118ecd324ec8d9716c508bec248a87c54ddee40e",
"size": "255",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "library/ATF/PDEVMODEW.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "207291"
},
{
"name": "C++",
"bytes": "21670817"
}
],
"symlink_target": ""
} |
from office365.runtime.queries.create_entity import CreateEntityQuery
from office365.runtime.queries.service_operation import ServiceOperationQuery
from office365.runtime.paths.service_operation import ServiceOperationPath
from office365.sharepoint.base_entity_collection import BaseEntityCollection
from office365.sharepoint.lists.list import List
class ListCollection(BaseEntityCollection):
"""Specifies a collection of lists."""
def __init__(self, context, resource_path=None):
super(ListCollection, self).__init__(context, List, resource_path)
def get_by_title(self, list_title):
"""Retrieve List client object by title
:type list_title: str
"""
return List(self.context,
ServiceOperationPath("GetByTitle", [list_title], self.resource_path))
def get_by_id(self, list_id):
"""
Returns the list with the specified list identifier.
:param str list_id: Specifies the list identifier
"""
return List(self.context,
ServiceOperationPath("GetById", [list_id], self.resource_path))
def ensure_client_rendered_site_pages_library(self):
"""
Returns a list that is designated as a default location for site pages.
"""
return_type = List(self.context)
self.add_child(return_type)
qry = ServiceOperationQuery(self, "EnsureClientRenderedSitePagesLibrary", None, None, None, return_type)
self.context.add_query(qry)
return return_type
def ensure_events_list(self):
"""Returns a list that is designated as a default location for events."""
return_type = List(self.context)
self.add_child(return_type)
qry = ServiceOperationQuery(self, "EnsureEventsList", None, None, None, return_type)
self.context.add_query(qry)
return return_type
def ensure_site_assets_library(self):
"""Gets a list that is the default asset location for images or other files, which the users
upload to their wiki pages."""
return_type = List(self.context)
self.add_child(return_type)
qry = ServiceOperationQuery(self, "ensureSiteAssetsLibrary", None, None, None, return_type)
self.context.add_query(qry)
return return_type
def ensure_site_pages_library(self):
"""Gets a list that is the default location for wiki pages."""
return_type = List(self.context)
self.add_child(return_type)
qry = ServiceOperationQuery(self, "ensureSitePagesLibrary", None, None, None, return_type)
self.context.add_query(qry)
return return_type
def add(self, list_creation_information):
"""Creates a List resource
:type list_creation_information: office365.sharepoint.lists.creation_information.ListCreationInformation
"""
return_type = List(self.context)
self.add_child(return_type)
qry = CreateEntityQuery(self, list_creation_information, return_type)
self.context.add_query(qry)
return return_type
| {
"content_hash": "2817f0a3a36bcafcc1d21491e5d99d15",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 112,
"avg_line_length": 41.14666666666667,
"alnum_prop": 0.6756318859364874,
"repo_name": "vgrem/Office365-REST-Python-Client",
"id": "75f7a1912e90c828d0feaf417f052796f1626fe0",
"size": "3086",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "office365/sharepoint/lists/collection.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "1659292"
}
],
"symlink_target": ""
} |
package com.google.common.reflect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ForwardingSet;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import com.google.common.primitives.Primitives;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A {@link Type} with generics.
*
* <p>Operations that are otherwise only available in {@link Class} are implemented to support
* {@code Type}, for example {@link #isSubtypeOf}, {@link #isArray} and {@link #getComponentType}.
* It also provides additional utilities such as {@link #getTypes}, {@link #resolveType}, etc.
*
* <p>There are three ways to get a {@code TypeToken} instance:
*
* <ul>
* <li>Wrap a {@code Type} obtained via reflection. For example: {@code
* TypeToken.of(method.getGenericReturnType())}.
* <li>Capture a generic type with a (usually anonymous) subclass. For example:
* <pre>{@code
* new TypeToken<List<String>>() {}
* }</pre>
* <p>Note that it's critical that the actual type argument is carried by a subclass. The
* following code is wrong because it only captures the {@code <T>} type variable of the
* {@code listType()} method signature; while {@code <String>} is lost in erasure:
* <pre>{@code
* class Util {
* static <T> TypeToken<List<T>> listType() {
* return new TypeToken<List<T>>() {};
* }
* }
*
* TypeToken<List<String>> stringListType = Util.<String>listType();
* }</pre>
* <li>Capture a generic type with a (usually anonymous) subclass and resolve it against a context
* class that knows what the type parameters are. For example:
* <pre>{@code
* abstract class IKnowMyType<T> {
* TypeToken<T> type = new TypeToken<T>(getClass()) {};
* }
* new IKnowMyType<String>() {}.type => String
* }</pre>
* </ul>
*
* <p>{@code TypeToken} is serializable when no type variable is contained in the type.
*
* <p>Note to Guice users: {@code} TypeToken is similar to Guice's {@code TypeLiteral} class except
* that it is serializable and offers numerous additional utility methods.
*
* @author Bob Lee
* @author Sven Mawson
* @author Ben Yu
* @since 12.0
*/
@Beta
@SuppressWarnings("serial") // SimpleTypeToken is the serialized form.
public abstract class TypeToken<T> extends TypeCapture<T> implements Serializable {
private final Type runtimeType;
/** Resolver for resolving parameter and field types with {@link #runtimeType} as context. */
private transient @Nullable TypeResolver invariantTypeResolver;
/** Resolver for resolving covariant types with {@link #runtimeType} as context. */
private transient @Nullable TypeResolver covariantTypeResolver;
/**
* Constructs a new type token of {@code T}.
*
* <p>Clients create an empty anonymous subclass. Doing so embeds the type parameter in the
* anonymous class's type hierarchy so we can reconstitute it at runtime despite erasure.
*
* <p>For example:
*
* <pre>{@code
* TypeToken<List<String>> t = new TypeToken<List<String>>() {};
* }</pre>
*/
protected TypeToken() {
this.runtimeType = capture();
checkState(
!(runtimeType instanceof TypeVariable),
"Cannot construct a TypeToken for a type variable.\n"
+ "You probably meant to call new TypeToken<%s>(getClass()) "
+ "that can resolve the type variable for you.\n"
+ "If you do need to create a TypeToken of a type variable, "
+ "please use TypeToken.of() instead.",
runtimeType);
}
/**
* Constructs a new type token of {@code T} while resolving free type variables in the context of
* {@code declaringClass}.
*
* <p>Clients create an empty anonymous subclass. Doing so embeds the type parameter in the
* anonymous class's type hierarchy so we can reconstitute it at runtime despite erasure.
*
* <p>For example:
*
* <pre>{@code
* abstract class IKnowMyType<T> {
* TypeToken<T> getMyType() {
* return new TypeToken<T>(getClass()) {};
* }
* }
*
* new IKnowMyType<String>() {}.getMyType() => String
* }</pre>
*/
protected TypeToken(Class<?> declaringClass) {
Type captured = super.capture();
if (captured instanceof Class) {
this.runtimeType = captured;
} else {
this.runtimeType = TypeResolver.covariantly(declaringClass).resolveType(captured);
}
}
private TypeToken(Type type) {
this.runtimeType = checkNotNull(type);
}
/** Returns an instance of type token that wraps {@code type}. */
public static <T> TypeToken<T> of(Class<T> type) {
return new SimpleTypeToken<T>(type);
}
/** Returns an instance of type token that wraps {@code type}. */
public static TypeToken<?> of(Type type) {
return new SimpleTypeToken<>(type);
}
/**
* Returns the raw type of {@code T}. Formally speaking, if {@code T} is returned by {@link
* java.lang.reflect.Method#getGenericReturnType}, the raw type is what's returned by {@link
* java.lang.reflect.Method#getReturnType} of the same method object. Specifically:
*
* <ul>
* <li>If {@code T} is a {@code Class} itself, {@code T} itself is returned.
* <li>If {@code T} is a {@link ParameterizedType}, the raw type of the parameterized type is
* returned.
* <li>If {@code T} is a {@link GenericArrayType}, the returned type is the corresponding array
* class. For example: {@code List<Integer>[] => List[]}.
* <li>If {@code T} is a type variable or a wildcard type, the raw type of the first upper bound
* is returned. For example: {@code <X extends Foo> => Foo}.
* </ul>
*/
public final Class<? super T> getRawType() {
// For wildcard or type variable, the first bound determines the runtime type.
Class<?> rawType = getRawTypes().iterator().next();
@SuppressWarnings("unchecked") // raw type is |T|
Class<? super T> result = (Class<? super T>) rawType;
return result;
}
/** Returns the represented type. */
public final Type getType() {
return runtimeType;
}
/**
* Returns a new {@code TypeToken} where type variables represented by {@code typeParam} are
* substituted by {@code typeArg}. For example, it can be used to construct {@code Map<K, V>} for
* any {@code K} and {@code V} type:
*
* <pre>{@code
* static <K, V> TypeToken<Map<K, V>> mapOf(
* TypeToken<K> keyType, TypeToken<V> valueType) {
* return new TypeToken<Map<K, V>>() {}
* .where(new TypeParameter<K>() {}, keyType)
* .where(new TypeParameter<V>() {}, valueType);
* }
* }</pre>
*
* @param <X> The parameter type
* @param typeParam the parameter type variable
* @param typeArg the actual type to substitute
*/
public final <X> TypeToken<T> where(TypeParameter<X> typeParam, TypeToken<X> typeArg) {
TypeResolver resolver =
new TypeResolver()
.where(
ImmutableMap.of(
new TypeResolver.TypeVariableKey(typeParam.typeVariable), typeArg.runtimeType));
// If there's any type error, we'd report now rather than later.
return new SimpleTypeToken<T>(resolver.resolveType(runtimeType));
}
/**
* Returns a new {@code TypeToken} where type variables represented by {@code typeParam} are
* substituted by {@code typeArg}. For example, it can be used to construct {@code Map<K, V>} for
* any {@code K} and {@code V} type:
*
* <pre>{@code
* static <K, V> TypeToken<Map<K, V>> mapOf(
* Class<K> keyType, Class<V> valueType) {
* return new TypeToken<Map<K, V>>() {}
* .where(new TypeParameter<K>() {}, keyType)
* .where(new TypeParameter<V>() {}, valueType);
* }
* }</pre>
*
* @param <X> The parameter type
* @param typeParam the parameter type variable
* @param typeArg the actual type to substitute
*/
public final <X> TypeToken<T> where(TypeParameter<X> typeParam, Class<X> typeArg) {
return where(typeParam, of(typeArg));
}
/**
* Resolves the given {@code type} against the type context represented by this type. For example:
*
* <pre>{@code
* new TypeToken<List<String>>() {}.resolveType(
* List.class.getMethod("get", int.class).getGenericReturnType())
* => String.class
* }</pre>
*/
public final TypeToken<?> resolveType(Type type) {
checkNotNull(type);
// Being conservative here because the user could use resolveType() to resolve a type in an
// invariant context.
return of(getInvariantTypeResolver().resolveType(type));
}
private TypeToken<?> resolveSupertype(Type type) {
TypeToken<?> supertype = of(getCovariantTypeResolver().resolveType(type));
// super types' type mapping is a subset of type mapping of this type.
supertype.covariantTypeResolver = covariantTypeResolver;
supertype.invariantTypeResolver = invariantTypeResolver;
return supertype;
}
/**
* Returns the generic superclass of this type or {@code null} if the type represents {@link
* Object} or an interface. This method is similar but different from {@link
* Class#getGenericSuperclass}. For example, {@code new TypeToken<StringArrayList>()
* {}.getGenericSuperclass()} will return {@code new TypeToken<ArrayList<String>>() {}}; while
* {@code StringArrayList.class.getGenericSuperclass()} will return {@code ArrayList<E>}, where
* {@code E} is the type variable declared by class {@code ArrayList}.
*
* <p>If this type is a type variable or wildcard, its first upper bound is examined and returned
* if the bound is a class or extends from a class. This means that the returned type could be a
* type variable too.
*/
final @Nullable TypeToken<? super T> getGenericSuperclass() {
if (runtimeType instanceof TypeVariable) {
// First bound is always the super class, if one exists.
return boundAsSuperclass(((TypeVariable<?>) runtimeType).getBounds()[0]);
}
if (runtimeType instanceof WildcardType) {
// wildcard has one and only one upper bound.
return boundAsSuperclass(((WildcardType) runtimeType).getUpperBounds()[0]);
}
Type superclass = getRawType().getGenericSuperclass();
if (superclass == null) {
return null;
}
@SuppressWarnings("unchecked") // super class of T
TypeToken<? super T> superToken = (TypeToken<? super T>) resolveSupertype(superclass);
return superToken;
}
private @Nullable TypeToken<? super T> boundAsSuperclass(Type bound) {
TypeToken<?> token = of(bound);
if (token.getRawType().isInterface()) {
return null;
}
@SuppressWarnings("unchecked") // only upper bound of T is passed in.
TypeToken<? super T> superclass = (TypeToken<? super T>) token;
return superclass;
}
/**
* Returns the generic interfaces that this type directly {@code implements}. This method is
* similar but different from {@link Class#getGenericInterfaces()}. For example, {@code new
* TypeToken<List<String>>() {}.getGenericInterfaces()} will return a list that contains {@code
* new TypeToken<Iterable<String>>() {}}; while {@code List.class.getGenericInterfaces()} will
* return an array that contains {@code Iterable<T>}, where the {@code T} is the type variable
* declared by interface {@code Iterable}.
*
* <p>If this type is a type variable or wildcard, its upper bounds are examined and those that
* are either an interface or upper-bounded only by interfaces are returned. This means that the
* returned types could include type variables too.
*/
final ImmutableList<TypeToken<? super T>> getGenericInterfaces() {
if (runtimeType instanceof TypeVariable) {
return boundsAsInterfaces(((TypeVariable<?>) runtimeType).getBounds());
}
if (runtimeType instanceof WildcardType) {
return boundsAsInterfaces(((WildcardType) runtimeType).getUpperBounds());
}
ImmutableList.Builder<TypeToken<? super T>> builder = ImmutableList.builder();
for (Type interfaceType : getRawType().getGenericInterfaces()) {
@SuppressWarnings("unchecked") // interface of T
TypeToken<? super T> resolvedInterface =
(TypeToken<? super T>) resolveSupertype(interfaceType);
builder.add(resolvedInterface);
}
return builder.build();
}
private ImmutableList<TypeToken<? super T>> boundsAsInterfaces(Type[] bounds) {
ImmutableList.Builder<TypeToken<? super T>> builder = ImmutableList.builder();
for (Type bound : bounds) {
@SuppressWarnings("unchecked") // upper bound of T
TypeToken<? super T> boundType = (TypeToken<? super T>) of(bound);
if (boundType.getRawType().isInterface()) {
builder.add(boundType);
}
}
return builder.build();
}
/**
* Returns the set of interfaces and classes that this type is or is a subtype of. The returned
* types are parameterized with proper type arguments.
*
* <p>Subtypes are always listed before supertypes. But the reverse is not true. A type isn't
* necessarily a subtype of all the types following. Order between types without subtype
* relationship is arbitrary and not guaranteed.
*
* <p>If this type is a type variable or wildcard, upper bounds that are themselves type variables
* aren't included (their super interfaces and superclasses are).
*/
public final TypeSet getTypes() {
return new TypeSet();
}
/**
* Returns the generic form of {@code superclass}. For example, if this is {@code
* ArrayList<String>}, {@code Iterable<String>} is returned given the input {@code
* Iterable.class}.
*/
public final TypeToken<? super T> getSupertype(Class<? super T> superclass) {
checkArgument(
this.someRawTypeIsSubclassOf(superclass),
"%s is not a super class of %s",
superclass,
this);
if (runtimeType instanceof TypeVariable) {
return getSupertypeFromUpperBounds(superclass, ((TypeVariable<?>) runtimeType).getBounds());
}
if (runtimeType instanceof WildcardType) {
return getSupertypeFromUpperBounds(superclass, ((WildcardType) runtimeType).getUpperBounds());
}
if (superclass.isArray()) {
return getArraySupertype(superclass);
}
@SuppressWarnings("unchecked") // resolved supertype
TypeToken<? super T> supertype =
(TypeToken<? super T>) resolveSupertype(toGenericType(superclass).runtimeType);
return supertype;
}
/**
* Returns subtype of {@code this} with {@code subclass} as the raw class. For example, if this is
* {@code Iterable<String>} and {@code subclass} is {@code List}, {@code List<String>} is
* returned.
*/
public final TypeToken<? extends T> getSubtype(Class<?> subclass) {
checkArgument(
!(runtimeType instanceof TypeVariable), "Cannot get subtype of type variable <%s>", this);
if (runtimeType instanceof WildcardType) {
return getSubtypeFromLowerBounds(subclass, ((WildcardType) runtimeType).getLowerBounds());
}
// unwrap array type if necessary
if (isArray()) {
return getArraySubtype(subclass);
}
// At this point, it's either a raw class or parameterized type.
checkArgument(
getRawType().isAssignableFrom(subclass), "%s isn't a subclass of %s", subclass, this);
Type resolvedTypeArgs = resolveTypeArgsForSubclass(subclass);
@SuppressWarnings("unchecked") // guarded by the isAssignableFrom() statement above
TypeToken<? extends T> subtype = (TypeToken<? extends T>) of(resolvedTypeArgs);
checkArgument(
subtype.isSubtypeOf(this), "%s does not appear to be a subtype of %s", subtype, this);
return subtype;
}
/**
* Returns true if this type is a supertype of the given {@code type}. "Supertype" is defined
* according to <a
* href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.5.1">the rules for type
* arguments</a> introduced with Java generics.
*
* @since 19.0
*/
public final boolean isSupertypeOf(TypeToken<?> type) {
return type.isSubtypeOf(getType());
}
/**
* Returns true if this type is a supertype of the given {@code type}. "Supertype" is defined
* according to <a
* href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.5.1">the rules for type
* arguments</a> introduced with Java generics.
*
* @since 19.0
*/
public final boolean isSupertypeOf(Type type) {
return of(type).isSubtypeOf(getType());
}
/**
* Returns true if this type is a subtype of the given {@code type}. "Subtype" is defined
* according to <a
* href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.5.1">the rules for type
* arguments</a> introduced with Java generics.
*
* @since 19.0
*/
public final boolean isSubtypeOf(TypeToken<?> type) {
return isSubtypeOf(type.getType());
}
/**
* Returns true if this type is a subtype of the given {@code type}. "Subtype" is defined
* according to <a
* href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.5.1">the rules for type
* arguments</a> introduced with Java generics.
*
* @since 19.0
*/
public final boolean isSubtypeOf(Type supertype) {
checkNotNull(supertype);
if (supertype instanceof WildcardType) {
// if 'supertype' is <? super Foo>, 'this' can be:
// Foo, SubFoo, <? extends Foo>.
// if 'supertype' is <? extends Foo>, nothing is a subtype.
return any(((WildcardType) supertype).getLowerBounds()).isSupertypeOf(runtimeType);
}
// if 'this' is wildcard, it's a suptype of to 'supertype' if any of its "extends"
// bounds is a subtype of 'supertype'.
if (runtimeType instanceof WildcardType) {
// <? super Base> is of no use in checking 'from' being a subtype of 'to'.
return any(((WildcardType) runtimeType).getUpperBounds()).isSubtypeOf(supertype);
}
// if 'this' is type variable, it's a subtype if any of its "extends"
// bounds is a subtype of 'supertype'.
if (runtimeType instanceof TypeVariable) {
return runtimeType.equals(supertype)
|| any(((TypeVariable<?>) runtimeType).getBounds()).isSubtypeOf(supertype);
}
if (runtimeType instanceof GenericArrayType) {
return of(supertype).isSupertypeOfArray((GenericArrayType) runtimeType);
}
// Proceed to regular Type subtype check
if (supertype instanceof Class) {
return this.someRawTypeIsSubclassOf((Class<?>) supertype);
} else if (supertype instanceof ParameterizedType) {
return this.isSubtypeOfParameterizedType((ParameterizedType) supertype);
} else if (supertype instanceof GenericArrayType) {
return this.isSubtypeOfArrayType((GenericArrayType) supertype);
} else { // to instanceof TypeVariable
return false;
}
}
/**
* Returns true if this type is known to be an array type, such as {@code int[]}, {@code T[]},
* {@code <? extends Map<String, Integer>[]>} etc.
*/
public final boolean isArray() {
return getComponentType() != null;
}
/**
* Returns true if this type is one of the nine primitive types (including {@code void}).
*
* @since 15.0
*/
public final boolean isPrimitive() {
return (runtimeType instanceof Class) && ((Class<?>) runtimeType).isPrimitive();
}
/**
* Returns the corresponding wrapper type if this is a primitive type; otherwise returns {@code
* this} itself. Idempotent.
*
* @since 15.0
*/
public final TypeToken<T> wrap() {
if (isPrimitive()) {
@SuppressWarnings("unchecked") // this is a primitive class
Class<T> type = (Class<T>) runtimeType;
return of(Primitives.wrap(type));
}
return this;
}
private boolean isWrapper() {
return Primitives.allWrapperTypes().contains(runtimeType);
}
/**
* Returns the corresponding primitive type if this is a wrapper type; otherwise returns {@code
* this} itself. Idempotent.
*
* @since 15.0
*/
public final TypeToken<T> unwrap() {
if (isWrapper()) {
@SuppressWarnings("unchecked") // this is a wrapper class
Class<T> type = (Class<T>) runtimeType;
return of(Primitives.unwrap(type));
}
return this;
}
/**
* Returns the array component type if this type represents an array ({@code int[]}, {@code T[]},
* {@code <? extends Map<String, Integer>[]>} etc.), or else {@code null} is returned.
*/
public final @Nullable TypeToken<?> getComponentType() {
Type componentType = Types.getComponentType(runtimeType);
if (componentType == null) {
return null;
}
return of(componentType);
}
/**
* Returns the {@link Invokable} for {@code method}, which must be a member of {@code T}.
*
* @since 14.0
*/
public final Invokable<T, Object> method(Method method) {
checkArgument(
this.someRawTypeIsSubclassOf(method.getDeclaringClass()),
"%s not declared by %s",
method,
this);
return new Invokable.MethodInvokable<T>(method) {
@Override
Type getGenericReturnType() {
return getCovariantTypeResolver().resolveType(super.getGenericReturnType());
}
@Override
Type[] getGenericParameterTypes() {
return getInvariantTypeResolver().resolveTypesInPlace(super.getGenericParameterTypes());
}
@Override
Type[] getGenericExceptionTypes() {
return getCovariantTypeResolver().resolveTypesInPlace(super.getGenericExceptionTypes());
}
@Override
public TypeToken<T> getOwnerType() {
return TypeToken.this;
}
@Override
public String toString() {
return getOwnerType() + "." + super.toString();
}
};
}
/**
* Returns the {@link Invokable} for {@code constructor}, which must be a member of {@code T}.
*
* @since 14.0
*/
public final Invokable<T, T> constructor(Constructor<?> constructor) {
checkArgument(
constructor.getDeclaringClass() == getRawType(),
"%s not declared by %s",
constructor,
getRawType());
return new Invokable.ConstructorInvokable<T>(constructor) {
@Override
Type getGenericReturnType() {
return getCovariantTypeResolver().resolveType(super.getGenericReturnType());
}
@Override
Type[] getGenericParameterTypes() {
return getInvariantTypeResolver().resolveTypesInPlace(super.getGenericParameterTypes());
}
@Override
Type[] getGenericExceptionTypes() {
return getCovariantTypeResolver().resolveTypesInPlace(super.getGenericExceptionTypes());
}
@Override
public TypeToken<T> getOwnerType() {
return TypeToken.this;
}
@Override
public String toString() {
return getOwnerType() + "(" + Joiner.on(", ").join(getGenericParameterTypes()) + ")";
}
};
}
/**
* The set of interfaces and classes that {@code T} is or is a subtype of. {@link Object} is not
* included in the set if this type is an interface.
*
* @since 13.0
*/
public class TypeSet extends ForwardingSet<TypeToken<? super T>> implements Serializable {
private transient @Nullable ImmutableSet<TypeToken<? super T>> types;
TypeSet() {}
/** Returns the types that are interfaces implemented by this type. */
public TypeSet interfaces() {
return new InterfaceSet(this);
}
/** Returns the types that are classes. */
public TypeSet classes() {
return new ClassSet();
}
@Override
protected Set<TypeToken<? super T>> delegate() {
ImmutableSet<TypeToken<? super T>> filteredTypes = types;
if (filteredTypes == null) {
// Java has no way to express ? super T when we parameterize TypeToken vs. Class.
@SuppressWarnings({"unchecked", "rawtypes"})
ImmutableList<TypeToken<? super T>> collectedTypes =
(ImmutableList) TypeCollector.FOR_GENERIC_TYPE.collectTypes(TypeToken.this);
return (types =
FluentIterable.from(collectedTypes)
.filter(TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD)
.toSet());
} else {
return filteredTypes;
}
}
/** Returns the raw types of the types in this set, in the same order. */
public Set<Class<? super T>> rawTypes() {
// Java has no way to express ? super T when we parameterize TypeToken vs. Class.
@SuppressWarnings({"unchecked", "rawtypes"})
ImmutableList<Class<? super T>> collectedTypes =
(ImmutableList) TypeCollector.FOR_RAW_TYPE.collectTypes(getRawTypes());
return ImmutableSet.copyOf(collectedTypes);
}
private static final long serialVersionUID = 0;
}
private final class InterfaceSet extends TypeSet {
private final transient TypeSet allTypes;
private transient @Nullable ImmutableSet<TypeToken<? super T>> interfaces;
InterfaceSet(TypeSet allTypes) {
this.allTypes = allTypes;
}
@Override
protected Set<TypeToken<? super T>> delegate() {
ImmutableSet<TypeToken<? super T>> result = interfaces;
if (result == null) {
return (interfaces =
FluentIterable.from(allTypes).filter(TypeFilter.INTERFACE_ONLY).toSet());
} else {
return result;
}
}
@Override
public TypeSet interfaces() {
return this;
}
@Override
public Set<Class<? super T>> rawTypes() {
// Java has no way to express ? super T when we parameterize TypeToken vs. Class.
@SuppressWarnings({"unchecked", "rawtypes"})
ImmutableList<Class<? super T>> collectedTypes =
(ImmutableList) TypeCollector.FOR_RAW_TYPE.collectTypes(getRawTypes());
return FluentIterable.from(collectedTypes)
.filter(
new Predicate<Class<?>>() {
@Override
public boolean apply(Class<?> type) {
return type.isInterface();
}
})
.toSet();
}
@Override
public TypeSet classes() {
throw new UnsupportedOperationException("interfaces().classes() not supported.");
}
private Object readResolve() {
return getTypes().interfaces();
}
private static final long serialVersionUID = 0;
}
private final class ClassSet extends TypeSet {
private transient @Nullable ImmutableSet<TypeToken<? super T>> classes;
@Override
protected Set<TypeToken<? super T>> delegate() {
ImmutableSet<TypeToken<? super T>> result = classes;
if (result == null) {
@SuppressWarnings({"unchecked", "rawtypes"})
ImmutableList<TypeToken<? super T>> collectedTypes =
(ImmutableList)
TypeCollector.FOR_GENERIC_TYPE.classesOnly().collectTypes(TypeToken.this);
return (classes =
FluentIterable.from(collectedTypes)
.filter(TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD)
.toSet());
} else {
return result;
}
}
@Override
public TypeSet classes() {
return this;
}
@Override
public Set<Class<? super T>> rawTypes() {
// Java has no way to express ? super T when we parameterize TypeToken vs. Class.
@SuppressWarnings({"unchecked", "rawtypes"})
ImmutableList<Class<? super T>> collectedTypes =
(ImmutableList) TypeCollector.FOR_RAW_TYPE.classesOnly().collectTypes(getRawTypes());
return ImmutableSet.copyOf(collectedTypes);
}
@Override
public TypeSet interfaces() {
throw new UnsupportedOperationException("classes().interfaces() not supported.");
}
private Object readResolve() {
return getTypes().classes();
}
private static final long serialVersionUID = 0;
}
private enum TypeFilter implements Predicate<TypeToken<?>> {
IGNORE_TYPE_VARIABLE_OR_WILDCARD {
@Override
public boolean apply(TypeToken<?> type) {
return !(type.runtimeType instanceof TypeVariable
|| type.runtimeType instanceof WildcardType);
}
},
INTERFACE_ONLY {
@Override
public boolean apply(TypeToken<?> type) {
return type.getRawType().isInterface();
}
}
}
/**
* Returns true if {@code o} is another {@code TypeToken} that represents the same {@link Type}.
*/
@Override
public boolean equals(@Nullable Object o) {
if (o instanceof TypeToken) {
TypeToken<?> that = (TypeToken<?>) o;
return runtimeType.equals(that.runtimeType);
}
return false;
}
@Override
public int hashCode() {
return runtimeType.hashCode();
}
@Override
public String toString() {
return Types.toString(runtimeType);
}
/** Implemented to support serialization of subclasses. */
protected Object writeReplace() {
// TypeResolver just transforms the type to our own impls that are Serializable
// except TypeVariable.
return of(new TypeResolver().resolveType(runtimeType));
}
/**
* Ensures that this type token doesn't contain type variables, which can cause unchecked type
* errors for callers like {@link TypeToInstanceMap}.
*/
@CanIgnoreReturnValue
final TypeToken<T> rejectTypeVariables() {
new TypeVisitor() {
@Override
void visitTypeVariable(TypeVariable<?> type) {
throw new IllegalArgumentException(
runtimeType + "contains a type variable and is not safe for the operation");
}
@Override
void visitWildcardType(WildcardType type) {
visit(type.getLowerBounds());
visit(type.getUpperBounds());
}
@Override
void visitParameterizedType(ParameterizedType type) {
visit(type.getActualTypeArguments());
visit(type.getOwnerType());
}
@Override
void visitGenericArrayType(GenericArrayType type) {
visit(type.getGenericComponentType());
}
}.visit(runtimeType);
return this;
}
private boolean someRawTypeIsSubclassOf(Class<?> superclass) {
for (Class<?> rawType : getRawTypes()) {
if (superclass.isAssignableFrom(rawType)) {
return true;
}
}
return false;
}
private boolean isSubtypeOfParameterizedType(ParameterizedType supertype) {
Class<?> matchedClass = of(supertype).getRawType();
if (!someRawTypeIsSubclassOf(matchedClass)) {
return false;
}
TypeVariable<?>[] typeVars = matchedClass.getTypeParameters();
Type[] supertypeArgs = supertype.getActualTypeArguments();
for (int i = 0; i < typeVars.length; i++) {
Type subtypeParam = getCovariantTypeResolver().resolveType(typeVars[i]);
// If 'supertype' is "List<? extends CharSequence>"
// and 'this' is StringArrayList,
// First step is to figure out StringArrayList "is-a" List<E> where <E> = String.
// String is then matched against <? extends CharSequence>, the supertypeArgs[0].
if (!of(subtypeParam).is(supertypeArgs[i], typeVars[i])) {
return false;
}
}
// We only care about the case when the supertype is a non-static inner class
// in which case we need to make sure the subclass's owner type is a subtype of the
// supertype's owner.
return Modifier.isStatic(((Class<?>) supertype.getRawType()).getModifiers())
|| supertype.getOwnerType() == null
|| isOwnedBySubtypeOf(supertype.getOwnerType());
}
private boolean isSubtypeOfArrayType(GenericArrayType supertype) {
if (runtimeType instanceof Class) {
Class<?> fromClass = (Class<?>) runtimeType;
if (!fromClass.isArray()) {
return false;
}
return of(fromClass.getComponentType()).isSubtypeOf(supertype.getGenericComponentType());
} else if (runtimeType instanceof GenericArrayType) {
GenericArrayType fromArrayType = (GenericArrayType) runtimeType;
return of(fromArrayType.getGenericComponentType())
.isSubtypeOf(supertype.getGenericComponentType());
} else {
return false;
}
}
private boolean isSupertypeOfArray(GenericArrayType subtype) {
if (runtimeType instanceof Class) {
Class<?> thisClass = (Class<?>) runtimeType;
if (!thisClass.isArray()) {
return thisClass.isAssignableFrom(Object[].class);
}
return of(subtype.getGenericComponentType()).isSubtypeOf(thisClass.getComponentType());
} else if (runtimeType instanceof GenericArrayType) {
return of(subtype.getGenericComponentType())
.isSubtypeOf(((GenericArrayType) runtimeType).getGenericComponentType());
} else {
return false;
}
}
/**
* {@code A.is(B)} is defined as {@code Foo<A>.isSubtypeOf(Foo<B>)}.
*
* <p>Specifically, returns true if any of the following conditions is met:
*
* <ol>
* <li>'this' and {@code formalType} are equal.
* <li>'this' and {@code formalType} have equal canonical form.
* <li>{@code formalType} is {@code <? extends Foo>} and 'this' is a subtype of {@code Foo}.
* <li>{@code formalType} is {@code <? super Foo>} and 'this' is a supertype of {@code Foo}.
* </ol>
*
* Note that condition 2 isn't technically accurate under the context of a recursively bounded
* type variables. For example, {@code Enum<? extends Enum<E>>} canonicalizes to {@code Enum<?>}
* where {@code E} is the type variable declared on the {@code Enum} class declaration. It's
* technically <em>not</em> true that {@code Foo<Enum<? extends Enum<E>>>} is a subtype of {@code
* Foo<Enum<?>>} according to JLS. See testRecursiveWildcardSubtypeBug() for a real example.
*
* <p>It appears that properly handling recursive type bounds in the presence of implicit type
* bounds is not easy. For now we punt, hoping that this defect should rarely cause issues in real
* code.
*
* @param formalType is {@code Foo<formalType>} a supertype of {@code Foo<T>}?
* @param declaration The type variable in the context of a parameterized type. Used to infer type
* bound when {@code formalType} is a wildcard with implicit upper bound.
*/
private boolean is(Type formalType, TypeVariable<?> declaration) {
if (runtimeType.equals(formalType)) {
return true;
}
if (formalType instanceof WildcardType) {
WildcardType your = canonicalizeWildcardType(declaration, (WildcardType) formalType);
// if "formalType" is <? extends Foo>, "this" can be:
// Foo, SubFoo, <? extends Foo>, <? extends SubFoo>, <T extends Foo> or
// <T extends SubFoo>.
// if "formalType" is <? super Foo>, "this" can be:
// Foo, SuperFoo, <? super Foo> or <? super SuperFoo>.
return every(your.getUpperBounds()).isSupertypeOf(runtimeType)
&& every(your.getLowerBounds()).isSubtypeOf(runtimeType);
}
return canonicalizeWildcardsInType(runtimeType).equals(canonicalizeWildcardsInType(formalType));
}
/**
* In reflection, {@code Foo<?>.getUpperBounds()[0]} is always {@code Object.class}, even when Foo
* is defined as {@code Foo<T extends String>}. Thus directly calling {@code <?>.is(String.class)}
* will return false. To mitigate, we canonicalize wildcards by enforcing the following
* invariants:
*
* <ol>
* <li>{@code canonicalize(t)} always produces the equal result for equivalent types. For
* example both {@code Enum<?>} and {@code Enum<? extends Enum<?>>} canonicalize to {@code
* Enum<? extends Enum<E>}.
* <li>{@code canonicalize(t)} produces a "literal" supertype of t. For example: {@code Enum<?
* extends Enum<?>>} canonicalizes to {@code Enum<?>}, which is a supertype (if we disregard
* the upper bound is implicitly an Enum too).
* <li>If {@code canonicalize(A) == canonicalize(B)}, then {@code Foo<A>.isSubtypeOf(Foo<B>)}
* and vice versa. i.e. {@code A.is(B)} and {@code B.is(A)}.
* <li>{@code canonicalize(canonicalize(A)) == canonicalize(A)}.
* </ol>
*/
private static Type canonicalizeTypeArg(TypeVariable<?> declaration, Type typeArg) {
return typeArg instanceof WildcardType
? canonicalizeWildcardType(declaration, ((WildcardType) typeArg))
: canonicalizeWildcardsInType(typeArg);
}
private static Type canonicalizeWildcardsInType(Type type) {
if (type instanceof ParameterizedType) {
return canonicalizeWildcardsInParameterizedType((ParameterizedType) type);
}
if (type instanceof GenericArrayType) {
return Types.newArrayType(
canonicalizeWildcardsInType(((GenericArrayType) type).getGenericComponentType()));
}
return type;
}
// WARNING: the returned type may have empty upper bounds, which may violate common expectations
// by user code or even some of our own code. It's fine for the purpose of checking subtypes.
// Just don't ever let the user access it.
private static WildcardType canonicalizeWildcardType(
TypeVariable<?> declaration, WildcardType type) {
Type[] declared = declaration.getBounds();
List<Type> upperBounds = new ArrayList<>();
for (Type bound : type.getUpperBounds()) {
if (!any(declared).isSubtypeOf(bound)) {
upperBounds.add(canonicalizeWildcardsInType(bound));
}
}
return new Types.WildcardTypeImpl(type.getLowerBounds(), upperBounds.toArray(new Type[0]));
}
private static ParameterizedType canonicalizeWildcardsInParameterizedType(
ParameterizedType type) {
Class<?> rawType = (Class<?>) type.getRawType();
TypeVariable<?>[] typeVars = rawType.getTypeParameters();
Type[] typeArgs = type.getActualTypeArguments();
for (int i = 0; i < typeArgs.length; i++) {
typeArgs[i] = canonicalizeTypeArg(typeVars[i], typeArgs[i]);
}
return Types.newParameterizedTypeWithOwner(type.getOwnerType(), rawType, typeArgs);
}
private static Bounds every(Type[] bounds) {
// Every bound must match. On any false, result is false.
return new Bounds(bounds, false);
}
private static Bounds any(Type[] bounds) {
// Any bound matches. On any true, result is true.
return new Bounds(bounds, true);
}
private static class Bounds {
private final Type[] bounds;
private final boolean target;
Bounds(Type[] bounds, boolean target) {
this.bounds = bounds;
this.target = target;
}
boolean isSubtypeOf(Type supertype) {
for (Type bound : bounds) {
if (of(bound).isSubtypeOf(supertype) == target) {
return target;
}
}
return !target;
}
boolean isSupertypeOf(Type subtype) {
TypeToken<?> type = of(subtype);
for (Type bound : bounds) {
if (type.isSubtypeOf(bound) == target) {
return target;
}
}
return !target;
}
}
private ImmutableSet<Class<? super T>> getRawTypes() {
final ImmutableSet.Builder<Class<?>> builder = ImmutableSet.builder();
new TypeVisitor() {
@Override
void visitTypeVariable(TypeVariable<?> t) {
visit(t.getBounds());
}
@Override
void visitWildcardType(WildcardType t) {
visit(t.getUpperBounds());
}
@Override
void visitParameterizedType(ParameterizedType t) {
builder.add((Class<?>) t.getRawType());
}
@Override
void visitClass(Class<?> t) {
builder.add(t);
}
@Override
void visitGenericArrayType(GenericArrayType t) {
builder.add(Types.getArrayClass(of(t.getGenericComponentType()).getRawType()));
}
}.visit(runtimeType);
// Cast from ImmutableSet<Class<?>> to ImmutableSet<Class<? super T>>
@SuppressWarnings({"unchecked", "rawtypes"})
ImmutableSet<Class<? super T>> result = (ImmutableSet) builder.build();
return result;
}
private boolean isOwnedBySubtypeOf(Type supertype) {
for (TypeToken<?> type : getTypes()) {
Type ownerType = type.getOwnerTypeIfPresent();
if (ownerType != null && of(ownerType).isSubtypeOf(supertype)) {
return true;
}
}
return false;
}
/**
* Returns the owner type of a {@link ParameterizedType} or enclosing class of a {@link Class}, or
* null otherwise.
*/
private @Nullable Type getOwnerTypeIfPresent() {
if (runtimeType instanceof ParameterizedType) {
return ((ParameterizedType) runtimeType).getOwnerType();
} else if (runtimeType instanceof Class<?>) {
return ((Class<?>) runtimeType).getEnclosingClass();
} else {
return null;
}
}
/**
* Returns the type token representing the generic type declaration of {@code cls}. For example:
* {@code TypeToken.getGenericType(Iterable.class)} returns {@code Iterable<T>}.
*
* <p>If {@code cls} isn't parameterized and isn't a generic array, the type token of the class is
* returned.
*/
@VisibleForTesting
static <T> TypeToken<? extends T> toGenericType(Class<T> cls) {
if (cls.isArray()) {
Type arrayOfGenericType =
Types.newArrayType(
// If we are passed with int[].class, don't turn it to GenericArrayType
toGenericType(cls.getComponentType()).runtimeType);
@SuppressWarnings("unchecked") // array is covariant
TypeToken<? extends T> result = (TypeToken<? extends T>) of(arrayOfGenericType);
return result;
}
TypeVariable<Class<T>>[] typeParams = cls.getTypeParameters();
Type ownerType =
cls.isMemberClass() && !Modifier.isStatic(cls.getModifiers())
? toGenericType(cls.getEnclosingClass()).runtimeType
: null;
if ((typeParams.length > 0) || ((ownerType != null) && ownerType != cls.getEnclosingClass())) {
@SuppressWarnings("unchecked") // Like, it's Iterable<T> for Iterable.class
TypeToken<? extends T> type =
(TypeToken<? extends T>)
of(Types.newParameterizedTypeWithOwner(ownerType, cls, typeParams));
return type;
} else {
return of(cls);
}
}
private TypeResolver getCovariantTypeResolver() {
TypeResolver resolver = covariantTypeResolver;
if (resolver == null) {
resolver = (covariantTypeResolver = TypeResolver.covariantly(runtimeType));
}
return resolver;
}
private TypeResolver getInvariantTypeResolver() {
TypeResolver resolver = invariantTypeResolver;
if (resolver == null) {
resolver = (invariantTypeResolver = TypeResolver.invariantly(runtimeType));
}
return resolver;
}
private TypeToken<? super T> getSupertypeFromUpperBounds(
Class<? super T> supertype, Type[] upperBounds) {
for (Type upperBound : upperBounds) {
@SuppressWarnings("unchecked") // T's upperbound is <? super T>.
TypeToken<? super T> bound = (TypeToken<? super T>) of(upperBound);
if (bound.isSubtypeOf(supertype)) {
@SuppressWarnings({"rawtypes", "unchecked"}) // guarded by the isSubtypeOf check.
TypeToken<? super T> result = bound.getSupertype((Class) supertype);
return result;
}
}
throw new IllegalArgumentException(supertype + " isn't a super type of " + this);
}
private TypeToken<? extends T> getSubtypeFromLowerBounds(Class<?> subclass, Type[] lowerBounds) {
if (lowerBounds.length > 0) {
@SuppressWarnings("unchecked") // T's lower bound is <? extends T>
TypeToken<? extends T> bound = (TypeToken<? extends T>) of(lowerBounds[0]);
// Java supports only one lowerbound anyway.
return bound.getSubtype(subclass);
}
throw new IllegalArgumentException(subclass + " isn't a subclass of " + this);
}
private TypeToken<? super T> getArraySupertype(Class<? super T> supertype) {
// with component type, we have lost generic type information
// Use raw type so that compiler allows us to call getSupertype()
@SuppressWarnings("rawtypes")
TypeToken componentType =
checkNotNull(getComponentType(), "%s isn't a super type of %s", supertype, this);
// array is covariant. component type is super type, so is the array type.
@SuppressWarnings("unchecked") // going from raw type back to generics
TypeToken<?> componentSupertype = componentType.getSupertype(supertype.getComponentType());
@SuppressWarnings("unchecked") // component type is super type, so is array type.
TypeToken<? super T> result =
(TypeToken<? super T>)
// If we are passed with int[].class, don't turn it to GenericArrayType
of(newArrayClassOrGenericArrayType(componentSupertype.runtimeType));
return result;
}
private TypeToken<? extends T> getArraySubtype(Class<?> subclass) {
// array is covariant. component type is subtype, so is the array type.
TypeToken<?> componentSubtype = getComponentType().getSubtype(subclass.getComponentType());
@SuppressWarnings("unchecked") // component type is subtype, so is array type.
TypeToken<? extends T> result =
(TypeToken<? extends T>)
// If we are passed with int[].class, don't turn it to GenericArrayType
of(newArrayClassOrGenericArrayType(componentSubtype.runtimeType));
return result;
}
private Type resolveTypeArgsForSubclass(Class<?> subclass) {
// If both runtimeType and subclass are not parameterized, return subclass
// If runtimeType is not parameterized but subclass is, process subclass as a parameterized type
// If runtimeType is a raw type (i.e. is a parameterized type specified as a Class<?>), we
// return subclass as a raw type
if (runtimeType instanceof Class
&& ((subclass.getTypeParameters().length == 0)
|| (getRawType().getTypeParameters().length != 0))) {
// no resolution needed
return subclass;
}
// class Base<A, B> {}
// class Sub<X, Y> extends Base<X, Y> {}
// Base<String, Integer>.subtype(Sub.class):
// Sub<X, Y>.getSupertype(Base.class) => Base<X, Y>
// => X=String, Y=Integer
// => Sub<X, Y>=Sub<String, Integer>
TypeToken<?> genericSubtype = toGenericType(subclass);
@SuppressWarnings({"rawtypes", "unchecked"}) // subclass isn't <? extends T>
Type supertypeWithArgsFromSubtype =
genericSubtype.getSupertype((Class) getRawType()).runtimeType;
return new TypeResolver()
.where(supertypeWithArgsFromSubtype, runtimeType)
.resolveType(genericSubtype.runtimeType);
}
/**
* Creates an array class if {@code componentType} is a class, or else, a {@link
* GenericArrayType}. This is what Java7 does for generic array type parameters.
*/
private static Type newArrayClassOrGenericArrayType(Type componentType) {
return Types.JavaVersion.JAVA7.newArrayType(componentType);
}
private static final class SimpleTypeToken<T> extends TypeToken<T> {
SimpleTypeToken(Type type) {
super(type);
}
private static final long serialVersionUID = 0;
}
/**
* Collects parent types from a sub type.
*
* @param <K> The type "kind". Either a TypeToken, or Class.
*/
private abstract static class TypeCollector<K> {
static final TypeCollector<TypeToken<?>> FOR_GENERIC_TYPE =
new TypeCollector<TypeToken<?>>() {
@Override
Class<?> getRawType(TypeToken<?> type) {
return type.getRawType();
}
@Override
Iterable<? extends TypeToken<?>> getInterfaces(TypeToken<?> type) {
return type.getGenericInterfaces();
}
@Override
@Nullable
TypeToken<?> getSuperclass(TypeToken<?> type) {
return type.getGenericSuperclass();
}
};
static final TypeCollector<Class<?>> FOR_RAW_TYPE =
new TypeCollector<Class<?>>() {
@Override
Class<?> getRawType(Class<?> type) {
return type;
}
@Override
Iterable<? extends Class<?>> getInterfaces(Class<?> type) {
return Arrays.asList(type.getInterfaces());
}
@Override
@Nullable
Class<?> getSuperclass(Class<?> type) {
return type.getSuperclass();
}
};
/** For just classes, we don't have to traverse interfaces. */
final TypeCollector<K> classesOnly() {
return new ForwardingTypeCollector<K>(this) {
@Override
Iterable<? extends K> getInterfaces(K type) {
return ImmutableSet.of();
}
@Override
ImmutableList<K> collectTypes(Iterable<? extends K> types) {
ImmutableList.Builder<K> builder = ImmutableList.builder();
for (K type : types) {
if (!getRawType(type).isInterface()) {
builder.add(type);
}
}
return super.collectTypes(builder.build());
}
};
}
final ImmutableList<K> collectTypes(K type) {
return collectTypes(ImmutableList.of(type));
}
ImmutableList<K> collectTypes(Iterable<? extends K> types) {
// type -> order number. 1 for Object, 2 for anything directly below, so on so forth.
Map<K, Integer> map = Maps.newHashMap();
for (K type : types) {
collectTypes(type, map);
}
return sortKeysByValue(map, Ordering.natural().reverse());
}
/** Collects all types to map, and returns the total depth from T up to Object. */
@CanIgnoreReturnValue
private int collectTypes(K type, Map<? super K, Integer> map) {
Integer existing = map.get(type);
if (existing != null) {
// short circuit: if set contains type it already contains its supertypes
return existing;
}
// Interfaces should be listed before Object.
int aboveMe = getRawType(type).isInterface() ? 1 : 0;
for (K interfaceType : getInterfaces(type)) {
aboveMe = Math.max(aboveMe, collectTypes(interfaceType, map));
}
K superclass = getSuperclass(type);
if (superclass != null) {
aboveMe = Math.max(aboveMe, collectTypes(superclass, map));
}
/*
* TODO(benyu): should we include Object for interface? Also, CharSequence[] and Object[] for
* String[]?
*
*/
map.put(type, aboveMe + 1);
return aboveMe + 1;
}
private static <K, V> ImmutableList<K> sortKeysByValue(
final Map<K, V> map, final Comparator<? super V> valueComparator) {
Ordering<K> keyOrdering =
new Ordering<K>() {
@Override
public int compare(K left, K right) {
return valueComparator.compare(map.get(left), map.get(right));
}
};
return keyOrdering.immutableSortedCopy(map.keySet());
}
abstract Class<?> getRawType(K type);
abstract Iterable<? extends K> getInterfaces(K type);
abstract @Nullable K getSuperclass(K type);
private static class ForwardingTypeCollector<K> extends TypeCollector<K> {
private final TypeCollector<K> delegate;
ForwardingTypeCollector(TypeCollector<K> delegate) {
this.delegate = delegate;
}
@Override
Class<?> getRawType(K type) {
return delegate.getRawType(type);
}
@Override
Iterable<? extends K> getInterfaces(K type) {
return delegate.getInterfaces(type);
}
@Override
K getSuperclass(K type) {
return delegate.getSuperclass(type);
}
}
}
// This happens to be the hash of the class as of now. So setting it makes a backward compatible
// change. Going forward, if any incompatible change is added, we can change the UID back to 1.
private static final long serialVersionUID = 3637540370352322684L;
}
| {
"content_hash": "7cf49da05c3de371ad25bb30ebfb8ec7",
"timestamp": "",
"source": "github",
"line_count": 1429,
"max_line_length": 100,
"avg_line_length": 36.89223233030091,
"alnum_prop": 0.6583015611070012,
"repo_name": "typetools/guava",
"id": "88deff3f4f10df9e2517c483936970e6ebcbeab6",
"size": "53313",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "guava/src/com/google/common/reflect/TypeToken.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "11478"
},
{
"name": "Java",
"bytes": "26145170"
},
{
"name": "Shell",
"bytes": "4096"
}
],
"symlink_target": ""
} |
package org.elasticsearch.xpack.ml.job.persistence;
import org.elasticsearch.client.Client;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.xpack.core.ClientHelper;
import org.elasticsearch.xpack.core.ml.job.results.Result;
import org.elasticsearch.xpack.ml.test.MockOriginSettingClient;
import java.util.Deque;
import java.util.List;
import java.util.NoSuchElementException;
import static org.mockito.Mockito.mock;
public class MockBatchedDocumentsIterator<T> extends BatchedResultsIterator<T> {
private final List<Deque<Result<T>>> batches;
private int index;
private boolean wasTimeRangeCalled;
private Boolean includeInterim;
private Boolean requireIncludeInterim;
public MockBatchedDocumentsIterator(List<Deque<Result<T>>> batches, String resultType) {
super(MockOriginSettingClient.mockOriginSettingClient(mock(Client.class), ClientHelper.ML_ORIGIN), "foo", resultType);
this.batches = batches;
index = 0;
wasTimeRangeCalled = false;
}
@Override
public BatchedResultsIterator<T> timeRange(long startEpochMs, long endEpochMs) {
wasTimeRangeCalled = true;
return this;
}
@Override
public BatchedResultsIterator<T> includeInterim(boolean includeInterim) {
this.includeInterim = includeInterim;
return this;
}
@Override
public Deque<Result<T>> next() {
if (requireIncludeInterim != null && requireIncludeInterim != includeInterim) {
throw new IllegalStateException(
"Required include interim value [" + requireIncludeInterim + "]; actual was [" + includeInterim + "]"
);
}
if (wasTimeRangeCalled == false || hasNext() == false) {
throw new NoSuchElementException();
}
return batches.get(index++);
}
@Override
protected Result<T> map(SearchHit hit) {
return null;
}
@Override
public boolean hasNext() {
return index != batches.size();
}
@Nullable
public Boolean isIncludeInterim() {
return includeInterim;
}
public void requireIncludeInterim(boolean value) {
this.requireIncludeInterim = value;
}
}
| {
"content_hash": "7b5b75b094b0f831b5ab4505bb7b63e4",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 126,
"avg_line_length": 30.266666666666666,
"alnum_prop": 0.690748898678414,
"repo_name": "GlenRSmith/elasticsearch",
"id": "99f542f88fb60535e800760de5b3f7d9dcadcdc2",
"size": "2522",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/persistence/MockBatchedDocumentsIterator.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "11082"
},
{
"name": "Batchfile",
"bytes": "11057"
},
{
"name": "Emacs Lisp",
"bytes": "3341"
},
{
"name": "FreeMarker",
"bytes": "45"
},
{
"name": "Groovy",
"bytes": "337461"
},
{
"name": "HTML",
"bytes": "2186"
},
{
"name": "Java",
"bytes": "43224931"
},
{
"name": "Perl",
"bytes": "11756"
},
{
"name": "Python",
"bytes": "19852"
},
{
"name": "Shell",
"bytes": "99571"
}
],
"symlink_target": ""
} |
'use strict';
/* global angular */
(function() {
var homepage = angular.module('homepage');
homepage.controller('HomepageController', function($rootScope, $scope, $state, sessionFactory) {
$scope.stateName = 'homepage';
$scope.email = '';
$scope.password = '';
$scope.registerAndLogin = function() {
var user = { };
user.email = $scope.email;
user.password = $scope.password;
sessionFactory.registerAndLogin(user)
.then(function() {
$state.go('app-root.list');
});
};
});
})();
| {
"content_hash": "5a794e713a2fed69fde2dd1ec56672dc",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 97,
"avg_line_length": 19.296296296296298,
"alnum_prop": 0.6295585412667947,
"repo_name": "LAzzam2/tradeTracker-client",
"id": "11c161d36d4058f80e156c7708d6c25675fdfa42",
"size": "521",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/states/homepage/homepage_controller.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "24771"
},
{
"name": "CSS",
"bytes": "17018"
},
{
"name": "HTML",
"bytes": "11150"
},
{
"name": "JavaScript",
"bytes": "63095"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from django.test import TestCase
from ..models import Panoply
class CompilerTest(TestCase):
def setUp(self):
self.panoply = Panoply.objects.create()
def test_noop(self):
pass
def tearDown(self):
pass
| {
"content_hash": "eddf0665f7fc8936868898cb58f01564",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 47,
"avg_line_length": 16.647058823529413,
"alnum_prop": 0.6643109540636042,
"repo_name": "peterlandry/django-ember-models",
"id": "a744995558a2e7e6d8cd2f571b37fe5f0b97e690",
"size": "283",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/tests/test.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "0"
},
{
"name": "Python",
"bytes": "4724"
}
],
"symlink_target": ""
} |
import { resolve as resolvePath } from "path";
import { compileFile } from "pug";
// disable debugging for compiled functions
const pugOptions = { debug: false, compileDebug: false };
// compiled synchronous functions to generate dynamic metadata
const genSync = {
pkgOpf: compileFile(
resolvePath(__dirname, "templates", "package.opf.pug"),
pugOptions
),
tocNcx: compileFile(
resolvePath(__dirname, "templates", "toc.ncx.pug"),
pugOptions
),
tocXhtml: compileFile(
resolvePath(__dirname, "templates", "toc.xhtml.pug"),
pugOptions
)
};
const generate = {
tocXhtml(data) {
return new Promise((resolve, reject) => {
// simple error checking
if (typeof data.title !== "string") {
return reject(new Error("title is not a string"));
} else if (!Array.isArray(data.chapters)) {
return reject(new Error("chapters is not an array"));
} else if (data.title.length === 0) {
return reject(new Error("title has zero length"));
} else if (data.chapters.length === 0) {
return reject(new Error("chapters has zero length"));
} else if (
!data.chapters.every(
chapter =>
typeof chapter.title === "string" &&
typeof chapter.name === "string"
)
) {
return reject(
new Error("chapters are missing properties: title, fileName")
);
}
// generate toc.xhtml
const tocXHTML = genSync.tocXhtml({
title: data.title,
chapters: data.chapters
});
return resolve(tocXHTML);
});
},
tocNcx(data) {
return new Promise((resolve, reject) => {
// simple error checking
if (typeof data.title !== "string") {
return reject(new Error("title is not a string"));
} else if (typeof data.id !== "string") {
return reject(new Error("id is not a string"));
} else if (typeof data.language !== "string") {
return reject(new Error("language is not a string"));
} else if (typeof data.generator !== "string") {
return reject(new Error("generator is not a string"));
} else if (!Array.isArray(data.author)) {
return reject(new Error("author is not an array"));
} else if (!Array.isArray(data.chapters)) {
return reject(new Error("chapters is not an array"));
} else if (data.title.length === 0) {
return reject(new Error("title has zero length"));
} else if (data.id.length === 0) {
return reject(new Error("id has zero length"));
} else if (data.language.length === 0) {
return reject(new Error("language has zero length"));
} else if (data.generator.length === 0) {
return reject(new Error("generator has zero length"));
} else if (data.author.length === 0) {
return reject(new Error("author has zero length"));
} else if (data.chapters.length === 0) {
return reject(new Error("chapters has zero length"));
} else if (
!data.chapters.every(
chapter =>
typeof chapter.title === "string" &&
typeof chapter.name === "string"
)
) {
return reject(
new Error("chapters are missing properties: title, fileName")
);
}
// generate toc.ncx
const tocNCX = genSync.tocNcx({
language: data.language,
generator: data.generator,
id: data.id,
title: data.title,
author: data.author,
chapters: data.chapters
});
return resolve(tocNCX);
});
},
pkgOpf(data) {
return new Promise((resolve, reject) => {
// simple error checking
// generate package.opf
const packageOPF = genSync.pkgOpf({
language: data.language,
id: data.id,
title: data.title,
author: data.author,
dates: data.dates,
publisher: data.publisher,
description: data.description,
identifiers: data.identifiers,
chapters: data.chapters
});
return resolve(packageOPF);
});
}
};
const generateMetadata = options =>
new Promise((resolve, reject) => {
Promise.all([
generate.pkgOpf(options),
generate.tocXhtml(options),
generate.tocNcx(options)
])
.then(([packageOPF, tocXHTML, tocNCX]) => {
// generate metadata property & append relevant metadata
options.metadata = {};
options.metadata.packageOPF = packageOPF;
options.metadata.tocXHTML = tocXHTML;
options.metadata.tocNCX = tocNCX;
resolve(options);
})
.catch(e => reject(e));
});
export default {
generate,
generateMetadata
};
| {
"content_hash": "4b1e33a9b4be6bd709a4a843fbfdc828",
"timestamp": "",
"source": "github",
"line_count": 149,
"max_line_length": 71,
"avg_line_length": 31.48993288590604,
"alnum_prop": 0.5869565217391305,
"repo_name": "grawlinson/quick-epub",
"id": "9f84a09096af4a284ccdac118e8dda3e292066ef",
"size": "4692",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/metadata.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "3950"
},
{
"name": "JavaScript",
"bytes": "28641"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="./../../helpwin.css">
<title>MATLAB File Help: prtClassDlrt/name</title>
</head>
<body>
<!--Single-page help-->
<table border="0" cellspacing="0" width="100%">
<tr class="subheader">
<td class="headertitle">MATLAB File Help: prtClassDlrt/name</td>
</tr>
</table>
<div class="title">prtClassDlrt/name</div>
<div class="helptext"><pre><!--helptext --> name - Distance Likelihood Ratio Test</pre></div><!--after help -->
<!--Property-->
<div class="sectiontitle">Property Details</div>
<table class="class-details">
<tr>
<td class="class-detail-label">Constant</td>
<td>false</td>
</tr>
<tr>
<td class="class-detail-label">Dependent</td>
<td>false</td>
</tr>
<tr>
<td class="class-detail-label">Sealed</td>
<td>false</td>
</tr>
<tr>
<td class="class-detail-label">Transient</td>
<td>false</td>
</tr>
<tr>
<td class="class-detail-label">GetAccess</td>
<td>public</td>
</tr>
<tr>
<td class="class-detail-label">SetAccess</td>
<td>private</td>
</tr>
<tr>
<td class="class-detail-label">GetObservable</td>
<td>false</td>
</tr>
<tr>
<td class="class-detail-label">SetObservable</td>
<td>false</td>
</tr>
</table>
</body>
</html> | {
"content_hash": "a7904961e4c4a6d74fa97852dd1b3152",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 118,
"avg_line_length": 30.571428571428573,
"alnum_prop": 0.48189252336448596,
"repo_name": "covartech/PRT",
"id": "9918dc4916a52e3c5ba3f729401394490e1f6e86",
"size": "1712",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "doc/functionReference/prtClassDlrt/name.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "55270"
},
{
"name": "C++",
"bytes": "66966"
},
{
"name": "HTML",
"bytes": "7962"
},
{
"name": "M",
"bytes": "9170"
},
{
"name": "MATLAB",
"bytes": "2421942"
},
{
"name": "Makefile",
"bytes": "1462"
},
{
"name": "Mathematica",
"bytes": "2580"
},
{
"name": "Objective-C",
"bytes": "255"
},
{
"name": "Python",
"bytes": "2334"
},
{
"name": "Shell",
"bytes": "1092"
}
],
"symlink_target": ""
} |
using namespace std;
void roll(unsigned int numRolls, int numDie = 1, int numSides = 6);
void displayHistogram(vector<unsigned int>& values, int numDie);
void displayCounts(vector<unsigned int>& values, int numDie);
void findLargest(vector<unsigned int>& values, int numDie);
#endif | {
"content_hash": "ab34e7a59c4944c1608445ca3ddcd114",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 67,
"avg_line_length": 24,
"alnum_prop": 0.7604166666666666,
"repo_name": "danburkhol/diehistogram",
"id": "9051f4b81de66ad53af29602e6a76c275641b25f",
"size": "422",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DieHelper.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "4526"
}
],
"symlink_target": ""
} |
'''
The Layer 2.0 archtecture introduces several optimized node/message serialization formats
used by the layers to optimize returning primitives and facilitate efficient node construction:
.. note::
This interface is subject to change between minor revisions.
Storage Types (<stortype>)
In Layers 2.0, each node property from the model has an associated "storage type". Each
storage type determines how the data is indexed and represented within the Layer. This
formalizes the separation of "data model" from "storage model". Each data model type has
a "stortype" property which coresponds to one of the STOR_TYPE_XXX values. The knowledge
of the mapping of data model types to storage types is the responsibility of the data model,
making the Layer implementation fully decoupled from the data model.
Node Edits / Edits
A node edit consists of a (<buid>, <form>, [edits]) tuple. An edit is Tuple of (<type>, <info>, List[NodeEdits])
where the first element is an int that matches to an EDIT_* constant below, the info is a tuple that varies
depending on the first element, and the third element is a list of dependent NodeEdits that will only be applied
if the edit actually makes a change.
Storage Node (<sode>)
A storage node is a layer/storage optimized node representation which is similar to a "packed node".
A storage node *may* be partial ( as it is produced by a given layer ) and are joined by the view/snap
into "full" storage nodes which are used to construct Node() instances.
Sode format::
(<buid>, {
'ndef': (<formname>, <formvalu>),
'props': {
<propname>: <propvalu>,
}
'tags': {
<tagname>: <tagvalu>,
}
'tagprops: {
<tagname>: {
<propname>: <propvalu>,
},
}
# changes that were *just* made.
'edits': [
<edit>
]
}),
'''
import os
import math
import shutil
import struct
import asyncio
import logging
import ipaddress
import contextlib
import collections
import regex
import xxhash
import synapse.exc as s_exc
import synapse.common as s_common
import synapse.telepath as s_telepath
import synapse.lib.gis as s_gis
import synapse.lib.cell as s_cell
import synapse.lib.cache as s_cache
import synapse.lib.nexus as s_nexus
import synapse.lib.queue as s_queue
import synapse.lib.urlhelp as s_urlhelp
import synapse.lib.config as s_config
import synapse.lib.lmdbslab as s_lmdbslab
import synapse.lib.slabseqn as s_slabseqn
from synapse.lib.msgpack import deepcopy
logger = logging.getLogger(__name__)
import synapse.lib.msgpack as s_msgpack
reqValidLdef = s_config.getJsValidator({
'type': 'object',
'properties': {
'iden': {'type': 'string', 'pattern': s_config.re_iden},
'creator': {'type': 'string', 'pattern': s_config.re_iden},
'lockmemory': {'type': 'boolean'},
'lmdb:growsize': {'type': 'integer'},
'logedits': {'type': 'boolean', 'default': True},
'name': {'type': 'string'},
},
'additionalProperties': True,
'required': ['iden', 'creator', 'lockmemory'],
})
class LayerApi(s_cell.CellApi):
async def __anit__(self, core, link, user, layr):
await s_cell.CellApi.__anit__(self, core, link, user)
self.layr = layr
self.liftperm = ('layer', 'lift', self.layr.iden)
self.writeperm = ('layer', 'write', self.layr.iden)
async def iterLayerNodeEdits(self):
'''
Scan the full layer and yield artificial nodeedit sets.
'''
await self._reqUserAllowed(self.liftperm)
async for item in self.layr.iterLayerNodeEdits():
yield item
@s_cell.adminapi()
async def saveNodeEdits(self, edits, meta):
'''
Save node edits to the layer and return a tuple of (nexsoffs, changes).
Note: nexsoffs will be None if there are no changes.
'''
meta['link:user'] = self.user.iden
return await self.layr.saveNodeEdits(edits, meta)
async def storNodeEdits(self, nodeedits, meta=None):
await self._reqUserAllowed(self.writeperm)
if meta is None:
meta = {'time': s_common.now(), 'user': self.user.iden}
return await self.layr.storNodeEdits(nodeedits, meta)
async def storNodeEditsNoLift(self, nodeedits, meta=None):
await self._reqUserAllowed(self.writeperm)
if meta is None:
meta = {'time': s_common.now(), 'user': self.user.iden}
await self.layr.storNodeEditsNoLift(nodeedits, meta)
async def syncNodeEdits(self, offs, wait=True):
'''
Yield (offs, nodeedits) tuples from the nodeedit log starting from the given offset.
Once caught up with storage, yield them in realtime.
'''
await self._reqUserAllowed(self.liftperm)
async for item in self.layr.syncNodeEdits(offs, wait=wait):
yield item
async def syncNodeEdits2(self, offs, wait=True):
await self._reqUserAllowed(self.liftperm)
async for item in self.layr.syncNodeEdits2(offs, wait=wait):
yield item
async def splices(self, offs=None, size=None):
'''
This API is deprecated.
Yield (offs, splice) tuples from the nodeedit log starting from the given offset.
Nodeedits will be flattened into splices before being yielded.
'''
s_common.deprecated('LayerApi.splices')
await self._reqUserAllowed(self.liftperm)
async for item in self.layr.splices(offs=offs, size=size):
yield item
async def getEditIndx(self):
'''
Returns what will be the *next* nodeedit log index.
'''
await self._reqUserAllowed(self.liftperm)
return await self.layr.getEditIndx()
async def getEditSize(self):
'''
Return the total number of (edits, meta) pairs in the layer changelog.
'''
await self._reqUserAllowed(self.liftperm)
return await self.layr.getEditSize()
async def getIden(self):
await self._reqUserAllowed(self.liftperm)
return self.layr.iden
BUID_CACHE_SIZE = 10000
STOR_TYPE_UTF8 = 1
STOR_TYPE_U8 = 2
STOR_TYPE_U16 = 3
STOR_TYPE_U32 = 4
STOR_TYPE_U64 = 5
STOR_TYPE_I8 = 6
STOR_TYPE_I16 = 7
STOR_TYPE_I32 = 8
STOR_TYPE_I64 = 9
STOR_TYPE_GUID = 10
STOR_TYPE_TIME = 11
STOR_TYPE_IVAL = 12
STOR_TYPE_MSGP = 13
STOR_TYPE_LATLONG = 14
STOR_TYPE_LOC = 15
STOR_TYPE_TAG = 16
STOR_TYPE_FQDN = 17
STOR_TYPE_IPV6 = 18
STOR_TYPE_U128 = 19
STOR_TYPE_I128 = 20
STOR_TYPE_MINTIME = 21
STOR_TYPE_FLOAT64 = 22
STOR_TYPE_HUGENUM = 23
# STOR_TYPE_TOMB = ??
# STOR_TYPE_FIXED = ??
STOR_FLAG_ARRAY = 0x8000
# Edit types (etyp)
EDIT_NODE_ADD = 0 # (<etyp>, (<valu>, <type>), ())
EDIT_NODE_DEL = 1 # (<etyp>, (<oldv>, <type>), ())
EDIT_PROP_SET = 2 # (<etyp>, (<prop>, <valu>, <oldv>, <type>), ())
EDIT_PROP_DEL = 3 # (<etyp>, (<prop>, <oldv>, <type>), ())
EDIT_TAG_SET = 4 # (<etyp>, (<tag>, <valu>, <oldv>), ())
EDIT_TAG_DEL = 5 # (<etyp>, (<tag>, <oldv>), ())
EDIT_TAGPROP_SET = 6 # (<etyp>, (<tag>, <prop>, <valu>, <oldv>, <type>), ())
EDIT_TAGPROP_DEL = 7 # (<etyp>, (<tag>, <prop>, <oldv>, <type>), ())
EDIT_NODEDATA_SET = 8 # (<etyp>, (<name>, <valu>, <oldv>), ())
EDIT_NODEDATA_DEL = 9 # (<etyp>, (<name>, <oldv>), ())
EDIT_EDGE_ADD = 10 # (<etyp>, (<verb>, <destnodeiden>), ())
EDIT_EDGE_DEL = 11 # (<etyp>, (<verb>, <destnodeiden>), ())
EDIT_PROGRESS = 100 # (used by syncIndexEvents) (<etyp>, (), ())
class IndxBy:
'''
IndxBy sub-classes encapsulate access methods and encoding details for
various types of properties within the layer to be lifted/compared by
storage types.
'''
def __init__(self, layr, abrv, db):
self.db = db
self.abrv = abrv
self.layr = layr
self.abrvlen = len(abrv) # Dividing line between the abbreviations and the data-specific index
def getNodeValu(self, buid):
raise s_exc.NoSuchImpl(name='getNodeValu')
def keyBuidsByDups(self, indx):
yield from self.layr.layrslab.scanByDups(self.abrv + indx, db=self.db)
def buidsByDups(self, indx):
for _, buid in self.layr.layrslab.scanByDups(self.abrv + indx, db=self.db):
yield buid
def keyBuidsByPref(self, indx=b''):
yield from self.layr.layrslab.scanByPref(self.abrv + indx, db=self.db)
def buidsByPref(self, indx=b''):
for _, buid in self.layr.layrslab.scanByPref(self.abrv + indx, db=self.db):
yield buid
def keyBuidsByRange(self, minindx, maxindx):
yield from self.layr.layrslab.scanByRange(self.abrv + minindx, self.abrv + maxindx, db=self.db)
def buidsByRange(self, minindx, maxindx):
yield from (x[1] for x in self.keyBuidsByRange(minindx, maxindx))
def keyBuidsByRangeBack(self, minindx, maxindx):
'''
Yields backwards from maxindx to minindx
'''
yield from self.layr.layrslab.scanByRangeBack(self.abrv + maxindx, lmin=self.abrv + minindx, db=self.db)
def buidsByRangeBack(self, minindx, maxindx):
yield from (x[1] for x in self.keyBuidsByRangeBack(minindx, maxindx))
def scanByDups(self, indx):
for item in self.layr.layrslab.scanByDups(self.abrv + indx, db=self.db):
yield item
def scanByPref(self, indx=b''):
for item in self.layr.layrslab.scanByPref(self.abrv + indx, db=self.db):
yield item
def scanByRange(self, minindx, maxindx):
for item in self.layr.layrslab.scanByRange(self.abrv + minindx, self.abrv + maxindx, db=self.db):
yield item
def hasIndxBuid(self, indx, buid):
return self.layr.layrslab.hasdup(self.abrv + indx, buid, db=self.db)
class IndxByForm(IndxBy):
def __init__(self, layr, form):
'''
Note: may raise s_exc.NoSuchAbrv
'''
abrv = layr.getPropAbrv(form, None)
IndxBy.__init__(self, layr, abrv, layr.byprop)
self.form = form
def getNodeValu(self, buid):
sode = self.layr._getStorNode(buid)
if sode is None: # pragma: no cover
return None
valt = sode.get('valu')
if valt is not None:
return valt[0]
class IndxByProp(IndxBy):
def __init__(self, layr, form, prop):
'''
Note: may raise s_exc.NoSuchAbrv
'''
abrv = layr.getPropAbrv(form, prop)
IndxBy.__init__(self, layr, abrv, db=layr.byprop)
self.form = form
self.prop = prop
def getNodeValu(self, buid):
sode = self.layr._getStorNode(buid)
if sode is None: # pragma: no cover
return None
valt = sode['props'].get(self.prop)
if valt is not None:
return valt[0]
class IndxByPropArray(IndxBy):
def __init__(self, layr, form, prop):
'''
Note: may raise s_exc.NoSuchAbrv
'''
abrv = layr.getPropAbrv(form, prop)
IndxBy.__init__(self, layr, abrv, db=layr.byarray)
self.form = form
self.prop = prop
def getNodeValu(self, buid):
sode = self.layr._getStorNode(buid)
if sode is None: # pragma: no cover
return None
valt = sode['props'].get(self.prop)
if valt is not None:
return valt[0]
class IndxByTag(IndxBy):
def __init__(self, layr, form, tag):
'''
Note: may raise s_exc.NoSuchAbrv
'''
abrv = layr.tagabrv.bytsToAbrv(tag.encode())
if form is not None:
abrv += layr.getPropAbrv(form, None)
IndxBy.__init__(self, layr, abrv, layr.bytag)
self.abrvlen = 16
self.form = form
self.tag = tag
def getNodeValuForm(self, buid):
sode = self.layr._getStorNode(buid)
if sode is None: # pragma: no cover
return None
valt = sode['tags'].get(self.tag)
if valt is not None:
return valt, sode['form']
class IndxByTagProp(IndxBy):
def __init__(self, layr, form, tag, prop):
'''
Note: may raise s_exc.NoSuchAbrv
'''
abrv = layr.getTagPropAbrv(form, tag, prop)
IndxBy.__init__(self, layr, abrv, layr.bytagprop)
self.form = form
self.prop = prop
self.tag = tag
def getNodeValu(self, buid):
sode = self.layr._getStorNode(buid)
if sode is None: # pragma: no cover
return None
props = sode['tagprops'].get(self.tag)
if not props:
return
valu = props.get(self.prop)
if valu is not None:
return valu[0]
class StorType:
def __init__(self, layr, stortype):
self.layr = layr
self.stortype = stortype
self.lifters = {}
async def indxBy(self, liftby, cmpr, valu):
func = self.lifters.get(cmpr)
if func is None:
raise s_exc.NoSuchCmpr(cmpr=cmpr)
async for item in func(liftby, valu):
yield item
async def indxByForm(self, form, cmpr, valu):
try:
indxby = IndxByForm(self.layr, form)
except s_exc.NoSuchAbrv:
return
async for item in self.indxBy(indxby, cmpr, valu):
yield item
async def verifyBuidProp(self, buid, form, prop, valu):
indxby = IndxByProp(self.layr, form, prop)
for indx in self.indx(valu):
if not indxby.hasIndxBuid(indx, buid):
yield ('NoPropIndex', {'prop': prop, 'valu': valu})
async def indxByProp(self, form, prop, cmpr, valu):
try:
indxby = IndxByProp(self.layr, form, prop)
except s_exc.NoSuchAbrv:
return
async for item in self.indxBy(indxby, cmpr, valu):
yield item
async def indxByPropArray(self, form, prop, cmpr, valu):
try:
indxby = IndxByPropArray(self.layr, form, prop)
except s_exc.NoSuchAbrv:
return
async for item in self.indxBy(indxby, cmpr, valu):
yield item
async def indxByTagProp(self, form, tag, prop, cmpr, valu):
try:
indxby = IndxByTagProp(self.layr, form, tag, prop)
except s_exc.NoSuchAbrv:
return
async for item in self.indxBy(indxby, cmpr, valu):
yield item
def indx(self, valu): # pragma: no cover
raise NotImplementedError
def decodeIndx(self, valu): # pragma: no cover
return s_common.novalu
async def _liftRegx(self, liftby, valu):
regx = regex.compile(valu)
abrvlen = liftby.abrvlen
isarray = isinstance(liftby, IndxByPropArray)
for lkey, buid in liftby.keyBuidsByPref():
await asyncio.sleep(0)
indx = lkey[abrvlen:]
storvalu = self.decodeIndx(indx)
if storvalu == s_common.novalu:
storvalu = liftby.getNodeValu(buid)
if isarray:
for sval in storvalu:
if self.indx(sval)[0] == indx:
storvalu = sval
break
else:
continue
def regexin(regx, storvalu):
if isinstance(storvalu, str):
if regx.search(storvalu) is not None:
return True
elif isinstance(storvalu, (tuple, list)):
return any(regexin(regx, sv) for sv in storvalu)
return False
if regexin(regx, storvalu):
yield lkey, buid
class StorTypeUtf8(StorType):
def __init__(self, layr):
StorType.__init__(self, layr, STOR_TYPE_UTF8)
self.lifters.update({
'=': self._liftUtf8Eq,
'~=': self._liftRegx,
'^=': self._liftUtf8Prefix,
'range=': self._liftUtf8Range,
})
async def _liftUtf8Eq(self, liftby, valu):
indx = self._getIndxByts(valu)
for item in liftby.keyBuidsByDups(indx):
yield item
async def _liftUtf8Range(self, liftby, valu):
minindx = self._getIndxByts(valu[0])
maxindx = self._getIndxByts(valu[1])
for item in liftby.keyBuidsByRange(minindx, maxindx):
yield item
async def _liftUtf8Prefix(self, liftby, valu):
indx = self._getIndxByts(valu)
for item in liftby.keyBuidsByPref(indx):
yield item
def _getIndxByts(self, valu):
indx = valu.encode('utf8', 'surrogatepass')
# cut down an index value to 256 bytes...
if len(indx) <= 256:
return indx
base = indx[:248]
sufx = xxhash.xxh64(indx).digest()
return base + sufx
def indx(self, valu):
return (self._getIndxByts(valu), )
def decodeIndx(self, bytz):
if len(bytz) >= 256:
return s_common.novalu
return bytz.decode('utf8', 'surrogatepass')
class StorTypeHier(StorType):
def __init__(self, layr, stortype, sepr='.'):
StorType.__init__(self, layr, stortype)
self.sepr = sepr
self.lifters.update({
'=': self._liftHierEq,
'^=': self._liftHierPref,
})
def indx(self, valu):
return (
self.getHierIndx(valu),
)
def getHierIndx(self, valu):
# encode the index values with a trailing sepr to allow ^=foo.bar to be boundary aware
return (valu + self.sepr).encode()
def decodeIndx(self, bytz):
return bytz.decode()[:-len(self.sepr)]
async def _liftHierEq(self, liftby, valu):
indx = self.getHierIndx(valu)
for item in liftby.keyBuidsByDups(indx):
yield item
async def _liftHierPref(self, liftby, valu):
indx = self.getHierIndx(valu)
for item in liftby.keyBuidsByPref(indx):
yield item
class StorTypeLoc(StorTypeHier):
def __init__(self, layr):
StorTypeHier.__init__(self, layr, STOR_TYPE_LOC)
class StorTypeTag(StorTypeHier):
def __init__(self, layr):
StorTypeHier.__init__(self, layr, STOR_TYPE_TAG)
@staticmethod
def getTagFilt(cmpr, valu):
if cmpr == '=':
def filt1(x):
return x == valu
return filt1
if cmpr == '@=':
def filt2(item):
if item is None:
return False
if item == (None, None):
return False
if item[0] >= valu[1]:
return False
if item[1] <= valu[0]:
return False
return True
return filt2
class StorTypeFqdn(StorTypeUtf8):
def indx(self, norm):
return (
self._getIndxByts(norm[::-1]),
)
def decodeIndx(self, bytz):
if len(bytz) >= 256:
return s_common.novalu
return bytz.decode('utf8', 'surrogatepass')[::-1]
def __init__(self, layr):
StorType.__init__(self, layr, STOR_TYPE_UTF8)
self.lifters.update({
'=': self._liftFqdnEq,
'~=': self._liftRegx,
})
async def _liftFqdnEq(self, liftby, valu):
if valu[0] == '*':
indx = self._getIndxByts(valu[1:][::-1])
for item in liftby.keyBuidsByPref(indx):
yield item
return
async for item in StorTypeUtf8._liftUtf8Eq(self, liftby, valu[::-1]):
yield item
class StorTypeIpv6(StorType):
def __init__(self, layr):
StorType.__init__(self, layr, STOR_TYPE_IPV6)
self.lifters.update({
'=': self._liftIPv6Eq,
'range=': self._liftIPv6Range,
})
def getIPv6Indx(self, valu):
return ipaddress.IPv6Address(valu).packed
def indx(self, valu):
return (
self.getIPv6Indx(valu),
)
def decodeIndx(self, bytz):
return str(ipaddress.IPv6Address(bytz))
async def _liftIPv6Eq(self, liftby, valu):
indx = self.getIPv6Indx(valu)
for item in liftby.keyBuidsByDups(indx):
yield item
async def _liftIPv6Range(self, liftby, valu):
minindx = self.getIPv6Indx(valu[0])
maxindx = self.getIPv6Indx(valu[1])
for item in liftby.keyBuidsByRange(minindx, maxindx):
yield item
class StorTypeInt(StorType):
def __init__(self, layr, stortype, size, signed):
StorType.__init__(self, layr, stortype)
self.size = size
self.signed = signed
self.offset = 0
if signed:
self.offset = 2 ** ((self.size * 8) - 1) - 1
self.maxval = 2 ** (self.size * 8) - 1
self.lifters.update({
'=': self._liftIntEq,
'<': self._liftIntLt,
'>': self._liftIntGt,
'<=': self._liftIntLe,
'>=': self._liftIntGe,
'range=': self._liftIntRange,
})
self.zerobyts = b'\x00' * self.size
self.fullbyts = b'\xff' * self.size
def getIntIndx(self, valu):
return (valu + self.offset).to_bytes(self.size, 'big')
def indx(self, valu):
return (self.getIntIndx(valu),)
def decodeIndx(self, bytz):
return int.from_bytes(bytz, 'big') - self.offset
async def _liftIntEq(self, liftby, valu):
indx = valu + self.offset
if indx < 0 or indx > self.maxval:
return
pkey = indx.to_bytes(self.size, 'big')
for item in liftby.keyBuidsByDups(pkey):
yield item
async def _liftIntGt(self, liftby, valu):
async for item in self._liftIntGe(liftby, valu + 1):
yield item
async def _liftIntGe(self, liftby, valu):
minv = valu + self.offset
if minv > self.maxval:
return
minv = max(minv, 0)
pkeymin = minv.to_bytes(self.size, 'big')
pkeymax = self.fullbyts
for item in liftby.keyBuidsByRange(pkeymin, pkeymax):
yield item
async def _liftIntLt(self, liftby, valu):
async for item in self._liftIntLe(liftby, valu - 1):
yield item
async def _liftIntLe(self, liftby, valu):
maxv = valu + self.offset
if maxv < 0:
return
maxv = min(maxv, self.maxval)
pkeymin = self.zerobyts
pkeymax = maxv.to_bytes(self.size, 'big')
for item in liftby.keyBuidsByRange(pkeymin, pkeymax):
yield item
async def _liftIntRange(self, liftby, valu):
minv = valu[0] + self.offset
maxv = valu[1] + self.offset
if minv > self.maxval or maxv < 0:
return
minv = max(minv, 0)
maxv = min(maxv, self.maxval)
pkeymin = minv.to_bytes(self.size, 'big')
pkeymax = maxv.to_bytes(self.size, 'big')
for item in liftby.keyBuidsByRange(pkeymin, pkeymax):
yield item
class StorTypeHugeNum(StorType):
def __init__(self, layr, stortype):
StorType.__init__(self, layr, STOR_TYPE_HUGENUM)
self.lifters.update({
'=': self._liftHugeEq,
'<': self._liftHugeLt,
'>': self._liftHugeGt,
'<=': self._liftHugeLe,
'>=': self._liftHugeGe,
'range=': self._liftHugeRange,
})
self.one = s_common.hugeexp
self.offset = s_common.hugenum(0x7fffffffffffffffffffffffffffffffffffffff)
self.zerobyts = b'\x00' * 20
self.fullbyts = b'\xff' * 20
def getHugeIndx(self, norm):
scaled = s_common.hugescaleb(s_common.hugenum(norm), 24)
byts = int(s_common.hugeadd(scaled, self.offset)).to_bytes(20, byteorder='big')
return byts
def indx(self, norm):
return (self.getHugeIndx(norm),)
def decodeIndx(self, bytz):
huge = s_common.hugenum(int.from_bytes(bytz, 'big'))
valu = s_common.hugescaleb(s_common.hugesub(huge, self.offset), -24)
return '{:f}'.format(valu.normalize(s_common.hugectx))
async def _liftHugeEq(self, liftby, valu):
byts = self.getHugeIndx(valu)
for item in liftby.keyBuidsByDups(byts):
yield item
async def _liftHugeGt(self, liftby, valu):
valu = s_common.hugenum(valu)
async for item in self._liftHugeGe(liftby, s_common.hugeadd(valu, self.one)):
yield item
async def _liftHugeLt(self, liftby, valu):
valu = s_common.hugenum(valu)
async for item in self._liftHugeLe(liftby, s_common.hugesub(valu, self.one)):
yield item
async def _liftHugeGe(self, liftby, valu):
pkeymin = self.getHugeIndx(valu)
pkeymax = self.fullbyts
for item in liftby.keyBuidsByRange(pkeymin, pkeymax):
yield item
async def _liftHugeLe(self, liftby, valu):
pkeymin = self.zerobyts
pkeymax = self.getHugeIndx(valu)
for item in liftby.keyBuidsByRange(pkeymin, pkeymax):
yield item
async def _liftHugeRange(self, liftby, valu):
pkeymin = self.getHugeIndx(valu[0])
pkeymax = self.getHugeIndx(valu[1])
for item in liftby.keyBuidsByRange(pkeymin, pkeymax):
yield item
class StorTypeFloat(StorType):
FloatPacker = struct.Struct('>d')
fpack = FloatPacker.pack
FloatPackPosMax = FloatPacker.pack(math.inf)
FloatPackPosMin = FloatPacker.pack(0.0)
FloatPackNegMin = FloatPacker.pack(-math.inf)
FloatPackNegMax = FloatPacker.pack(-0.0)
def __init__(self, layr, stortype, size=8):
'''
Size reserved for later use
'''
assert size == 8
StorType.__init__(self, layr, stortype)
self.lifters.update({
'=': self._liftFloatEq,
'<': self._liftFloatLt,
'>': self._liftFloatGt,
'<=': self._liftFloatLe,
'>=': self._liftFloatGe,
'range=': self._liftFloatRange,
})
def indx(self, valu):
return (self.fpack(valu),)
def decodeIndx(self, bytz):
return self.FloatPacker.unpack(bytz)[0]
async def _liftFloatEq(self, liftby, valu):
for item in liftby.keyBuidsByDups(self.fpack(valu)):
yield item
async def _liftFloatGeCommon(self, liftby, valu):
if math.isnan(valu):
raise s_exc.NotANumberCompared()
valupack = self.fpack(valu)
if math.copysign(1.0, valu) < 0.0: # negative values and -0.0
for item in liftby.keyBuidsByRangeBack(self.FloatPackNegMax, valupack):
yield item
valupack = self.FloatPackPosMin
for item in liftby.keyBuidsByRange(valupack, self.FloatPackPosMax):
yield item
async def _liftFloatGe(self, liftby, valu):
async for item in self._liftFloatGeCommon(liftby, valu):
yield item
async def _liftFloatGt(self, liftby, valu):
valupack = self.fpack(valu)
async for item in self._liftFloatGeCommon(liftby, valu):
if item[0] == valupack:
continue
yield item
async def _liftFloatLeCommon(self, liftby, valu):
if math.isnan(valu):
raise s_exc.NotANumberCompared()
valupack = self.fpack(valu)
if math.copysign(1.0, valu) > 0.0:
for item in liftby.keyBuidsByRangeBack(self.FloatPackNegMax, self.FloatPackNegMin):
yield item
for item in liftby.keyBuidsByRange(self.FloatPackPosMin, valupack):
yield item
else:
for item in liftby.keyBuidsByRangeBack(valupack, self.FloatPackNegMin):
yield item
async def _liftFloatLe(self, liftby, valu):
async for item in self._liftFloatLeCommon(liftby, valu):
yield item
async def _liftFloatLt(self, liftby, valu):
valupack = self.fpack(valu)
async for item in self._liftFloatLeCommon(liftby, valu):
if item[0] == valupack:
continue
yield item
async def _liftFloatRange(self, liftby, valu):
valumin, valumax = valu
if math.isnan(valumin) or math.isnan(valumax):
raise s_exc.NotANumberCompared()
assert valumin <= valumax
pkeymin, pkeymax = (self.fpack(v) for v in valu)
if math.copysign(1.0, valumin) > 0.0:
# Entire range is nonnegative
for item in liftby.keyBuidsByRange(pkeymin, pkeymax):
yield item
return
if math.copysign(1.0, valumax) < 0.0: # negative values and -0.0
# Entire range is negative
for item in liftby.keyBuidsByRangeBack(pkeymax, pkeymin):
yield item
return
# Yield all values between min and -0
for item in liftby.keyBuidsByRangeBack(self.FloatPackNegMax, pkeymin):
yield item
# Yield all values between 0 and max
for item in liftby.keyBuidsByRange(self.FloatPackPosMin, pkeymax):
yield item
class StorTypeGuid(StorType):
def __init__(self, layr):
StorType.__init__(self, layr, STOR_TYPE_GUID)
self.lifters.update({
'=': self._liftGuidEq,
'^=': self._liftGuidPref,
})
async def _liftGuidPref(self, liftby, byts):
# valu is already bytes of the guid prefix
for item in liftby.keyBuidsByPref(byts):
yield item
async def _liftGuidEq(self, liftby, valu):
indx = s_common.uhex(valu)
for item in liftby.keyBuidsByDups(indx):
yield item
def indx(self, valu):
return (s_common.uhex(valu),)
def decodeIndx(self, bytz):
return s_common.ehex(bytz)
class StorTypeTime(StorTypeInt):
def __init__(self, layr):
StorTypeInt.__init__(self, layr, STOR_TYPE_TIME, 8, True)
self.lifters.update({
'@=': self._liftAtIval,
})
async def _liftAtIval(self, liftby, valu):
minindx = self.getIntIndx(valu[0])
maxindx = self.getIntIndx(valu[1] - 1)
for item in liftby.scanByRange(minindx, maxindx):
yield item
class StorTypeIval(StorType):
def __init__(self, layr):
StorType.__init__(self, layr, STOR_TYPE_IVAL)
self.timetype = StorTypeTime(layr)
self.lifters.update({
'=': self._liftIvalEq,
'@=': self._liftIvalAt,
})
async def _liftIvalEq(self, liftby, valu):
indx = self.timetype.getIntIndx(valu[0]) + self.timetype.getIntIndx(valu[1])
for item in liftby.keyBuidsByDups(indx):
yield item
async def _liftIvalAt(self, liftby, valu):
minindx = self.timetype.getIntIndx(valu[0])
maxindx = self.timetype.getIntIndx(valu[1])
for lkey, buid in liftby.scanByPref():
tick = lkey[-16:-8]
tock = lkey[-8:]
# check for non-ovelap left and right
if tick >= maxindx:
continue
if tock <= minindx:
continue
yield lkey, buid
def indx(self, valu):
return (self.timetype.getIntIndx(valu[0]) + self.timetype.getIntIndx(valu[1]),)
def decodeIndx(self, bytz):
return (self.timetype.decodeIndx(bytz[:8]), self.timetype.decodeIndx(bytz[8:]))
class StorTypeMsgp(StorType):
def __init__(self, layr):
StorType.__init__(self, layr, STOR_TYPE_MSGP)
self.lifters.update({
'=': self._liftMsgpEq,
'~=': self._liftRegx,
})
async def _liftMsgpEq(self, liftby, valu):
indx = s_common.buid(valu)
for item in liftby.keyBuidsByDups(indx):
yield item
def indx(self, valu):
return (s_common.buid(valu),)
class StorTypeLatLon(StorType):
def __init__(self, layr):
StorType.__init__(self, layr, STOR_TYPE_LATLONG)
self.scale = 10 ** 8
self.latspace = 90 * 10 ** 8
self.lonspace = 180 * 10 ** 8
self.lifters.update({
'=': self._liftLatLonEq,
'near=': self._liftLatLonNear,
})
async def _liftLatLonEq(self, liftby, valu):
indx = self._getLatLonIndx(valu)
for item in liftby.keyBuidsByDups(indx):
yield item
async def _liftLatLonNear(self, liftby, valu):
(lat, lon), dist = valu
# latscale = (lat * self.scale) + self.latspace
# lonscale = (lon * self.scale) + self.lonspace
latmin, latmax, lonmin, lonmax = s_gis.bbox(lat, lon, dist)
lonminindx = (round(lonmin * self.scale) + self.lonspace).to_bytes(5, 'big')
lonmaxindx = (round(lonmax * self.scale) + self.lonspace).to_bytes(5, 'big')
latminindx = (round(latmin * self.scale) + self.latspace).to_bytes(5, 'big')
latmaxindx = (round(latmax * self.scale) + self.latspace).to_bytes(5, 'big')
# scan by lon range and down-select the results to matches.
for lkey, buid in liftby.scanByRange(lonminindx, lonmaxindx):
# lkey = <abrv> <lonindx> <latindx>
# limit results to the bounding box before unpacking...
latbyts = lkey[13:18]
if latbyts > latmaxindx:
continue
if latbyts < latminindx:
continue
lonbyts = lkey[8:13]
latvalu = (int.from_bytes(latbyts, 'big') - self.latspace) / self.scale
lonvalu = (int.from_bytes(lonbyts, 'big') - self.lonspace) / self.scale
if s_gis.haversine((lat, lon), (latvalu, lonvalu)) <= dist:
yield lkey, buid
def _getLatLonIndx(self, latlong):
# yield index bytes in lon/lat order to allow cheap optimal indexing
latindx = (round(latlong[0] * self.scale) + self.latspace).to_bytes(5, 'big')
lonindx = (round(latlong[1] * self.scale) + self.lonspace).to_bytes(5, 'big')
return lonindx + latindx
def indx(self, valu):
# yield index bytes in lon/lat order to allow cheap optimal indexing
return (self._getLatLonIndx(valu),)
def decodeIndx(self, bytz):
lon = (int.from_bytes(bytz[:5], 'big') - self.lonspace) / self.scale
lat = (int.from_bytes(bytz[5:], 'big') - self.latspace) / self.scale
return (lat, lon)
class Layer(s_nexus.Pusher):
'''
The base class for a cortex layer.
'''
nodeeditctor = s_slabseqn.SlabSeqn
def __repr__(self):
return f'Layer ({self.__class__.__name__}): {self.iden}'
async def __anit__(self, core, layrinfo):
self.core = core
self.layrinfo = layrinfo
self.addoffs = None # The nexus log index where I was created
self.deloffs = None # The nexus log index where I was deleted
self.isdeleted = False
self.iden = layrinfo.get('iden')
await s_nexus.Pusher.__anit__(self, self.iden, nexsroot=core.nexsroot)
self.dirn = s_common.gendir(core.dirn, 'layers', self.iden)
self.readonly = layrinfo.get('readonly')
self.lockmemory = self.layrinfo.get('lockmemory')
self.growsize = self.layrinfo.get('growsize')
self.logedits = self.layrinfo.get('logedits')
self.mapasync = core.conf.get('layer:lmdb:map_async')
self.maxreplaylog = core.conf.get('layer:lmdb:max_replay_log')
# slim hooks to avoid async/fire
self.nodeAddHook = None
self.nodeDelHook = None
path = s_common.genpath(self.dirn, 'layer_v2.lmdb')
self.fresh = not os.path.exists(path)
self.dirty = {}
self.futures = {}
self.stortypes = [
None,
StorTypeUtf8(self),
StorTypeInt(self, STOR_TYPE_U8, 1, False),
StorTypeInt(self, STOR_TYPE_U16, 2, False),
StorTypeInt(self, STOR_TYPE_U32, 4, False),
StorTypeInt(self, STOR_TYPE_U64, 8, False),
StorTypeInt(self, STOR_TYPE_I8, 1, True),
StorTypeInt(self, STOR_TYPE_I16, 2, True),
StorTypeInt(self, STOR_TYPE_I32, 4, True),
StorTypeInt(self, STOR_TYPE_I64, 8, True),
StorTypeGuid(self),
StorTypeTime(self),
StorTypeIval(self),
StorTypeMsgp(self),
StorTypeLatLon(self),
StorTypeLoc(self),
StorTypeTag(self),
StorTypeFqdn(self),
StorTypeIpv6(self),
StorTypeInt(self, STOR_TYPE_U128, 16, False),
StorTypeInt(self, STOR_TYPE_I128, 16, True),
StorTypeTime(self), # STOR_TYPE_MINTIME
StorTypeFloat(self, STOR_TYPE_FLOAT64, 8),
StorTypeHugeNum(self, STOR_TYPE_HUGENUM),
]
await self._initLayerStorage()
self.editors = [
self._editNodeAdd,
self._editNodeDel,
self._editPropSet,
self._editPropDel,
self._editTagSet,
self._editTagDel,
self._editTagPropSet,
self._editTagPropDel,
self._editNodeDataSet,
self._editNodeDataDel,
self._editNodeEdgeAdd,
self._editNodeEdgeDel,
]
self.canrev = True
self.ctorname = f'{self.__class__.__module__}.{self.__class__.__name__}'
self.windows = []
self.upstreamwaits = collections.defaultdict(lambda: collections.defaultdict(list))
self.buidcache = s_cache.LruDict(BUID_CACHE_SIZE)
self.onfini(self._onLayrFini)
# if we are a mirror, we upstream all our edits and
# wait for them to make it back down the pipe...
self.leader = None
self.leadtask = None
self.ismirror = layrinfo.get('mirror') is not None
self.activetasks = []
@contextlib.contextmanager
def getIdenFutu(self, iden=None):
if iden is None:
iden = s_common.guid()
futu = self.loop.create_future()
self.futures[iden] = futu
yield iden, futu
self.futures.pop(iden, None)
async def getMirrorStatus(self):
# TODO plumb back to upstream on not self.core.isactive
retn = {'mirror': self.leader is not None}
if self.leader:
proxy = await self.leader.proxy()
retn['local'] = {'size': await self.getEditSize()}
retn['remote'] = {'size': await proxy.getEditSize()}
return retn
async def initLayerActive(self):
if self.leadtask is not None:
self.leadtask.cancel()
mirror = self.layrinfo.get('mirror')
if mirror is not None:
conf = {'retrysleep': 2}
self.leader = await s_telepath.Client.anit(mirror, conf=conf)
self.leadtask = self.schedCoro(self._runMirrorLoop())
uplayr = self.layrinfo.get('upstream')
if uplayr is not None:
if isinstance(uplayr, (tuple, list)):
for layr in uplayr:
await self.initUpstreamSync(layr)
else:
await self.initUpstreamSync(uplayr)
async def initLayerPassive(self):
if self.leadtask is not None:
self.leadtask.cancel()
self.leadtask = None
if self.leader is not None:
await self.leader.fini()
self.leader = None
[t.cancel() for t in self.activetasks]
self.activetasks.clear()
async def getEditSize(self):
return self.nodeeditlog.size
async def _runMirrorLoop(self):
while not self.isfini:
try:
proxy = await self.leader.proxy()
leadoffs = await self._getLeadOffs()
async for offs, edits, meta in proxy.syncNodeEdits2(leadoffs + 1):
iden = meta.get('task')
futu = self.futures.pop(iden, None)
meta['indx'] = offs
try:
item = await self.saveToNexs('edits', edits, meta)
if futu is not None:
futu.set_result(item)
except asyncio.CancelledError: # pragma: no cover
raise
except s_exc.LinkShutDown:
raise
except Exception as e:
if futu is not None:
futu.set_exception(e)
continue
logger.error(f'Error consuming mirror nodeedit at offset {offs} for (layer: {self.iden}): {e}')
except asyncio.CancelledError as e: # pragma: no cover
raise
except Exception as e: # pragma: no cover
logger.exception(f'error in runMirrorLoop() (layer: {self.iden}): ')
await self.waitfini(timeout=2)
async def _getLeadOffs(self):
last = self.nodeeditlog.last()
if last is None:
return -1
return last[1][1].get('indx', -1)
async def verifyBuidTag(self, buid, formname, tagname, tagvalu):
abrv = self.tagabrv.bytsToAbrv(tagname.encode())
abrv += self.getPropAbrv(formname, None)
if not self.layrslab.hasdup(abrv, buid, db=self.bytag):
yield ('NoTagIndex', {'buid': buid, 'form': formname, 'tag': tagname, 'valu': tagvalu})
def _testDelTagIndx(self, buid, form, tag):
formabrv = self.setPropAbrv(form, None)
tagabrv = self.tagabrv.bytsToAbrv(tag.encode())
self.layrslab.delete(tagabrv + formabrv, buid, db=self.bytag)
def _testDelPropIndx(self, buid, form, prop):
sode = self._getStorNode(buid)
storvalu, stortype = sode['props'][prop]
abrv = self.setPropAbrv(form, prop)
for indx in self.stortypes[stortype].indx(storvalu):
self.layrslab.delete(abrv + indx, buid, db=self.byprop)
def _testDelTagStor(self, buid, form, tag):
sode = self._getStorNode(buid)
sode['tags'].pop(tag, None)
self.setSodeDirty(buid, sode, form)
def _testDelPropStor(self, buid, form, prop):
sode = self._getStorNode(buid)
sode['props'].pop(prop, None)
self.setSodeDirty(buid, sode, form)
def _testDelFormValuStor(self, buid, form):
sode = self._getStorNode(buid)
sode['valu'] = None
self.setSodeDirty(buid, sode, form)
def _testAddPropIndx(self, buid, form, prop, valu):
modlprop = self.core.model.prop(f'{form}:{prop}')
abrv = self.setPropAbrv(form, prop)
for indx in self.stortypes[modlprop.type.stortype].indx(valu):
self.layrslab.put(abrv + indx, buid, db=self.byprop)
def _testAddPropArrayIndx(self, buid, form, prop, valu):
modlprop = self.core.model.prop(f'{form}:{prop}')
abrv = self.setPropAbrv(form, prop)
for indx in self.getStorIndx(modlprop.type.stortype, valu):
self.layrslab.put(abrv + indx, buid, db=self.byarray)
def _testAddTagIndx(self, buid, form, tag):
formabrv = self.setPropAbrv(form, None)
tagabrv = self.tagabrv.bytsToAbrv(tag.encode())
self.layrslab.put(tagabrv + formabrv, buid, db=self.bytag)
def _testAddTagPropIndx(self, buid, form, tag, prop, valu):
tpabrv = self.setTagPropAbrv(None, tag, prop)
ftpabrv = self.setTagPropAbrv(form, tag, prop)
tagprop = self.core.model.tagprop(prop)
for indx in self.stortypes[tagprop.type.stortype].indx(valu):
self.layrslab.put(tpabrv + indx, buid, db=self.bytagprop)
self.layrslab.put(ftpabrv + indx, buid, db=self.bytagprop)
async def verify(self, config=None):
if config is None:
config = {}
defconf = None
if config.get('scanall', True):
defconf = {}
scans = config.get('scans', {})
nodescan = scans.get('nodes', defconf)
if nodescan is not None:
async for error in self.verifyAllBuids(nodescan):
yield error
tagsscan = scans.get('tagindex', defconf)
if tagsscan is not None:
async for error in self.verifyAllTags(tagsscan):
yield error
propscan = scans.get('propindex', defconf)
if propscan is not None:
async for error in self.verifyAllProps(propscan):
yield error
tagpropscan = scans.get('tagpropindex', defconf)
if tagpropscan is not None:
async for error in self.verifyAllTagProps(tagpropscan):
yield error
async def verifyAllBuids(self, scanconf=None):
if scanconf is None:
scanconf = {}
async for buid, sode in self.getStorNodes():
async for error in self.verifyByBuid(buid, sode):
yield error
async def verifyAllTags(self, scanconf=None):
if scanconf is None:
scanconf = {}
globs = None
includes = scanconf.get('include', ())
if includes:
globs = s_cache.TagGlobs()
for incname in includes:
globs.add(incname, True)
autofix = scanconf.get('autofix')
if autofix not in (None, 'node', 'index'):
mesg = f'invalid tag index autofix strategy "{autofix}"'
raise s_exc.BadArg(mesg=mesg)
for name in self.tagabrv.names():
if globs is not None and not globs.get(name):
continue
async for error in self.verifyByTag(name, autofix=autofix):
yield error
async def verifyAllProps(self, scanconf=None):
if scanconf is None:
scanconf = {}
autofix = scanconf.get('autofix')
if autofix not in (None, 'index'):
mesg = f'invalid prop index autofix strategy "{autofix}"'
raise s_exc.BadArg(mesg=mesg)
include = scanconf.get('include', None)
for form, prop in self.getFormProps():
if include is not None and (form, prop) not in include:
continue
async for error in self.verifyByProp(form, prop, autofix=autofix):
yield error
async for error in self.verifyByPropArray(form, prop, autofix=autofix):
yield error
async def verifyAllTagProps(self, scanconf=None):
if scanconf is None:
scanconf = {}
autofix = scanconf.get('autofix')
if autofix not in (None, 'index'):
mesg = f'invalid tagprop index autofix strategy "{autofix}"'
raise s_exc.BadArg(mesg=mesg)
include = scanconf.get('include', None)
for form, tag, prop in self.getTagProps():
if include is not None and prop not in include:
continue
async for error in self.verifyByTagProp(form, tag, prop, autofix=autofix):
yield error
async def verifyByTag(self, tag, autofix=None):
tagabrv = self.tagabrv.bytsToAbrv(tag.encode())
async def tryfix(lkey, buid, form):
if autofix == 'node':
sode = self._genStorNode(buid)
sode.setdefault('form', form)
sode['tags'][tag] = (None, None)
self.setSodeDirty(buid, sode, form)
elif autofix == 'index':
self.layrslab.delete(lkey, buid, db=self.bytag)
for lkey, buid in self.layrslab.scanByPref(tagabrv, db=self.bytag):
await asyncio.sleep(0)
(form, prop) = self.getAbrvProp(lkey[8:])
sode = self._getStorNode(buid)
if sode is None: # pragma: no cover
await tryfix(lkey, buid, form)
yield ('NoNodeForTagIndex', {'buid': s_common.ehex(buid), 'form': form, 'tag': tag})
continue
tags = sode.get('tags')
if tags.get(tag) is None:
await tryfix(lkey, buid, form)
yield ('NoTagForTagIndex', {'buid': s_common.ehex(buid), 'form': form, 'tag': tag})
continue
async def verifyByProp(self, form, prop, autofix=None):
abrv = self.getPropAbrv(form, prop)
async def tryfix(lkey, buid):
if autofix == 'index':
self.layrslab.delete(lkey, buid, db=self.byprop)
for lkey, buid in self.layrslab.scanByPref(abrv, db=self.byprop):
await asyncio.sleep(0)
indx = lkey[len(abrv):]
sode = self._getStorNode(buid)
if sode is None:
await tryfix(lkey, buid)
yield ('NoNodeForPropIndex', {'buid': s_common.ehex(buid), 'form': form, 'prop': prop, 'indx': indx})
continue
if prop is not None:
props = sode.get('props')
if props is None:
await tryfix(lkey, buid)
yield ('NoValuForPropIndex', {'buid': s_common.ehex(buid), 'form': form, 'prop': prop, 'indx': indx})
continue
valu = props.get(prop)
if valu is None:
await tryfix(lkey, buid)
yield ('NoValuForPropIndex', {'buid': s_common.ehex(buid), 'form': form, 'prop': prop, 'indx': indx})
continue
else:
valu = sode.get('valu')
if valu is None:
await tryfix(lkey, buid)
yield ('NoValuForPropIndex', {'buid': s_common.ehex(buid), 'form': form, 'prop': prop, 'indx': indx})
continue
propvalu, stortype = valu
if stortype & STOR_FLAG_ARRAY:
stortype = STOR_TYPE_MSGP
try:
for indx in self.stortypes[stortype].indx(propvalu):
if abrv + indx == lkey:
break
else:
await tryfix(lkey, buid)
yield ('SpurPropKeyForIndex', {'buid': s_common.ehex(buid), 'form': form,
'prop': prop, 'indx': indx})
except IndexError:
await tryfix(lkey, buid)
yield ('NoStorTypeForProp', {'buid': s_common.ehex(buid), 'form': form, 'prop': prop,
'stortype': stortype})
async def verifyByPropArray(self, form, prop, autofix=None):
abrv = self.getPropAbrv(form, prop)
async def tryfix(lkey, buid):
if autofix == 'index':
self.layrslab.delete(lkey, buid, db=self.byarray)
for lkey, buid in self.layrslab.scanByPref(abrv, db=self.byarray):
await asyncio.sleep(0)
indx = lkey[len(abrv):]
sode = self._getStorNode(buid)
if sode is None:
await tryfix(lkey, buid)
yield ('NoNodeForPropArrayIndex', {'buid': s_common.ehex(buid), 'form': form,
'prop': prop, 'indx': indx})
continue
if prop is not None:
props = sode.get('props')
if props is None:
await tryfix(lkey, buid)
yield ('NoValuForPropArrayIndex', {'buid': s_common.ehex(buid), 'form': form,
'prop': prop, 'indx': indx})
continue
valu = props.get(prop)
if valu is None:
await tryfix(lkey, buid)
yield ('NoValuForPropArrayIndex', {'buid': s_common.ehex(buid),
'form': form, 'prop': prop, 'indx': indx})
continue
else:
valu = sode.get('valu')
if valu is None:
await tryfix(lkey, buid)
yield ('NoValuForPropArrayIndex', {'buid': s_common.ehex(buid),
'form': form, 'prop': prop, 'indx': indx})
continue
propvalu, stortype = valu
try:
for indx in self.getStorIndx(stortype, propvalu):
if abrv + indx == lkey:
break
else:
await tryfix(lkey, buid)
yield ('SpurPropArrayKeyForIndex', {'buid': s_common.ehex(buid), 'form': form,
'prop': prop, 'indx': indx})
except IndexError:
await tryfix(lkey, buid)
yield ('NoStorTypeForPropArray', {'buid': s_common.ehex(buid), 'form': form,
'prop': prop, 'stortype': stortype})
async def verifyByTagProp(self, form, tag, prop, autofix=None):
abrv = self.getTagPropAbrv(form, tag, prop)
async def tryfix(lkey, buid):
if autofix == 'index':
self.layrslab.delete(lkey, buid, db=self.bytagprop)
for lkey, buid in self.layrslab.scanByPref(abrv, db=self.bytagprop):
await asyncio.sleep(0)
indx = lkey[len(abrv):]
sode = self._getStorNode(buid)
if sode is None:
await tryfix(lkey, buid)
yield ('NoNodeForTagPropIndex', {'buid': s_common.ehex(buid), 'form': form,
'tag': tag, 'prop': prop, 'indx': indx})
continue
tags = sode.get('tagprops')
if tags is None:
yield ('NoPropForTagPropIndex', {'buid': s_common.ehex(buid), 'form': form,
'tag': tag, 'prop': prop, 'indx': indx})
continue
props = tags.get(tag)
if props is None:
await tryfix(lkey, buid)
yield ('NoPropForTagPropIndex', {'buid': s_common.ehex(buid), 'form': form,
'tag': tag, 'prop': prop, 'indx': indx})
continue
valu = props.get(prop)
if valu is None:
await tryfix(lkey, buid)
yield ('NoValuForTagPropIndex', {'buid': s_common.ehex(buid), 'form': form,
'tag': tag, 'prop': prop, 'indx': indx})
continue
propvalu, stortype = valu
if stortype & STOR_FLAG_ARRAY: # pragma: no cover
# TODO: These aren't possible yet
stortype = STOR_TYPE_MSGP
try:
for indx in self.stortypes[stortype].indx(propvalu):
if abrv + indx == lkey:
break
else:
await tryfix(lkey, buid)
yield ('SpurTagPropKeyForIndex', {'buid': s_common.ehex(buid), 'form': form,
'tag': tag, 'prop': prop, 'indx': indx})
except IndexError:
await tryfix(lkey, buid)
yield ('NoStorTypeForTagProp', {'buid': s_common.ehex(buid), 'form': form,
'tag': tag, 'prop': prop, 'stortype': stortype})
async def verifyByBuid(self, buid, sode):
await asyncio.sleep(0)
form = sode.get('form')
stortags = sode.get('tags')
if stortags:
for tagname, storvalu in stortags.items():
async for error in self.verifyBuidTag(buid, form, tagname, storvalu):
yield error
storprops = sode.get('props')
if storprops:
for propname, (storvalu, stortype) in storprops.items():
# TODO: we dont support verifying array property indexes just yet...
if stortype & STOR_FLAG_ARRAY:
continue
try:
async for error in self.stortypes[stortype].verifyBuidProp(buid, form, propname, storvalu):
yield error
except IndexError as e:
yield ('NoStorTypeForProp', {'buid': s_common.ehex(buid), 'form': form, 'prop': propname,
'stortype': stortype})
async def pack(self):
ret = self.layrinfo.pack()
if ret.get('mirror'):
ret['mirror'] = s_urlhelp.sanitizeUrl(ret['mirror'])
ret['totalsize'] = await self.getLayerSize()
return ret
@s_nexus.Pusher.onPushAuto('layer:truncate')
async def truncate(self):
'''
Nuke all the contents in the layer, leaving an empty layer
NOTE: This internal API is deprecated but is kept for Nexus event backward compatibility
'''
s_common.deprecated('Layer.truncate')
self.dirty.clear()
self.buidcache.clear()
await self.layrslab.trash()
await self.nodeeditslab.trash()
await self.dataslab.trash()
await self._initLayerStorage()
# async def wipe(self, meta): ...
async def iterWipeNodeEdits(self):
await self._saveDirtySodes()
async for buid, sode in self.getStorNodes():
edits = []
async for verb, n2iden in self.iterNodeEdgesN1(buid):
edits.append((EDIT_EDGE_DEL, (verb, n2iden), ()))
async for prop, valu in self.iterNodeData(buid):
edits.append((EDIT_NODEDATA_DEL, (prop, valu), ()))
for tag, propdict in sode.get('tagprops', {}).items():
for prop, (valu, stortype) in propdict.items():
edits.append((EDIT_TAGPROP_DEL, (tag, prop, valu, stortype), ()))
for tag, tagv in sode.get('tags', {}).items():
edits.append((EDIT_TAG_DEL, (tag, tagv), ()))
for prop, (valu, stortype) in sode.get('props', {}).items():
edits.append((EDIT_PROP_DEL, (prop, valu, stortype), ()))
valu = sode.get('valu')
if valu is not None:
edits.append((EDIT_NODE_DEL, valu, ()))
yield (buid, sode.get('form'), edits)
async def clone(self, newdirn):
'''
Copy the contents of this layer to a new layer
'''
for root, dnames, fnames in os.walk(self.dirn, topdown=True):
relpath = os.path.relpath(root, start=self.dirn)
for name in list(dnames):
relname = os.path.join(relpath, name)
srcpath = s_common.genpath(root, name)
dstpath = s_common.genpath(newdirn, relname)
if srcpath in s_lmdbslab.Slab.allslabs:
slab = s_lmdbslab.Slab.allslabs[srcpath]
await slab.copyslab(dstpath)
dnames.remove(name)
continue
s_common.gendir(dstpath)
for name in fnames:
srcpath = s_common.genpath(root, name)
# skip unix sockets etc...
if not os.path.isfile(srcpath):
continue
dstpath = s_common.genpath(newdirn, relpath, name)
shutil.copy(srcpath, dstpath)
async def waitForHot(self):
'''
Wait for the layer's slab to be prefaulted and locked into memory if lockmemory is true, otherwise return.
'''
await self.layrslab.lockdoneevent.wait()
async def _layrV2toV3(self):
bybuid = self.layrslab.initdb('bybuid')
sode = collections.defaultdict(dict)
tostor = []
lastbuid = None
count = 0
forms = await self.getFormCounts()
minforms = sum(forms.values())
logger.warning(f'Converting layer from v2 to v3 storage (>={minforms} nodes): {self.dirn}')
for lkey, lval in self.layrslab.scanByFull(db=bybuid):
flag = lkey[32]
buid = lkey[:32]
if lastbuid != buid:
if lastbuid is not None:
count += 1
tostor.append((lastbuid, s_msgpack.en(sode)))
sode.clear()
if len(tostor) >= 10000:
logger.warning(f'...syncing 10k nodes @{count}')
self.layrslab.putmulti(tostor, db=self.bybuidv3)
tostor.clear()
lastbuid = buid
if flag == 0:
form, valu, stortype = s_msgpack.un(lval)
sode['form'] = form
sode['valu'] = (valu, stortype)
continue
if flag == 1:
name = lkey[33:].decode()
sode['props'][name] = s_msgpack.un(lval)
continue
if flag == 2:
name = lkey[33:].decode()
sode['tags'][name] = s_msgpack.un(lval)
continue
if flag == 3:
tag, prop = lkey[33:].decode().split(':')
if tag not in sode['tagprops']:
sode['tagprops'][tag] = {}
sode['tagprops'][tag][prop] = s_msgpack.un(lval)
continue
if flag == 9:
sode['form'] = lval.decode()
continue
logger.warning('Invalid flag %d found for buid %s during migration', flag, buid) # pragma: no cover
count += 1
# Mop up the leftovers
if lastbuid is not None:
count += 1
tostor.append((lastbuid, s_msgpack.en(sode)))
if tostor:
self.layrslab.putmulti(tostor, db=self.bybuidv3)
logger.warning('...removing old bybuid index')
self.layrslab.dropdb('bybuid')
self.meta.set('version', 3)
self.layrvers = 3
logger.warning(f'...complete! ({count} nodes)')
async def _layrV3toV5(self):
sode = collections.defaultdict(dict)
logger.warning(f'Cleaning layer byarray index: {self.dirn}')
for lkey, lval in self.layrslab.scanByFull(db=self.byarray):
abrv = lkey[:8]
(form, prop) = self.getAbrvProp(abrv)
if form is None or prop is None:
continue
byts = self.layrslab.get(lval, db=self.bybuidv3)
if byts is not None:
sode.update(s_msgpack.un(byts))
pval = sode['props'].get(prop)
if pval is None:
self.layrslab.delete(lkey, lval, db=self.byarray)
sode.clear()
continue
indxbyts = lkey[8:]
valu, stortype = pval
realtype = stortype & 0x7fff
realstor = self.stortypes[realtype]
for aval in valu:
if indxbyts in realstor.indx(aval):
break
else:
self.layrslab.delete(lkey, lval, db=self.byarray)
sode.clear()
self.meta.set('version', 5)
self.layrvers = 5
logger.warning(f'...complete!')
async def _layrV4toV5(self):
sode = collections.defaultdict(dict)
logger.warning(f'Rebuilding layer byarray index: {self.dirn}')
for byts, abrv in self.propabrv.slab.scanByFull(db=self.propabrv.name2abrv):
form, prop = s_msgpack.un(byts)
if form is None or prop is None:
continue
for lkey, buid in self.layrslab.scanByPref(abrv, db=self.byprop):
byts = self.layrslab.get(buid, db=self.bybuidv3)
if byts is not None:
sode.clear()
sode.update(s_msgpack.un(byts))
pval = sode['props'].get(prop)
if pval is None:
continue
valu, stortype = pval
if not stortype & STOR_FLAG_ARRAY:
break
for indx in self.getStorIndx(stortype, valu):
self.layrslab.put(abrv + indx, buid, db=self.byarray)
self.meta.set('version', 5)
self.layrvers = 5
logger.warning(f'...complete!')
async def _v5ToV7Buid(self, buid):
byts = self.layrslab.get(buid, db=self.bybuidv3)
if byts is None:
return
sode = s_msgpack.un(byts)
tagprops = sode.get('tagprops')
if tagprops is None:
return
edited_sode = False
# do this in a partially-covered / replay safe way
for tpkey, tpval in list(tagprops.items()):
if isinstance(tpkey, tuple):
tagprops.pop(tpkey)
edited_sode = True
tag, prop = tpkey
if tagprops.get(tag) is None:
tagprops[tag] = {}
if prop in tagprops[tag]:
continue
tagprops[tag][prop] = tpval
if edited_sode:
self.layrslab.put(buid, s_msgpack.en(sode), db=self.bybuidv3)
async def _layrV5toV7(self):
logger.warning(f'Updating tagprop keys in bytagprop index: {self.dirn}')
for lkey, buid in self.layrslab.scanByFull(db=self.bytagprop):
await self._v5ToV7Buid(buid)
self.meta.set('version', 7)
self.layrvers = 7
logger.warning('...complete!')
async def _v7toV8Prop(self, prop):
propname = prop.name
form = prop.form
if form:
form = form.name
try:
abrv = self.getPropAbrv(form, propname)
except s_exc.NoSuchAbrv:
return
isarray = False
if prop.type.stortype & STOR_FLAG_ARRAY:
isarray = True
araystor = self.stortypes[STOR_TYPE_MSGP]
for lkey, buid in self.layrslab.scanByPref(abrv, db=self.byarray):
self.layrslab.delete(lkey, buid, db=self.byarray)
hugestor = self.stortypes[STOR_TYPE_HUGENUM]
sode = collections.defaultdict(dict)
for lkey, buid in self.layrslab.scanByPref(abrv, db=self.byprop):
if isarray is False and len(lkey) == 28:
continue
byts = self.layrslab.get(buid, db=self.bybuidv3)
if byts is None:
self.layrslab.delete(lkey, buid, db=self.byprop)
continue
sode.update(s_msgpack.un(byts))
pval = sode['props'].get(propname)
if pval is None:
self.layrslab.delete(lkey, buid, db=self.byprop)
sode.clear()
continue
valu, _ = pval
if isarray:
try:
newval = prop.type.norm(valu)[0]
except s_exc.BadTypeValu:
logger.warning(f'Invalid value {valu} for prop {propname} for buid {buid}')
continue
if valu != newval:
nkey = abrv + araystor.indx(newval)[0]
if nkey != lkey:
self.layrslab.put(nkey, buid, db=self.byprop)
self.layrslab.delete(lkey, buid, db=self.byprop)
for aval in valu:
indx = hugestor.indx(aval)[0]
self.layrslab.put(abrv + indx, buid, db=self.byarray)
else:
try:
indx = hugestor.indx(valu)[0]
except Exception:
logger.warning(f'Invalid value {valu} for prop {propname} for buid {buid}')
continue
self.layrslab.put(abrv + indx, buid, db=self.byprop)
self.layrslab.delete(lkey, buid, db=self.byprop)
sode.clear()
async def _v7toV8TagProp(self, form, tag, prop):
try:
ftpabrv = self.getTagPropAbrv(form, tag, prop)
tpabrv = self.getTagPropAbrv(None, tag, prop)
except s_exc.NoSuchAbrv:
return
abrvlen = len(ftpabrv)
hugestor = self.stortypes[STOR_TYPE_HUGENUM]
sode = collections.defaultdict(dict)
for lkey, buid in self.layrslab.scanByPref(ftpabrv, db=self.bytagprop):
if len(lkey) == 28:
continue
byts = self.layrslab.get(buid, db=self.bybuidv3)
if byts is None:
self.layrslab.delete(lkey, buid, db=self.bytagprop)
continue
sode.update(s_msgpack.un(byts))
props = sode['tagprops'].get(tag)
if not props:
self.layrslab.delete(lkey, buid, db=self.bytagprop)
sode.clear()
continue
pval = props.get(prop)
if pval is None:
self.layrslab.delete(lkey, buid, db=self.bytagprop)
sode.clear()
continue
valu, _ = pval
try:
indx = hugestor.indx(valu)[0]
except Exception:
logger.warning(f'Invalid value {valu} for tagprop {tag}:{prop} for buid {buid}')
continue
self.layrslab.put(ftpabrv + indx, buid, db=self.bytagprop)
self.layrslab.put(tpabrv + indx, buid, db=self.bytagprop)
oldindx = lkey[abrvlen:]
self.layrslab.delete(lkey, buid, db=self.bytagprop)
self.layrslab.delete(tpabrv + oldindx, buid, db=self.bytagprop)
sode.clear()
async def _layrV7toV8(self):
logger.warning(f'Updating hugenum index values: {self.dirn}')
for name, prop in self.core.model.props.items():
stortype = prop.type.stortype
if stortype & STOR_FLAG_ARRAY:
stortype = stortype & 0x7fff
if stortype == STOR_TYPE_HUGENUM:
await self._v7toV8Prop(prop)
tagprops = set()
for name, prop in self.core.model.tagprops.items():
if prop.type.stortype == STOR_TYPE_HUGENUM:
tagprops.add(prop.name)
for form, tag, prop in self.getTagProps():
if form is None or prop not in tagprops:
continue
await self._v7toV8TagProp(form, tag, prop)
self.meta.set('version', 8)
self.layrvers = 8
logger.warning('...complete!')
async def _v8toV9Prop(self, prop):
propname = prop.name
form = prop.form
if form:
form = form.name
try:
if prop.isform:
abrv = self.getPropAbrv(form, None)
else:
abrv = self.getPropAbrv(form, propname)
except s_exc.NoSuchAbrv:
return
isarray = False
if prop.type.stortype & STOR_FLAG_ARRAY:
isarray = True
araystor = self.stortypes[STOR_TYPE_MSGP]
for lkey, buid in self.layrslab.scanByPref(abrv, db=self.byarray):
self.layrslab.delete(lkey, buid, db=self.byarray)
abrvlen = len(abrv)
hugestor = self.stortypes[STOR_TYPE_HUGENUM]
sode = collections.defaultdict(dict)
for lkey, buid in self.layrslab.scanByPref(abrv, db=self.byprop):
byts = self.layrslab.get(buid, db=self.bybuidv3)
if byts is None:
self.layrslab.delete(lkey, buid, db=self.byprop)
continue
sode.clear()
sode.update(s_msgpack.un(byts))
if prop.isform:
valu = sode['valu']
else:
valu = sode['props'].get(propname)
if valu is None:
self.layrslab.delete(lkey, buid, db=self.byprop)
continue
valu = valu[0]
if isarray:
for aval in valu:
try:
indx = hugestor.indx(aval)[0]
except Exception:
logger.warning(f'Invalid value {valu} for prop {propname} for buid {s_common.ehex(buid)}')
continue
self.layrslab.put(abrv + indx, buid, db=self.byarray)
else:
try:
indx = hugestor.indx(valu)[0]
except Exception:
logger.warning(f'Invalid value {valu} for prop {propname} for buid {s_common.ehex(buid)}')
continue
if indx == lkey[abrvlen:]:
continue
self.layrslab.put(abrv + indx, buid, db=self.byprop)
self.layrslab.delete(lkey, buid, db=self.byprop)
async def _v8toV9TagProp(self, form, tag, prop):
try:
ftpabrv = self.getTagPropAbrv(form, tag, prop)
tpabrv = self.getTagPropAbrv(None, tag, prop)
except s_exc.NoSuchAbrv:
return
abrvlen = len(ftpabrv)
hugestor = self.stortypes[STOR_TYPE_HUGENUM]
sode = collections.defaultdict(dict)
for lkey, buid in self.layrslab.scanByPref(ftpabrv, db=self.bytagprop):
byts = self.layrslab.get(buid, db=self.bybuidv3)
if byts is None:
self.layrslab.delete(lkey, buid, db=self.bytagprop)
continue
sode.clear()
sode.update(s_msgpack.un(byts))
props = sode['tagprops'].get(tag)
if not props:
self.layrslab.delete(lkey, buid, db=self.bytagprop)
continue
pval = props.get(prop)
if pval is None:
self.layrslab.delete(lkey, buid, db=self.bytagprop)
continue
valu, _ = pval
try:
indx = hugestor.indx(valu)[0]
except Exception:
logger.warning(f'Invalid value {valu} for tagprop {tag}:{prop} for buid {s_common.ehex(buid)}')
continue
if indx == lkey[abrvlen:]:
continue
self.layrslab.put(ftpabrv + indx, buid, db=self.bytagprop)
self.layrslab.put(tpabrv + indx, buid, db=self.bytagprop)
oldindx = lkey[abrvlen:]
self.layrslab.delete(lkey, buid, db=self.bytagprop)
self.layrslab.delete(tpabrv + oldindx, buid, db=self.bytagprop)
async def _layrV8toV9(self):
logger.warning(f'Checking hugenum index values: {self.dirn}')
for name, prop in self.core.model.props.items():
stortype = prop.type.stortype
if stortype & STOR_FLAG_ARRAY:
stortype = stortype & 0x7fff
if stortype == STOR_TYPE_HUGENUM:
await self._v8toV9Prop(prop)
tagprops = set()
for name, prop in self.core.model.tagprops.items():
if prop.type.stortype == STOR_TYPE_HUGENUM:
tagprops.add(prop.name)
for form, tag, prop in self.getTagProps():
if form is None or prop not in tagprops:
continue
await self._v8toV9TagProp(form, tag, prop)
self.meta.set('version', 9)
self.layrvers = 9
logger.warning('...complete!')
async def _initLayerStorage(self):
slabopts = {
'readonly': self.readonly,
'readahead': True,
'lockmemory': self.lockmemory,
'map_async': self.mapasync,
'max_replay_log': self.maxreplaylog,
}
if self.growsize is not None:
slabopts['growsize'] = self.growsize
otherslabopts = {
**slabopts,
'readahead': False, # less-used slabs don't need readahead
'lockmemory': False, # less-used slabs definitely don't get dedicated memory
}
path = s_common.genpath(self.dirn, 'layer_v2.lmdb')
nodedatapath = s_common.genpath(self.dirn, 'nodedata.lmdb')
self.layrslab = await s_lmdbslab.Slab.anit(path, **slabopts)
self.dataslab = await s_lmdbslab.Slab.anit(nodedatapath, **otherslabopts)
metadb = self.layrslab.initdb('layer:meta')
self.meta = s_lmdbslab.SlabDict(self.layrslab, db=metadb)
if self.fresh:
self.meta.set('version', 9)
self.formcounts = await self.layrslab.getHotCount('count:forms')
path = s_common.genpath(self.dirn, 'nodeedits.lmdb')
self.nodeeditslab = await s_lmdbslab.Slab.anit(path, **otherslabopts)
self.offsets = await self.layrslab.getHotCount('offsets')
self.tagabrv = self.layrslab.getNameAbrv('tagabrv')
self.propabrv = self.layrslab.getNameAbrv('propabrv')
self.tagpropabrv = self.layrslab.getNameAbrv('tagpropabrv')
self.onfini(self.layrslab)
self.onfini(self.nodeeditslab)
self.onfini(self.dataslab)
self.bybuidv3 = self.layrslab.initdb('bybuidv3')
self.byverb = self.layrslab.initdb('byverb', dupsort=True)
self.edgesn1 = self.layrslab.initdb('edgesn1', dupsort=True)
self.edgesn2 = self.layrslab.initdb('edgesn2', dupsort=True)
self.bytag = self.layrslab.initdb('bytag', dupsort=True)
self.byprop = self.layrslab.initdb('byprop', dupsort=True)
self.byarray = self.layrslab.initdb('byarray', dupsort=True)
self.bytagprop = self.layrslab.initdb('bytagprop', dupsort=True)
self.countdb = self.layrslab.initdb('counters')
self.nodedata = self.dataslab.initdb('nodedata')
self.dataname = self.dataslab.initdb('dataname', dupsort=True)
self.nodeeditlog = self.nodeeditctor(self.nodeeditslab, 'nodeedits')
self.layrslab.on('commit', self._onLayrSlabCommit)
self.layrvers = self.meta.get('version', 2)
if self.layrvers < 3:
await self._layrV2toV3()
if self.layrvers < 4:
await self._layrV3toV5()
if self.layrvers < 5:
await self._layrV4toV5()
if self.layrvers < 7:
await self._layrV5toV7()
if self.layrvers < 8:
await self._layrV7toV8()
if self.layrvers < 9:
await self._layrV8toV9()
if self.layrvers != 9:
mesg = f'Got layer version {self.layrvers}. Expected 9. Accidental downgrade?'
raise s_exc.BadStorageVersion(mesg=mesg)
async def getLayerSize(self):
'''
Get the total storage size for the layer.
'''
realsize, _ = s_common.getDirSize(self.dirn)
return realsize
@s_nexus.Pusher.onPushAuto('layer:set')
async def setLayerInfo(self, name, valu):
'''
Set a mutable layer property.
'''
if name not in ('name', 'desc', 'logedits'):
mesg = f'{name} is not a valid layer info key'
raise s_exc.BadOptValu(mesg=mesg)
if name == 'logedits':
valu = bool(valu)
self.logedits = valu
# TODO when we can set more props, we may need to parse values.
await self.layrinfo.set(name, valu)
await self.core.feedBeholder('layer:set', {'iden': self.iden, 'name': name, 'valu': valu}, gates=[self.iden])
return valu
async def stat(self):
ret = {**self.layrslab.statinfo(),
}
if self.logedits:
ret['nodeeditlog_indx'] = (self.nodeeditlog.index(), 0, 0)
return ret
async def _onLayrFini(self):
[(await wind.fini()) for wind in self.windows]
[futu.cancel() for futu in self.futures.values()]
if self.leader is not None:
await self.leader.fini()
async def getFormCounts(self):
return self.formcounts.pack()
@s_cache.memoizemethod()
def getPropAbrv(self, form, prop):
return self.propabrv.bytsToAbrv(s_msgpack.en((form, prop)))
def setPropAbrv(self, form, prop):
return self.propabrv.setBytsToAbrv(s_msgpack.en((form, prop)))
def getFormProps(self):
for byts in self.propabrv.keys():
yield s_msgpack.un(byts)
def getTagProps(self):
for byts in self.tagpropabrv.keys():
yield s_msgpack.un(byts)
@s_cache.memoizemethod()
def getTagPropAbrv(self, *args):
return self.tagpropabrv.bytsToAbrv(s_msgpack.en(args))
def setTagPropAbrv(self, *args):
return self.tagpropabrv.setBytsToAbrv(s_msgpack.en(args))
@s_cache.memoizemethod()
def getAbrvProp(self, abrv):
byts = self.propabrv.abrvToByts(abrv)
return s_msgpack.un(byts)
async def getNodeValu(self, buid, prop=None):
'''
Retrieve either the form valu or a prop valu for the given node by buid.
'''
sode = self._getStorNode(buid)
if sode is None: # pragma: no cover
return (None, None)
if prop is None:
return sode.get('valu', (None, None))[0]
return sode['props'].get(prop, (None, None))[0]
async def getNodeTag(self, buid, tag):
sode = self._getStorNode(buid)
if sode is None: # pragma: no cover
return None
return sode['tags'].get(tag)
async def getNodeForm(self, buid):
sode = self._getStorNode(buid)
if sode is None: # pragma: no cover
return None
return sode.get('form')
def setSodeDirty(self, buid, sode, form):
sode['form'] = form
self.dirty[buid] = sode
async def _onLayrSlabCommit(self, mesg):
await self._saveDirtySodes()
async def _saveDirtySodes(self):
if not self.dirty:
return
# flush any dirty storage nodes before the commit
kvlist = []
for buid, sode in self.dirty.items():
self.buidcache[buid] = sode
kvlist.append((buid, s_msgpack.en(sode)))
self.layrslab.putmulti(kvlist, db=self.bybuidv3)
self.dirty.clear()
async def getStorNode(self, buid):
sode = self._getStorNode(buid)
if sode is not None:
return deepcopy(sode)
return {}
def _getStorNode(self, buid):
'''
Return the storage node for the given buid.
NOTE: This API returns the *actual* storage node dict if it's
dirty. You must make a deep copy if you plan to return it
outside of the Layer.
'''
# check the dirty nodes first
sode = self.dirty.get(buid)
if sode is not None:
return sode
sode = self.buidcache.get(buid)
if sode is not None:
return sode
byts = self.layrslab.get(buid, db=self.bybuidv3)
if byts is None:
return None
sode = collections.defaultdict(dict)
sode.update(s_msgpack.un(byts))
self.buidcache[buid] = sode
return sode
def _genStorNode(self, buid):
# get or create the storage node. this returns the *actual* storage node
sode = self._getStorNode(buid)
if sode is not None:
return sode
sode = collections.defaultdict(dict)
self.buidcache[buid] = sode
return sode
async def getTagCount(self, tagname, formname=None):
'''
Return the number of tag rows in the layer for the given tag/form.
'''
try:
abrv = self.tagabrv.bytsToAbrv(tagname.encode())
if formname is not None:
abrv += self.getPropAbrv(formname, None)
except s_exc.NoSuchAbrv:
return 0
return await self.layrslab.countByPref(abrv, db=self.bytag)
async def getPropCount(self, formname, propname=None, maxsize=None):
'''
Return the number of property rows in the layer for the given form/prop.
'''
try:
abrv = self.getPropAbrv(formname, propname)
except s_exc.NoSuchAbrv:
return 0
return await self.layrslab.countByPref(abrv, db=self.byprop, maxsize=maxsize)
async def getUnivPropCount(self, propname, maxsize=None):
'''
Return the number of universal property rows in the layer for the given prop.
'''
try:
abrv = self.getPropAbrv(None, propname)
except s_exc.NoSuchAbrv:
return 0
return await self.layrslab.countByPref(abrv, db=self.byprop, maxsize=maxsize)
async def liftByTag(self, tag, form=None):
try:
abrv = self.tagabrv.bytsToAbrv(tag.encode())
if form is not None:
abrv += self.getPropAbrv(form, None)
except s_exc.NoSuchAbrv:
return
for lkey, buid in self.layrslab.scanByPref(abrv, db=self.bytag):
sode = self._getStorNode(buid)
if sode is None: # pragma: no cover
# logger.warning(f'TagIndex for #{tag} has {s_common.ehex(buid)} but no storage node.')
continue
yield None, buid, deepcopy(sode)
async def liftByTagValu(self, tag, cmpr, valu, form=None):
try:
abrv = self.tagabrv.bytsToAbrv(tag.encode())
if form is not None:
abrv += self.getPropAbrv(form, None)
except s_exc.NoSuchAbrv:
return
filt = StorTypeTag.getTagFilt(cmpr, valu)
if filt is None:
raise s_exc.NoSuchCmpr(cmpr=cmpr)
for lkey, buid in self.layrslab.scanByPref(abrv, db=self.bytag):
# filter based on the ival value before lifting the node...
valu = await self.getNodeTag(buid, tag)
if filt(valu):
sode = self._getStorNode(buid)
if sode is None: # pragma: no cover
# logger.warning(f'TagValuIndex for #{tag} has {s_common.ehex(buid)} but no storage node.')
continue
yield None, buid, deepcopy(sode)
async def hasTagProp(self, name):
async for _ in self.liftTagProp(name):
return True
return False
async def hasNodeData(self, buid, name):
try:
abrv = self.getPropAbrv(name, None)
except s_exc.NoSuchAbrv:
return False
return self.dataslab.has(buid + abrv, db=self.nodedata)
async def liftTagProp(self, name):
for form, tag, prop in self.getTagProps():
if form is not None or prop != name:
continue
try:
abrv = self.getTagPropAbrv(None, tag, name)
except s_exc.NoSuchAbrv:
continue
for _, buid in self.layrslab.scanByPref(abrv, db=self.bytagprop):
yield buid
async def liftByTagProp(self, form, tag, prop):
try:
abrv = self.getTagPropAbrv(form, tag, prop)
except s_exc.NoSuchAbrv:
return
for lkey, buid in self.layrslab.scanByPref(abrv, db=self.bytagprop):
sode = self._getStorNode(buid)
if sode is None: # pragma: no cover
# logger.warning(f'TagPropIndex for {form}#{tag}:{prop} has {s_common.ehex(buid)} but no storage node.')
continue
yield lkey[8:], buid, deepcopy(sode)
async def liftByTagPropValu(self, form, tag, prop, cmprvals):
'''
Note: form may be None
'''
for cmpr, valu, kind in cmprvals:
async for lkey, buid in self.stortypes[kind].indxByTagProp(form, tag, prop, cmpr, valu):
sode = self._getStorNode(buid)
if sode is None: # pragma: no cover
# logger.warning(f'TagPropValuIndex for {form}#{tag}:{prop} has {s_common.ehex(buid)} but no storage node.')
continue
yield lkey[8:], buid, deepcopy(sode)
async def liftByProp(self, form, prop):
try:
abrv = self.getPropAbrv(form, prop)
except s_exc.NoSuchAbrv:
return
for lkey, buid in self.layrslab.scanByPref(abrv, db=self.byprop):
sode = self._getStorNode(buid)
if sode is None: # pragma: no cover
# logger.warning(f'PropIndex for {form}:{prop} has {s_common.ehex(buid)} but no storage node.')
continue
yield lkey[8:], buid, deepcopy(sode)
# NOTE: form vs prop valu lifting is differentiated to allow merge sort
async def liftByFormValu(self, form, cmprvals):
for cmpr, valu, kind in cmprvals:
if kind & 0x8000:
kind = STOR_TYPE_MSGP
async for lkey, buid in self.stortypes[kind].indxByForm(form, cmpr, valu):
sode = self._getStorNode(buid)
if sode is None: # pragma: no cover
# logger.warning(f'FormValuIndex for {form} has {s_common.ehex(buid)} but no storage node.')
continue
yield lkey[8:], buid, deepcopy(sode)
async def liftByPropValu(self, form, prop, cmprvals):
for cmpr, valu, kind in cmprvals:
if kind & 0x8000:
kind = STOR_TYPE_MSGP
async for lkey, buid in self.stortypes[kind].indxByProp(form, prop, cmpr, valu):
sode = self._getStorNode(buid)
if sode is None: # pragma: no cover
# logger.warning(f'PropValuIndex for {form}:{prop} has {s_common.ehex(buid)} but no storage node.')
continue
yield lkey[8:], buid, deepcopy(sode)
async def liftByPropArray(self, form, prop, cmprvals):
for cmpr, valu, kind in cmprvals:
async for lkey, buid in self.stortypes[kind].indxByPropArray(form, prop, cmpr, valu):
sode = self._getStorNode(buid)
if sode is None: # pragma: no cover
# logger.warning(f'PropArrayIndex for {form}:{prop} has {s_common.ehex(buid)} but no storage node.')
continue
yield lkey[8:], buid, deepcopy(sode)
async def liftByDataName(self, name):
try:
abrv = self.getPropAbrv(name, None)
except s_exc.NoSuchAbrv:
return
for abrv, buid in self.dataslab.scanByDups(abrv, db=self.dataname):
sode = self._getStorNode(buid)
if sode is None: # pragma: no cover
# logger.warning(f'PropArrayIndex for {form}:{prop} has {s_common.ehex(buid)} but no storage node.')
continue
sode = deepcopy(sode)
byts = self.dataslab.get(buid + abrv, db=self.nodedata)
if byts is None:
# logger.warning(f'NodeData for {name} has {s_common.ehex(buid)} but no data.')
continue
sode['nodedata'] = {name: s_msgpack.un(byts)}
yield None, buid, sode
async def storNodeEdits(self, nodeedits, meta):
saveoff, results = await self.saveNodeEdits(nodeedits, meta)
retn = []
for buid, _, edits in results:
sode = await self.getStorNode(buid)
retn.append((buid, sode, edits))
return retn
async def _realSaveNodeEdits(self, edits, meta):
saveoff, changes = await self.saveNodeEdits(edits, meta)
retn = []
for buid, _, edits in changes:
sode = await self.getStorNode(buid)
retn.append((buid, sode, edits))
return saveoff, changes, retn
async def saveNodeEdits(self, edits, meta):
'''
Save node edits to the layer and return a tuple of (nexsoffs, changes).
Note: nexsoffs will be None if there are no changes.
'''
if self.ismirror:
if self.core.isactive:
proxy = await self.leader.proxy()
with self.getIdenFutu(iden=meta.get('task')) as (iden, futu):
meta['task'] = iden
moff, changes = await proxy.saveNodeEdits(edits, meta)
if any(c[2] for c in changes):
return await futu
return None, ()
proxy = await self.core.nexsroot.client.proxy()
indx, changes = await proxy.saveLayerNodeEdits(self.iden, edits, meta)
await self.core.nexsroot.waitOffs(indx)
return indx, changes
return await self.saveToNexs('edits', edits, meta)
@s_nexus.Pusher.onPush('edits', passitem=True)
async def _storNodeEdits(self, nodeedits, meta, nexsitem):
'''
Execute a series of node edit operations, returning the updated nodes.
Args:
nodeedits: List[Tuple(buid, form, edits, subedits)] List of requested changes per node
Returns:
List[Tuple[buid, form, edits]] Same list, but with only the edits actually applied (plus the old value)
'''
edited = False
# use/abuse python's dict ordering behavior
results = {}
nodeedits = collections.deque(nodeedits)
while nodeedits:
buid, form, edits = nodeedits.popleft()
sode = self._genStorNode(buid)
changes = []
for edit in edits:
delt = self.editors[edit[0]](buid, form, edit, sode, meta)
if delt and edit[2]:
nodeedits.extend(edit[2])
changes.extend(delt)
await asyncio.sleep(0)
flatedit = results.get(buid)
if flatedit is None:
results[buid] = flatedit = (buid, form, [])
flatedit[2].extend(changes)
if changes:
edited = True
flatedits = list(results.values())
if edited:
nexsindx = nexsitem[0] if nexsitem is not None else None
await self.fire('layer:write', layer=self.iden, edits=flatedits, meta=meta, nexsindx=nexsindx)
if self.logedits:
offs = self.nodeeditlog.add((flatedits, meta), indx=nexsindx)
[(await wind.put((offs, flatedits, meta))) for wind in tuple(self.windows)]
await asyncio.sleep(0)
return flatedits
def mayDelBuid(self, buid, sode):
if sode.get('valu'):
return
if sode.get('props'):
return
if sode.get('tags'):
return
if sode.get('tagprops'):
return
if self.dataslab.prefexists(buid, self.nodedata):
return
if self.layrslab.prefexists(buid, db=self.edgesn1):
return
# no more refs in this layer. time to pop it...
self.dirty.pop(buid, None)
self.buidcache.pop(buid, None)
self.layrslab.delete(buid, db=self.bybuidv3)
async def storNodeEditsNoLift(self, nodeedits, meta):
'''
Execute a series of node edit operations.
Does not return the updated nodes.
'''
await self._push('edits', nodeedits, meta)
def _editNodeAdd(self, buid, form, edit, sode, meta):
valt = edit[1]
valu, stortype = valt
if sode.get('valu') == valt:
return ()
sode['valu'] = valt
self.setSodeDirty(buid, sode, form)
abrv = self.setPropAbrv(form, None)
if stortype & STOR_FLAG_ARRAY:
for indx in self.getStorIndx(stortype, valu):
self.layrslab.put(abrv + indx, buid, db=self.byarray)
for indx in self.getStorIndx(STOR_TYPE_MSGP, valu):
self.layrslab.put(abrv + indx, buid, db=self.byprop)
else:
for indx in self.getStorIndx(stortype, valu):
self.layrslab.put(abrv + indx, buid, db=self.byprop)
self.formcounts.inc(form)
if self.nodeAddHook is not None:
self.nodeAddHook()
retn = [
(EDIT_NODE_ADD, (valu, stortype), ())
]
tick = meta.get('time')
if tick is None:
tick = s_common.now()
edit = (EDIT_PROP_SET, ('.created', tick, None, STOR_TYPE_MINTIME), ())
retn.extend(self._editPropSet(buid, form, edit, sode, meta))
return retn
def _editNodeDel(self, buid, form, edit, sode, meta):
valt = sode.pop('valu', None)
if valt is None:
# TODO tombstone
self.mayDelBuid(buid, sode)
return ()
self.setSodeDirty(buid, sode, form)
valu, stortype = valt
abrv = self.setPropAbrv(form, None)
if stortype & STOR_FLAG_ARRAY:
for indx in self.getStorIndx(stortype, valu):
self.layrslab.delete(abrv + indx, buid, db=self.byarray)
for indx in self.getStorIndx(STOR_TYPE_MSGP, valu):
self.layrslab.delete(abrv + indx, buid, db=self.byprop)
else:
for indx in self.getStorIndx(stortype, valu):
self.layrslab.delete(abrv + indx, buid, db=self.byprop)
self.formcounts.inc(form, valu=-1)
if self.nodeDelHook is not None:
self.nodeDelHook()
self._wipeNodeData(buid)
# TODO edits to become async so we can sleep(0) on large deletes?
self._delNodeEdges(buid)
self.buidcache.pop(buid, None)
self.mayDelBuid(buid, sode)
return (
(EDIT_NODE_DEL, (valu, stortype), ()),
)
def _editPropSet(self, buid, form, edit, sode, meta):
prop, valu, oldv, stortype = edit[1]
oldv, oldt = sode['props'].get(prop, (None, None))
abrv = self.setPropAbrv(form, prop)
univabrv = None
if prop[0] == '.': # '.' to detect universal props (as quickly as possible)
univabrv = self.setPropAbrv(None, prop)
if oldv is not None:
# merge intervals and min times
if stortype == STOR_TYPE_IVAL:
valu = (min(*oldv, *valu), max(*oldv, *valu))
elif stortype == STOR_TYPE_MINTIME:
valu = min(valu, oldv)
if valu == oldv:
return ()
if oldt & STOR_FLAG_ARRAY:
for oldi in self.getStorIndx(oldt, oldv):
self.layrslab.delete(abrv + oldi, buid, db=self.byarray)
if univabrv is not None:
self.layrslab.delete(univabrv + oldi, buid, db=self.byarray)
for indx in self.getStorIndx(STOR_TYPE_MSGP, oldv):
self.layrslab.delete(abrv + indx, buid, db=self.byprop)
if univabrv is not None:
self.layrslab.delete(univabrv + indx, buid, db=self.byprop)
else:
for oldi in self.getStorIndx(oldt, oldv):
self.layrslab.delete(abrv + oldi, buid, db=self.byprop)
if univabrv is not None:
self.layrslab.delete(univabrv + oldi, buid, db=self.byprop)
sode['props'][prop] = (valu, stortype)
self.setSodeDirty(buid, sode, form)
if stortype & STOR_FLAG_ARRAY:
for indx in self.getStorIndx(stortype, valu):
self.layrslab.put(abrv + indx, buid, db=self.byarray)
if univabrv is not None:
self.layrslab.put(univabrv + indx, buid, db=self.byarray)
for indx in self.getStorIndx(STOR_TYPE_MSGP, valu):
self.layrslab.put(abrv + indx, buid, db=self.byprop)
if univabrv is not None:
self.layrslab.put(univabrv + indx, buid, db=self.byprop)
else:
for indx in self.getStorIndx(stortype, valu):
self.layrslab.put(abrv + indx, buid, db=self.byprop)
if univabrv is not None:
self.layrslab.put(univabrv + indx, buid, db=self.byprop)
return (
(EDIT_PROP_SET, (prop, valu, oldv, stortype), ()),
)
def _editPropDel(self, buid, form, edit, sode, meta):
prop, oldv, stortype = edit[1]
abrv = self.setPropAbrv(form, prop)
univabrv = None
if prop[0] == '.': # '.' to detect universal props (as quickly as possible)
univabrv = self.setPropAbrv(None, prop)
valt = sode['props'].pop(prop, None)
if valt is None:
# FIXME tombstone
self.mayDelBuid(buid, sode)
return ()
self.setSodeDirty(buid, sode, form)
valu, stortype = valt
if stortype & STOR_FLAG_ARRAY:
realtype = stortype & 0x7fff
for aval in valu:
for indx in self.getStorIndx(realtype, aval):
self.layrslab.delete(abrv + indx, buid, db=self.byarray)
if univabrv is not None:
self.layrslab.delete(univabrv + indx, buid, db=self.byarray)
for indx in self.getStorIndx(STOR_TYPE_MSGP, valu):
self.layrslab.delete(abrv + indx, buid, db=self.byprop)
if univabrv is not None:
self.layrslab.delete(univabrv + indx, buid, db=self.byprop)
else:
for indx in self.getStorIndx(stortype, valu):
self.layrslab.delete(abrv + indx, buid, db=self.byprop)
if univabrv is not None:
self.layrslab.delete(univabrv + indx, buid, db=self.byprop)
self.mayDelBuid(buid, sode)
return (
(EDIT_PROP_DEL, (prop, valu, stortype), ()),
)
def _editTagSet(self, buid, form, edit, sode, meta):
if form is None: # pragma: no cover
logger.warning(f'Invalid tag set edit, form is None: {edit}')
return ()
tag, valu, oldv = edit[1]
tagabrv = self.tagabrv.setBytsToAbrv(tag.encode())
formabrv = self.setPropAbrv(form, None)
oldv = sode['tags'].get(tag)
if oldv is not None:
if oldv != (None, None) and valu != (None, None):
valu = (min(oldv[0], valu[0]), max(oldv[1], valu[1]))
if oldv == valu:
return ()
sode['tags'][tag] = valu
self.setSodeDirty(buid, sode, form)
self.layrslab.put(tagabrv + formabrv, buid, db=self.bytag)
return (
(EDIT_TAG_SET, (tag, valu, oldv), ()),
)
def _editTagDel(self, buid, form, edit, sode, meta):
tag, oldv = edit[1]
formabrv = self.setPropAbrv(form, None)
oldv = sode['tags'].pop(tag, None)
if oldv is None:
# TODO tombstone
self.mayDelBuid(buid, sode)
return ()
self.setSodeDirty(buid, sode, form)
tagabrv = self.tagabrv.bytsToAbrv(tag.encode())
self.layrslab.delete(tagabrv + formabrv, buid, db=self.bytag)
self.mayDelBuid(buid, sode)
return (
(EDIT_TAG_DEL, (tag, oldv), ()),
)
def _editTagPropSet(self, buid, form, edit, sode, meta):
if form is None: # pragma: no cover
logger.warning(f'Invalid tagprop set edit, form is None: {edit}')
return ()
tag, prop, valu, oldv, stortype = edit[1]
tp_abrv = self.setTagPropAbrv(None, tag, prop)
ftp_abrv = self.setTagPropAbrv(form, tag, prop)
tp_dict = sode['tagprops'].get(tag)
if tp_dict:
oldv, oldt = tp_dict.get(prop, (None, None))
if oldv is not None:
if valu == oldv and stortype == oldt:
return ()
for oldi in self.getStorIndx(oldt, oldv):
self.layrslab.delete(tp_abrv + oldi, buid, db=self.bytagprop)
self.layrslab.delete(ftp_abrv + oldi, buid, db=self.bytagprop)
if tag not in sode['tagprops']:
sode['tagprops'][tag] = {}
sode['tagprops'][tag][prop] = (valu, stortype)
self.setSodeDirty(buid, sode, form)
kvpairs = []
for indx in self.getStorIndx(stortype, valu):
kvpairs.append((tp_abrv + indx, buid))
kvpairs.append((ftp_abrv + indx, buid))
self.layrslab.putmulti(kvpairs, db=self.bytagprop)
return (
(EDIT_TAGPROP_SET, (tag, prop, valu, oldv, stortype), ()),
)
def _editTagPropDel(self, buid, form, edit, sode, meta):
tag, prop, valu, stortype = edit[1]
tp_dict = sode['tagprops'].get(tag)
if not tp_dict:
self.mayDelBuid(buid, sode)
return ()
oldv, oldt = tp_dict.pop(prop, (None, None))
if not tp_dict.get(tag):
sode['tagprops'].pop(tag, None)
if oldv is None:
self.mayDelBuid(buid, sode)
return ()
self.setSodeDirty(buid, sode, form)
tp_abrv = self.setTagPropAbrv(None, tag, prop)
ftp_abrv = self.setTagPropAbrv(form, tag, prop)
for oldi in self.getStorIndx(oldt, oldv):
self.layrslab.delete(tp_abrv + oldi, buid, db=self.bytagprop)
self.layrslab.delete(ftp_abrv + oldi, buid, db=self.bytagprop)
self.mayDelBuid(buid, sode)
return (
(EDIT_TAGPROP_DEL, (tag, prop, oldv, oldt), ()),
)
def _editNodeDataSet(self, buid, form, edit, sode, meta):
name, valu, oldv = edit[1]
abrv = self.setPropAbrv(name, None)
byts = s_msgpack.en(valu)
oldb = self.dataslab.replace(buid + abrv, byts, db=self.nodedata)
if oldb == byts:
return ()
# a bit of special case...
if sode.get('form') is None:
self.setSodeDirty(buid, sode, form)
if oldb is not None:
oldv = s_msgpack.un(oldb)
self.dataslab.put(abrv, buid, db=self.dataname)
return (
(EDIT_NODEDATA_SET, (name, valu, oldv), ()),
)
def _editNodeDataDel(self, buid, form, edit, sode, meta):
name, valu = edit[1]
abrv = self.setPropAbrv(name, None)
oldb = self.dataslab.pop(buid + abrv, db=self.nodedata)
if oldb is None:
self.mayDelBuid(buid, sode)
return ()
oldv = s_msgpack.un(oldb)
self.dataslab.delete(abrv, buid, db=self.dataname)
self.mayDelBuid(buid, sode)
return (
(EDIT_NODEDATA_DEL, (name, oldv), ()),
)
def _editNodeEdgeAdd(self, buid, form, edit, sode, meta):
if form is None: # pragma: no cover
logger.warning(f'Invalid node edge edit, form is None: {edit}')
return ()
verb, n2iden = edit[1]
venc = verb.encode()
n2buid = s_common.uhex(n2iden)
n1key = buid + venc
if self.layrslab.hasdup(n1key, n2buid, db=self.edgesn1):
return ()
# a bit of special case...
if sode.get('form') is None:
self.setSodeDirty(buid, sode, form)
self.layrslab.put(venc, buid + n2buid, db=self.byverb)
self.layrslab.put(n1key, n2buid, db=self.edgesn1)
self.layrslab.put(n2buid + venc, buid, db=self.edgesn2)
return (
(EDIT_EDGE_ADD, (verb, n2iden), ()),
)
def _editNodeEdgeDel(self, buid, form, edit, sode, meta):
verb, n2iden = edit[1]
venc = verb.encode()
n2buid = s_common.uhex(n2iden)
if not self.layrslab.delete(buid + venc, n2buid, db=self.edgesn1):
self.mayDelBuid(buid, sode)
return ()
self.layrslab.delete(venc, buid + n2buid, db=self.byverb)
self.layrslab.delete(n2buid + venc, buid, db=self.edgesn2)
self.mayDelBuid(buid, sode)
return (
(EDIT_EDGE_DEL, (verb, n2iden), ()),
)
async def getEdgeVerbs(self):
for lkey in self.layrslab.scanKeys(db=self.byverb):
yield lkey.decode()
async def getEdges(self, verb=None):
if verb is None:
for lkey, lval in self.layrslab.scanByFull(db=self.byverb):
yield (s_common.ehex(lval[:32]), lkey.decode(), s_common.ehex(lval[32:]))
return
for _, lval in self.layrslab.scanByDups(verb.encode(), db=self.byverb):
yield (s_common.ehex(lval[:32]), verb, s_common.ehex(lval[32:]))
def _delNodeEdges(self, buid):
for lkey, n2buid in self.layrslab.scanByPref(buid, db=self.edgesn1):
venc = lkey[32:]
self.layrslab.delete(venc, buid + n2buid, db=self.byverb)
self.layrslab.delete(lkey, n2buid, db=self.edgesn1)
self.layrslab.delete(n2buid + venc, buid, db=self.edgesn2)
def getStorIndx(self, stortype, valu):
if stortype & 0x8000:
realtype = stortype & 0x7fff
retn = []
[retn.extend(self.getStorIndx(realtype, aval)) for aval in valu]
return retn
return self.stortypes[stortype].indx(valu)
async def iterNodeEdgesN1(self, buid, verb=None):
pref = buid
if verb is not None:
pref += verb.encode()
for lkey, n2buid in self.layrslab.scanByPref(pref, db=self.edgesn1):
verb = lkey[32:].decode()
yield verb, s_common.ehex(n2buid)
async def iterNodeEdgesN2(self, buid, verb=None):
pref = buid
if verb is not None:
pref += verb.encode()
for lkey, n1buid in self.layrslab.scanByPref(pref, db=self.edgesn2):
verb = lkey[32:].decode()
yield verb, s_common.ehex(n1buid)
async def hasNodeEdge(self, buid1, verb, buid2):
lkey = buid1 + verb.encode()
return self.layrslab.hasdup(lkey, buid2, db=self.edgesn1)
async def iterFormRows(self, form, stortype=None, startvalu=None):
'''
Yields buid, valu tuples of nodes of a single form, optionally (re)starting at startvalu.
Args:
form (str): A form name.
stortype (Optional[int]): a STOR_TYPE_* integer representing the type of form:prop
startvalu (Any): The value to start at. May only be not None if stortype is not None.
Returns:
AsyncIterator[Tuple(buid, valu)]
'''
try:
indxby = IndxByForm(self, form)
except s_exc.NoSuchAbrv:
return
async for item in self._iterRows(indxby, stortype=stortype, startvalu=startvalu):
yield item
async def iterPropRows(self, form, prop, stortype=None, startvalu=None):
'''
Yields buid, valu tuples of nodes with a particular secondary property, optionally (re)starting at startvalu.
Args:
form (str): A form name.
prop (str): A universal property name.
stortype (Optional[int]): a STOR_TYPE_* integer representing the type of form:prop
startvalu (Any): The value to start at. May only be not None if stortype is not None.
Returns:
AsyncIterator[Tuple(buid, valu)]
'''
try:
indxby = IndxByProp(self, form, prop)
except s_exc.NoSuchAbrv:
return
async for item in self._iterRows(indxby, stortype=stortype, startvalu=startvalu):
yield item
async def iterUnivRows(self, prop, stortype=None, startvalu=None):
'''
Yields buid, valu tuples of nodes with a particular universal property, optionally (re)starting at startvalu.
Args:
prop (str): A universal property name.
stortype (Optional[int]): a STOR_TYPE_* integer representing the type of form:prop
startvalu (Any): The value to start at. May only be not None if stortype is not None.
Returns:
AsyncIterator[Tuple(buid, valu)]
'''
try:
indxby = IndxByProp(self, None, prop)
except s_exc.NoSuchAbrv:
return
async for item in self._iterRows(indxby, stortype=stortype, startvalu=startvalu):
yield item
async def iterTagRows(self, tag, form=None, starttupl=None):
'''
Yields (buid, (valu, form)) values that match a tag and optional form, optionally (re)starting at starttupl.
Args:
tag (str): the tag to match
form (Optional[str]): if present, only yields buids of nodes that match the form.
starttupl (Optional[Tuple[buid, form]]): if present, (re)starts the stream of values there.
Returns:
AsyncIterator[Tuple(buid, (valu, form))]
Note:
This yields (buid, (tagvalu, form)) instead of just buid, valu in order to allow resuming an interrupted
call by feeding the last value retrieved into starttupl
'''
try:
indxby = IndxByTag(self, form, tag)
except s_exc.NoSuchAbrv:
return
abrv = indxby.abrv
startkey = startvalu = None
if starttupl:
startbuid, startform = starttupl
startvalu = startbuid
if form:
if startform != form:
return # Caller specified a form but doesn't want to start on the same form?!
startkey = None
else:
try:
startkey = self.getPropAbrv(startform, None)
except s_exc.NoSuchAbrv:
return
for _, buid in self.layrslab.scanByPref(abrv, startkey=startkey, startvalu=startvalu, db=indxby.db):
item = indxby.getNodeValuForm(buid)
await asyncio.sleep(0)
if item is None:
continue
yield buid, item
async def iterTagPropRows(self, tag, prop, form=None, stortype=None, startvalu=None):
'''
Yields (buid, valu) that match a tag:prop, optionally (re)starting at startvalu.
Args:
tag (str): tag name
prop (str): prop name
form (Optional[str]): optional form name
stortype (Optional[int]): a STOR_TYPE_* integer representing the type of form:prop
startvalu (Any): The value to start at. May only be not None if stortype is not None.
Returns:
AsyncIterator[Tuple(buid, valu)]
'''
try:
indxby = IndxByTagProp(self, form, tag, prop)
except s_exc.NoSuchAbrv:
return
async for item in self._iterRows(indxby, stortype=stortype, startvalu=startvalu):
yield item
async def _iterRows(self, indxby, stortype=None, startvalu=None):
'''
Args:
stortype (Optional[int]): a STOR_TYPE_* integer representing the type of form:prop
startvalu (Any): The value to start at. May only be not None if stortype is not None.
Returns:
AsyncIterator[Tuple[buid,valu]]
'''
assert stortype is not None or startvalu is None
abrv = indxby.abrv
abrvlen = indxby.abrvlen
startbytz = None
if stortype:
stor = self.stortypes[stortype]
if startvalu is not None:
startbytz = stor.indx(startvalu)[0]
for key, buid in self.layrslab.scanByPref(abrv, startkey=startbytz, db=indxby.db):
if stortype is not None:
# Extract the value directly out of the end of the key
indx = key[abrvlen:]
valu = stor.decodeIndx(indx)
if valu is not s_common.novalu:
await asyncio.sleep(0)
yield buid, valu
continue
valu = indxby.getNodeValu(buid)
await asyncio.sleep(0)
if valu is None:
continue
yield buid, valu
async def getNodeData(self, buid, name):
'''
Return a single element of a buid's node data
'''
try:
abrv = self.getPropAbrv(name, None)
except s_exc.NoSuchAbrv:
return False, None
byts = self.dataslab.get(buid + abrv, db=self.nodedata)
if byts is None:
return False, None
return True, s_msgpack.un(byts)
async def iterNodeData(self, buid):
'''
Return a generator of all a buid's node data
'''
for lkey, byts in self.dataslab.scanByPref(buid, db=self.nodedata):
abrv = lkey[32:]
valu = s_msgpack.un(byts)
prop = self.getAbrvProp(abrv)
yield prop[0], valu
async def iterNodeDataKeys(self, buid):
'''
Return a generator of all a buid's node data keys
'''
for lkey in self.dataslab.scanKeysByPref(buid, db=self.nodedata):
abrv = lkey[32:]
prop = self.getAbrvProp(abrv)
yield prop[0]
async def iterLayerNodeEdits(self):
'''
Scan the full layer and yield artificial sets of nodeedits.
'''
await self._saveDirtySodes()
for buid, byts in self.layrslab.scanByFull(db=self.bybuidv3):
sode = s_msgpack.un(byts)
form = sode.get('form')
if form is None:
iden = s_common.ehex(buid)
logger.warning(f'NODE HAS NO FORM: {iden}')
continue
edits = []
nodeedit = (buid, form, edits)
# TODO tombstones
valt = sode.get('valu')
if valt is not None:
edits.append((EDIT_NODE_ADD, valt, ()))
for prop, (valu, stortype) in sode.get('props', {}).items():
edits.append((EDIT_PROP_SET, (prop, valu, None, stortype), ()))
for tag, tagv in sode.get('tags', {}).items():
edits.append((EDIT_TAG_SET, (tag, tagv, None), ()))
for tag, propdict in sode.get('tagprops', {}).items():
for prop, (valu, stortype) in propdict.items():
edits.append((EDIT_TAGPROP_SET, (tag, prop, valu, None, stortype), ()))
async for prop, valu in self.iterNodeData(buid):
edits.append((EDIT_NODEDATA_SET, (prop, valu, None), ()))
async for verb, n2iden in self.iterNodeEdgesN1(buid):
edits.append((EDIT_EDGE_ADD, (verb, n2iden), ()))
yield nodeedit
async def initUpstreamSync(self, url):
self.activetasks.append(self.schedCoro(self._initUpstreamSync(url)))
async def _initUpstreamSync(self, url):
'''
We're a downstream layer, receiving a stream of edits from an upstream layer telepath proxy at url
'''
while not self.isfini:
try:
async with await s_telepath.openurl(url) as proxy:
creator = self.layrinfo.get('creator')
iden = await proxy.getIden()
offs = self.offsets.get(iden)
logger.warning(f'upstream sync connected ({s_urlhelp.sanitizeUrl(url)} offset={offs})')
if offs == 0:
offs = await proxy.getEditIndx()
meta = {'time': s_common.now(),
'user': creator,
}
async for item in proxy.iterLayerNodeEdits():
await self.storNodeEditsNoLift([item], meta)
self.offsets.set(iden, offs)
waits = [v for k, v in self.upstreamwaits[iden].items() if k <= offs]
for wait in waits:
[e.set() for e in wait]
while not proxy.isfini:
offs = self.offsets.get(iden)
# pump them into a queue so we can consume them in chunks
q = asyncio.Queue(maxsize=1000)
async def consume(x):
try:
async for item in proxy.syncNodeEdits(x):
await q.put(item)
finally:
await q.put(None)
proxy.schedCoro(consume(offs))
done = False
while not done:
# get the next item so we maybe block...
item = await q.get()
if item is None:
break
items = [item]
# check if there are more we can eat
for _ in range(q.qsize()):
nexi = await q.get()
if nexi is None:
done = True
break
items.append(nexi)
for nodeeditoffs, item in items:
await self.storNodeEditsNoLift(item, {'time': s_common.now(),
'user': creator,
})
self.offsets.set(iden, nodeeditoffs + 1)
waits = self.upstreamwaits[iden].pop(nodeeditoffs + 1, None)
if waits is not None:
[e.set() for e in waits]
except asyncio.CancelledError: # pragma: no cover
return
except Exception:
logger.exception('error in initUpstreamSync loop')
await self.waitfini(1)
def _wipeNodeData(self, buid):
'''
Remove all node data for a buid
'''
for lkey, _ in self.dataslab.scanByPref(buid, db=self.nodedata):
self.dataslab.delete(lkey, db=self.nodedata)
async def getModelVers(self):
return self.layrinfo.get('model:version', (-1, -1, -1))
async def setModelVers(self, vers):
await self._push('layer:set:modelvers', vers)
@s_nexus.Pusher.onPush('layer:set:modelvers')
async def _setModelVers(self, vers):
await self.layrinfo.set('model:version', vers)
async def getStorNodes(self):
'''
Yield (buid, sode) tuples for all the nodes with props/tags/tagprops stored in this layer.
'''
done = set()
for buid, sode in list(self.dirty.items()):
done.add(buid)
yield buid, sode
for buid, byts in self.layrslab.scanByFull(db=self.bybuidv3):
if buid in done:
continue
yield buid, s_msgpack.un(byts)
await asyncio.sleep(0)
async def splices(self, offs=None, size=None):
'''
This API is deprecated.
Yield (offs, splice) tuples from the nodeedit log starting from the given offset.
Nodeedits will be flattened into splices before being yielded.
'''
s_common.deprecated('Layer.splices')
if not self.logedits:
return
if offs is None:
offs = (0, 0, 0)
if size is not None:
count = 0
async for offset, nodeedits, meta in self.iterNodeEditLog(offs[0]):
async for splice in self.makeSplices(offset, nodeedits, meta):
if splice[0] < offs:
continue
if count >= size:
return
yield splice
count = count + 1
else:
async for offset, nodeedits, meta in self.iterNodeEditLog(offs[0]):
async for splice in self.makeSplices(offset, nodeedits, meta):
if splice[0] < offs:
continue
yield splice
async def splicesBack(self, offs=None, size=None):
s_common.deprecated('Layer.splicesBack')
if not self.logedits:
return
if offs is None:
offs = (await self.getEditIndx(), 0, 0)
if size is not None:
count = 0
async for offset, nodeedits, meta in self.iterNodeEditLogBack(offs[0]):
async for splice in self.makeSplices(offset, nodeedits, meta, reverse=True):
if splice[0] > offs:
continue
if count >= size:
return
yield splice
count += 1
else:
async for offset, nodeedits, meta in self.iterNodeEditLogBack(offs[0]):
async for splice in self.makeSplices(offset, nodeedits, meta, reverse=True):
if splice[0] > offs:
continue
yield splice
async def iterNodeEditLog(self, offs=0):
'''
Iterate the node edit log and yield (offs, edits, meta) tuples.
'''
for offs, (edits, meta) in self.nodeeditlog.iter(offs):
yield (offs, edits, meta)
async def iterNodeEditLogBack(self, offs=0):
'''
Iterate the node edit log and yield (offs, edits, meta) tuples in reverse.
'''
for offs, (edits, meta) in self.nodeeditlog.iterBack(offs):
yield (offs, edits, meta)
async def syncNodeEdits2(self, offs, wait=True):
'''
Once caught up with storage, yield them in realtime.
Returns:
Tuple of offset(int), nodeedits, meta(dict)
'''
if not self.logedits:
return
for offi, (nodeedits, meta) in self.nodeeditlog.iter(offs):
yield (offi, nodeedits, meta)
if wait:
async with self.getNodeEditWindow() as wind:
async for item in wind:
yield item
async def syncNodeEdits(self, offs, wait=True):
'''
Identical to syncNodeEdits2, but doesn't yield meta
'''
async for offi, nodeedits, _meta in self.syncNodeEdits2(offs, wait=wait):
yield (offi, nodeedits)
async def syncIndexEvents(self, offs, matchdef, wait=True):
'''
Yield (offs, (buid, form, ETYPE, VALS, META)) tuples from the nodeedit log starting from the given offset.
Only edits that match the filter in matchdef will be yielded.
Notes:
ETYPE is an constant EDIT_* above. VALS is a tuple whose format depends on ETYPE, outlined in the comment
next to the constant. META is a dict that may contain keys 'user' and 'time' to represent the iden of the
user that initiated the change, and the time that it took place, respectively.
Additionally, every 1000 entries, an entry (offs, (None, None, EDIT_PROGRESS, (), ())) message is emitted.
The matchdef dict may contain the following keys: forms, props, tags, tagprops. The value must be a
sequence of strings. Each key/val combination is treated as an "or", so each key and value yields more events.
forms: EDIT_NODE_ADD and EDIT_NODE_DEL events. Matches events for nodes with forms in the value list.
props: EDIT_PROP_SET and EDIT_PROP_DEL events. Values must be in form:prop or .universal form
tags: EDIT_TAG_SET and EDIT_TAG_DEL events. Values must be the raw tag with no #.
tagprops: EDIT_TAGPROP_SET and EDIT_TAGPROP_DEL events. Values must be just the prop or tag:prop.
Will not yield any values if this layer was not created with logedits enabled
Args:
offs(int): starting nexus/editlog offset
matchdef(Dict[str, Sequence[str]]): a dict describing which events are yielded
wait(bool): whether to pend and stream value until this layer is fini'd
'''
formm = set(matchdef.get('forms', ()))
propm = set(matchdef.get('props', ()))
tagm = set(matchdef.get('tags', ()))
tagpropm = set(matchdef.get('tagprops', ()))
count = 0
async for curoff, editses in self.syncNodeEdits(offs, wait=wait):
for buid, form, edit in editses:
for etyp, vals, meta in edit:
if ((form in formm and etyp in (EDIT_NODE_ADD, EDIT_NODE_DEL))
or (etyp in (EDIT_PROP_SET, EDIT_PROP_DEL)
and (vals[0] in propm or f'{form}:{vals[0]}' in propm))
or (etyp in (EDIT_TAG_SET, EDIT_TAG_DEL) and vals[0] in tagm)
or (etyp in (EDIT_TAGPROP_SET, EDIT_TAGPROP_DEL)
and (vals[1] in tagpropm or f'{vals[0]}:{vals[1]}' in tagpropm))):
yield (curoff, (buid, form, etyp, vals, meta))
await asyncio.sleep(0)
count += 1
if count % 1000 == 0:
yield (curoff, (None, None, EDIT_PROGRESS, (), ()))
async def makeSplices(self, offs, nodeedits, meta, reverse=False):
'''
Flatten a set of nodeedits into splices.
'''
if meta is None:
meta = {}
user = meta.get('user')
time = meta.get('time')
prov = meta.get('prov')
if reverse:
nodegenr = reversed(list(enumerate(nodeedits)))
else:
nodegenr = enumerate(nodeedits)
for nodeoffs, (buid, form, edits) in nodegenr:
formvalu = None
if reverse:
editgenr = reversed(list(enumerate(edits)))
else:
editgenr = enumerate(edits)
for editoffs, (edit, info, _) in editgenr:
if edit in (EDIT_NODEDATA_SET, EDIT_NODEDATA_DEL, EDIT_EDGE_ADD, EDIT_EDGE_DEL):
continue
spliceoffs = (offs, nodeoffs, editoffs)
props = {
'time': time,
'user': user,
}
if prov is not None:
props['prov'] = prov
if edit == EDIT_NODE_ADD:
formvalu, stortype = info
props['ndef'] = (form, formvalu)
yield (spliceoffs, ('node:add', props))
continue
if edit == EDIT_NODE_DEL:
formvalu, stortype = info
props['ndef'] = (form, formvalu)
yield (spliceoffs, ('node:del', props))
continue
if formvalu is None:
formvalu = await self.getNodeValu(buid)
props['ndef'] = (form, formvalu)
if edit == EDIT_PROP_SET:
prop, valu, oldv, stortype = info
props['prop'] = prop
props['valu'] = valu
props['oldv'] = oldv
yield (spliceoffs, ('prop:set', props))
continue
if edit == EDIT_PROP_DEL:
prop, valu, stortype = info
props['prop'] = prop
props['valu'] = valu
yield (spliceoffs, ('prop:del', props))
continue
if edit == EDIT_TAG_SET:
tag, valu, oldv = info
props['tag'] = tag
props['valu'] = valu
props['oldv'] = oldv
yield (spliceoffs, ('tag:add', props))
continue
if edit == EDIT_TAG_DEL:
tag, valu = info
props['tag'] = tag
props['valu'] = valu
yield (spliceoffs, ('tag:del', props))
continue
if edit == EDIT_TAGPROP_SET:
tag, prop, valu, oldv, stortype = info
props['tag'] = tag
props['prop'] = prop
props['valu'] = valu
props['oldv'] = oldv
yield (spliceoffs, ('tag:prop:set', props))
continue
if edit == EDIT_TAGPROP_DEL:
tag, prop, valu, stortype = info
props['tag'] = tag
props['prop'] = prop
props['valu'] = valu
yield (spliceoffs, ('tag:prop:del', props))
@contextlib.asynccontextmanager
async def getNodeEditWindow(self):
if not self.logedits:
raise s_exc.BadConfValu(mesg='Layer logging must be enabled for getting nodeedits')
async with await s_queue.Window.anit(maxsize=10000) as wind:
async def fini():
self.windows.remove(wind)
wind.onfini(fini)
self.windows.append(wind)
yield wind
async def getEditIndx(self):
'''
Returns what will be the *next* (i.e. 1 past the last) nodeedit log index.
'''
if not self.logedits:
return 0
return self.nodeeditlog.index()
async def getEditOffs(self):
'''
Return the offset of the last *recorded* log entry. Returns -1 if nodeedit log is disabled or empty.
'''
if not self.logedits:
return -1
last = self.nodeeditlog.last()
if last is not None:
return last[0]
return -1
async def waitEditOffs(self, offs, timeout=None):
'''
Wait for the node edit log to write an entry at/past the given offset.
'''
if not self.logedits:
mesg = 'Layer.waitEditOffs() does not work with logedits disabled.'
raise s_exc.BadArg(mesg=mesg)
return await self.nodeeditlog.waitForOffset(offs, timeout=timeout)
async def waitUpstreamOffs(self, iden, offs):
evnt = asyncio.Event()
if self.offsets.get(iden) >= offs:
evnt.set()
else:
self.upstreamwaits[iden][offs].append(evnt)
return evnt
async def delete(self):
'''
Delete the underlying storage
'''
self.isdeleted = True
await self.fini()
shutil.rmtree(self.dirn, ignore_errors=True)
def getFlatEdits(nodeedits):
editsbynode = collections.defaultdict(list)
# flatten out conditional node edits
def addedits(buid, form, edits):
nkey = (buid, form)
for edittype, editinfo, condedits in edits:
editsbynode[nkey].append((edittype, editinfo, ()))
for condedit in condedits:
addedits(*condedit)
for buid, form, edits in nodeedits:
addedits(buid, form, edits)
return [(k[0], k[1], v) for (k, v) in editsbynode.items()]
def getNodeEditPerms(nodeedits):
'''
Yields (offs, perm) tuples that can be used in user.allowed()
'''
for nodeoffs, (buid, form, edits) in enumerate(nodeedits):
for editoffs, (edit, info, _) in enumerate(edits):
permoffs = (nodeoffs, editoffs)
if edit == EDIT_NODE_ADD:
yield (permoffs, ('node', 'add', form))
continue
if edit == EDIT_NODE_DEL:
yield (permoffs, ('node', 'del', form))
continue
if edit == EDIT_PROP_SET:
yield (permoffs, ('node', 'prop', 'set', f'{form}:{info[0]}'))
continue
if edit == EDIT_PROP_DEL:
yield (permoffs, ('node', 'prop', 'del', f'{form}:{info[0]}'))
continue
if edit == EDIT_TAG_SET:
yield (permoffs, ('node', 'tag', 'add', *info[0].split('.')))
continue
if edit == EDIT_TAG_DEL:
yield (permoffs, ('node', 'tag', 'del', *info[0].split('.')))
continue
if edit == EDIT_TAGPROP_SET:
yield (permoffs, ('node', 'tag', 'add', *info[0].split('.')))
continue
if edit == EDIT_TAGPROP_DEL:
yield (permoffs, ('node', 'tag', 'del', *info[0].split('.')))
continue
if edit == EDIT_NODEDATA_SET:
yield (permoffs, ('node', 'data', 'set', info[0]))
continue
if edit == EDIT_NODEDATA_DEL:
yield (permoffs, ('node', 'data', 'pop', info[0]))
continue
if edit == EDIT_EDGE_ADD:
yield (permoffs, ('node', 'edge', 'add', info[0]))
continue
if edit == EDIT_EDGE_DEL:
yield (permoffs, ('node', 'edge', 'del', info[0]))
continue
| {
"content_hash": "7b7d532e481ab2e3e5393c8b9bbf7afb",
"timestamp": "",
"source": "github",
"line_count": 4216,
"max_line_length": 128,
"avg_line_length": 32.40061669829222,
"alnum_prop": 0.5470896991969312,
"repo_name": "vertexproject/synapse",
"id": "cab07be64d807ac0b5ead47a94cda245b9ff1365",
"size": "136601",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "synapse/lib/layer.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "4010"
},
{
"name": "HTML",
"bytes": "3"
},
{
"name": "Python",
"bytes": "5894053"
},
{
"name": "Shell",
"bytes": "10776"
}
],
"symlink_target": ""
} |
typeof(SVGeneration) == "undefined" && (SVGeneration = {});
SVGeneration.Editor = React.createClass({displayName: "Editor",
getInitialState: function() {
return {
active: 'Parameters',
image: false,
windowHeight: $(window).height()
};
},
componentDidMount: function() {
this.loadData();
$(window).resize(function(){
this.setState({
windowHeight: $(window).height()
})
})
},
loadData: function(){
$.ajax({
url: '/recipes/3d_cubes/config.json',
type: 'get',
success: function (data) {
this.setState({image: data});
}.bind(this)
});
},
navigate: function(active){
this.setState({active: active})
},
render: function() {
var topPadding = this.state.windowHeight - 64 - 164;
return (
React.createElement("div", {className: "editor", style: {paddingTop: topPadding}},
React.createElement("div", {className: "editor-controls"},
React.createElement("h1", {className: "image-title"}, "Stripes"),
React.createElement(SVGeneration.TabBar, {navigate: this.navigate, active: this.state.active}),
React.createElement(SVGeneration.Tabs, {active: this.state.active})
)
)
);
}
});
SVGeneration.TabBar = React.createClass({displayName: "TabBar",
renderTab: function(label){
var baseClass = "pure-u-1-3 tab";
return React.createElement("a", {onClick: this.navigate(label), className: this.props.active == label ? ' active '+baseClass : baseClass}, label)
},
navigate: function(label){
return function(){
this.props.navigate(label);
}.bind(this);
},
render: function(){
return (
React.createElement("div", {className: "tab-bar pure-g"},
this.renderTab('Parameters'),
this.renderTab('Source Code'),
this.renderTab('Export')
)
);
}
});
SVGeneration.Tabs = React.createClass({displayName: "Tabs",
render: function(){
var inner = '';
if (this.props.active == 'Parameters') {
inner = React.createElement(SVGeneration.ParamsTab, null)
} else if (this.props.active == 'Source Code') {
inner = React.createElement(SVGeneration.SourceTab, null)
} else {
inner = React.createElement(SVGeneration.ExportTab, null)
}
return (
React.createElement("div", {className: "inner-tab"},
inner
)
)
}
});
SVGeneration.ParamsTab = React.createClass({displayName: "ParamsTab",
render: function(){
return (
React.createElement("div", {className: ""},
"Params"
)
);
}
});
SVGeneration.SourceTab = React.createClass({displayName: "SourceTab",
render: function(){
return (
React.createElement("div", {className: ""},
"Source"
)
);
}
});
SVGeneration.ExportTab = React.createClass({displayName: "ExportTab",
render: function(){
return (
React.createElement("div", {className: ""},
"Export"
)
);
}
});
SVGeneration.IntegerSlider = React.createClass({displayName: "IntegerSlider",
render: function(){
return
}
});
SVGeneration.ColorPicker = React.createClass({displayName: "ColorPicker",
render: function(){
return
}
}) | {
"content_hash": "7c8903d365b7a30dd19d0c2228842046",
"timestamp": "",
"source": "github",
"line_count": 123,
"max_line_length": 149,
"avg_line_length": 26.43089430894309,
"alnum_prop": 0.6071977852968318,
"repo_name": "DDKnoll/SVGeneration",
"id": "1f8048cedb6bad9241042e1aed7d530ff9fc490c",
"size": "3251",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/.module-cache/03d12fe6b75f849f1acd6e10e00bd3bc52f8c520.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "42295"
},
{
"name": "HTML",
"bytes": "6679"
},
{
"name": "JavaScript",
"bytes": "3180777"
}
],
"symlink_target": ""
} |
package uk.co.real_logic.aeron.common.concurrent.logbuffer;
import uk.co.real_logic.agrona.DirectBuffer;
import uk.co.real_logic.agrona.concurrent.UnsafeBuffer;
import static uk.co.real_logic.agrona.BitUtil.align;
import static uk.co.real_logic.aeron.common.concurrent.logbuffer.FrameDescriptor.*;
import static uk.co.real_logic.aeron.common.concurrent.logbuffer.FrameDescriptor.PADDING_FRAME_TYPE;
import static uk.co.real_logic.aeron.common.concurrent.logbuffer.LogBufferDescriptor.TAIL_COUNTER_OFFSET;
/**
* Log buffer appender which supports many producers concurrently writing an append-only log.
*
* <b>Note:</b> This class is threadsafe.
*
* Messages are appending to a log using a framing protocol as described in {@link FrameDescriptor}.
* If a message is larger than what will fit in a single frame will be fragmented up to {@link #maxMessageLength()}.
*
* A default message header is applied to each message with the fields filled in for fragment flags, sequence number,
* and frame length as appropriate.
*
* A message of type {@link FrameDescriptor#PADDING_FRAME_TYPE} is appended at the end of the buffer if claimed
* space is not sufficiently large to accommodate the message about to be written.
*/
public class LogAppender extends LogBuffer
{
public enum ActionStatus
{
SUCCESS,
TRIPPED,
FAILURE,
}
private final byte[] defaultHeader;
private final int headerLength;
private final int maxMessageLength;
private final int maxFrameLength;
private final int maxPayloadLength;
/**
* Construct a view over a log buffer and state buffer for appending frames.
*
* @param logBuffer for where messages are stored.
* @param stateBuffer for where the state of writers is stored manage concurrency.
* @param defaultHeader to be applied for each frame logged.
* @param maxFrameLength maximum frame length supported by the underlying transport.
*/
public LogAppender(
final UnsafeBuffer logBuffer, final UnsafeBuffer stateBuffer, final byte[] defaultHeader, final int maxFrameLength)
{
super(logBuffer, stateBuffer);
checkHeaderLength(defaultHeader.length);
checkMaxFrameLength(maxFrameLength);
this.defaultHeader = defaultHeader;
this.headerLength = defaultHeader.length;
this.maxFrameLength = maxFrameLength;
this.maxMessageLength = FrameDescriptor.calculateMaxMessageLength(capacity());
this.maxPayloadLength = maxFrameLength - headerLength;
}
/**
* The maximum length of a message that can be recorded in the log.
*
* @return the maximum length of a message that can be recorded in the log.
*/
public int maxMessageLength()
{
return maxMessageLength;
}
/**
* The maximum length of a message payload within a frame before fragmentation takes place.
*
* @return the maximum length of a message that can be recorded in the log.
*/
public int maxPayloadLength()
{
return maxPayloadLength;
}
/**
* The maximum length of a frame, including header, that can be recorded in the log.
*
* @return the maximum length of a frame, including header, that can be recorded in the log.
*/
public int maxFrameLength()
{
return maxFrameLength;
}
/**
* The default header applied to each record.
*
* @return the default header applied to each record.
*/
public byte[] defaultHeader()
{
return defaultHeader;
}
/**
* Append a message to the log if sufficient capacity exists.
*
* @param srcBuffer containing the encoded message.
* @param srcOffset at which the encoded message begins.
* @param length of the message in bytes.
* @return SUCCESS if append was successful, FAILURE if beyond end of the log in the log, TRIPPED if first failure.
* @throws IllegalArgumentException if the length is greater than {@link #maxMessageLength()}
*/
public ActionStatus append(final DirectBuffer srcBuffer, final int srcOffset, final int length)
{
checkMessageLength(length);
if (length <= maxPayloadLength)
{
return appendUnfragmentedMessage(srcBuffer, srcOffset, length);
}
return appendFragmentedMessage(srcBuffer, srcOffset, length);
}
/**
* Claim a range within the buffer for recording a message payload.
*
* @param length of the message payload
* @param bufferClaim to be completed for the claim if successful.
* @return SUCCESS if claim was successful, FAILURE if beyond end of the log in the log, TRIPPED if first failure.
*/
public ActionStatus claim(final int length, final BufferClaim bufferClaim)
{
if (length > maxPayloadLength)
{
final String s = String.format("claim exceeds maxPayloadLength of %d, length=%d", maxPayloadLength, length);
throw new IllegalArgumentException(s);
}
final int headerLength = this.headerLength;
final int frameLength = length + headerLength;
final int alignedLength = align(frameLength, FRAME_ALIGNMENT);
final int frameOffset = getTailAndAdd(alignedLength);
final UnsafeBuffer logBuffer = logBuffer();
final int capacity = capacity();
if (isBeyondLogBufferCapacity(frameOffset, alignedLength, capacity))
{
if (frameOffset < capacity)
{
appendPaddingFrame(logBuffer, frameOffset);
return ActionStatus.TRIPPED;
}
else if (frameOffset == capacity)
{
return ActionStatus.TRIPPED;
}
return ActionStatus.FAILURE;
}
logBuffer.putBytes(frameOffset, defaultHeader, 0, headerLength);
frameFlags(logBuffer, frameOffset, UNFRAGMENTED);
frameTermOffset(logBuffer, frameOffset, frameOffset);
bufferClaim.buffer(logBuffer)
.offset(frameOffset + headerLength)
.length(length)
.frameLengthOffset(lengthOffset(frameOffset))
.frameLength(frameLength);
return ActionStatus.SUCCESS;
}
private ActionStatus appendUnfragmentedMessage(final DirectBuffer srcBuffer, final int srcOffset, final int length)
{
final int headerLength = this.headerLength;
final int frameLength = length + headerLength;
final int alignedLength = align(frameLength, FRAME_ALIGNMENT);
final int frameOffset = getTailAndAdd(alignedLength);
final UnsafeBuffer logBuffer = logBuffer();
final int capacity = capacity();
if (isBeyondLogBufferCapacity(frameOffset, alignedLength, capacity))
{
if (frameOffset < capacity)
{
appendPaddingFrame(logBuffer, frameOffset);
return ActionStatus.TRIPPED;
}
else if (frameOffset == capacity)
{
return ActionStatus.TRIPPED;
}
return ActionStatus.FAILURE;
}
logBuffer.putBytes(frameOffset, defaultHeader, 0, headerLength);
logBuffer.putBytes(frameOffset + headerLength, srcBuffer, srcOffset, length);
frameFlags(logBuffer, frameOffset, UNFRAGMENTED);
frameTermOffset(logBuffer, frameOffset, frameOffset);
frameLengthOrdered(logBuffer, frameOffset, frameLength);
return ActionStatus.SUCCESS;
}
private ActionStatus appendFragmentedMessage(final DirectBuffer srcBuffer, final int srcOffset, final int length)
{
final int numMaxPayloads = length / maxPayloadLength;
final int remainingPayload = length % maxPayloadLength;
final int headerLength = this.headerLength;
final int requiredCapacity =
align(remainingPayload + headerLength, FRAME_ALIGNMENT) + (numMaxPayloads * maxFrameLength);
int frameOffset = getTailAndAdd(requiredCapacity);
final UnsafeBuffer logBuffer = logBuffer();
final int capacity = capacity();
if (isBeyondLogBufferCapacity(frameOffset, requiredCapacity, capacity))
{
if (frameOffset < capacity)
{
appendPaddingFrame(logBuffer, frameOffset);
return ActionStatus.TRIPPED;
}
else if (frameOffset == capacity)
{
return ActionStatus.TRIPPED;
}
return ActionStatus.FAILURE;
}
byte flags = BEGIN_FRAG;
int remaining = length;
do
{
final int bytesToWrite = Math.min(remaining, maxPayloadLength);
final int frameLength = bytesToWrite + headerLength;
final int alignedLength = align(frameLength, FRAME_ALIGNMENT);
logBuffer.putBytes(frameOffset, defaultHeader, 0, headerLength);
logBuffer.putBytes(
frameOffset + headerLength,
srcBuffer,
srcOffset + (length - remaining),
bytesToWrite);
if (remaining <= maxPayloadLength)
{
flags |= END_FRAG;
}
frameFlags(logBuffer, frameOffset, flags);
frameTermOffset(logBuffer, frameOffset, frameOffset);
frameLengthOrdered(logBuffer, frameOffset, frameLength);
flags = 0;
frameOffset += alignedLength;
remaining -= bytesToWrite;
}
while (remaining > 0);
return ActionStatus.SUCCESS;
}
private boolean isBeyondLogBufferCapacity(final int frameOffset, final int alignedFrameLength, final int capacity)
{
return (frameOffset + alignedFrameLength + headerLength) > capacity;
}
private void appendPaddingFrame(final UnsafeBuffer logBuffer, final int frameOffset)
{
logBuffer.putBytes(frameOffset, defaultHeader, 0, headerLength);
frameType(logBuffer, frameOffset, PADDING_FRAME_TYPE);
frameFlags(logBuffer, frameOffset, UNFRAGMENTED);
frameTermOffset(logBuffer, frameOffset, frameOffset);
frameLengthOrdered(logBuffer, frameOffset, capacity() - frameOffset);
}
private int getTailAndAdd(final int delta)
{
return stateBuffer().getAndAddInt(TAIL_COUNTER_OFFSET, delta);
}
private void checkMessageLength(final int length)
{
if (length > maxMessageLength)
{
final String s = String.format("encoded message exceeds maxMessageLength of %d, length=%d", maxMessageLength, length);
throw new IllegalArgumentException(s);
}
}
}
| {
"content_hash": "6185fad8e4901113f634fda0837fba20",
"timestamp": "",
"source": "github",
"line_count": 297,
"max_line_length": 130,
"avg_line_length": 36.26262626262626,
"alnum_prop": 0.6563602599814299,
"repo_name": "qed-/Aeron",
"id": "5cbf6f6c5443d3b3d996a87ab4d85d71506d206c",
"size": "11364",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aeron-common/src/main/java/uk/co/real_logic/aeron/common/concurrent/logbuffer/LogAppender.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "37896"
},
{
"name": "C++",
"bytes": "126672"
},
{
"name": "Java",
"bytes": "1006010"
},
{
"name": "Shell",
"bytes": "118"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="@layout/toolbar_layout"/>
<ListView
android:background="@color/me"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="@+id/chat_list_view"
>
</ListView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="@color/white"
>
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:src="@drawable/chat_send_sound"
android:layout_gravity="center_vertical"
android:id="@+id/chat_iv_send_sound"
/>
<EditText
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:maxLines="3"
android:id="@+id/chat_et_send_text"
/>
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:src="@drawable/chat_emoji"
android:layout_gravity="center_vertical"
android:id="@+id/chat_iv_send_emoji"
/>
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_marginLeft="10dp"
android:layout_marginRight="5dp"
android:layout_width="30dp"
android:layout_height="30dp"
android:src="@drawable/chat_add_more"
android:layout_gravity="center_vertical"
android:id="@+id/chat_iv_ad_more"
android:layout_marginTop="4dp"
/>
<Button
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:text="发送"
android:background="@color/tool_button"
android:minHeight="0dp"
android:padding="10dp"
android:layout_gravity="center_vertical"
android:id="@+id/chat_btn_send"
android:visibility="gone"
/>
</FrameLayout>
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="300dp"
android:background="@color/me"
android:visibility="gone"
android:id="@+id/chat_fl_hidde"
>
</FrameLayout>
</LinearLayout> | {
"content_hash": "ab5fe37b3c6b18d2631e3beadcaa6536",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 72,
"avg_line_length": 35.325301204819276,
"alnum_prop": 0.5552523874488404,
"repo_name": "changchengfeng/fantastchat",
"id": "29a00ef39566a116c5edea9b08c053a54ebaddcf",
"size": "2936",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/layout/activity_chat.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "183087"
}
],
"symlink_target": ""
} |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#pragma once
// forward declarations
class IStructDeserializerBackend;
class UStruct;
/**
* Enumerates policies for various errors during de-serialization.
*/
enum class EStructDeserializerErrorPolicies
{
/** Fail the de-serialization. */
Error,
/** Ignore the error (default). */
Ignore,
/** Print a warning to the log. */
Warning,
};
/**
* Structure for UStruct serialization policies.
*/
struct FStructDeserializerPolicies
{
/** Holds the policy for handling missing fields. */
EStructDeserializerErrorPolicies MissingFields;
/** Default constructor. */
FStructDeserializerPolicies()
: MissingFields(EStructDeserializerErrorPolicies::Ignore)
{ }
};
/**
* Implements a static class that can deserialize UStruct based types.
*
* This class implements the basic functionality for the serialization of UStructs, such as
* iterating a structure's properties and writing property values. The actual reading of
* serialized input data is performed by de-serialization backends, which allows this
* class to remain serialization format agnostic.
*/
class FStructDeserializer
{
public:
/**
* Deserializes a data structure from an archive using the specified policy.
*
* @param OutStruct A pointer to the data structure to deserialize into.
* @param TypeInfo The data structure's type information.
* @param Backend The de-serialization backend to use.
* @param Policies The de-serialization policies to use.
* @return true if deserialization was successful, false otherwise.
*/
SERIALIZATION_API static bool Deserialize( void* OutStruct, UStruct& TypeInfo, IStructDeserializerBackend& Backend, const FStructDeserializerPolicies& Policies );
/**
* Deserializes a data structure from an archive using the default policy.
*
* @param OutStruct A pointer to the data structure to deserialize into.
* @param TypeInfo The data structure's type information.
* @param Backend The de-serialization backend to use.
* @return true if deserialization was successful, false otherwise.
*/
static bool Deserialize( void* OutStruct, UStruct& TypeInfo, IStructDeserializerBackend& Backend )
{
return Deserialize(OutStruct, TypeInfo, Backend, FStructDeserializerPolicies());
}
public:
/**
* Deserializes a data structure from an archive using the default policy.
*
* @param OutStruct The struct to deserialize into.
* @param Backend The de-serialization backend to use.
* @return true if deserialization was successful, false otherwise.
*/
template<typename StructType>
static bool Deserialize( StructType& OutStruct, IStructDeserializerBackend& Backend )
{
return Deserialize(&OutStruct, *StructType::StaticStruct(), Backend);
}
/**
* Deserializes a data structure from an archive using the specified policy.
*
* @param OutStruct The struct to deserialize into.
* @param Backend The de-serialization backend to use.
* @param Policies The de-serialization policies to use.
* @return true if deserialization was successful, false otherwise.
*/
template<typename StructType>
static bool Deserialize( StructType& OutStruct, IStructDeserializerBackend& Backend, const FStructDeserializerPolicies& Policies )
{
return Deserialize(&OutStruct, *StructType::StaticStruct(), Backend, Policies);
}
};
| {
"content_hash": "b74d0d6908d3fbbb916f2d03b81b2944",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 163,
"avg_line_length": 31.59433962264151,
"alnum_prop": 0.7590325470289638,
"repo_name": "PopCap/GameIdea",
"id": "85a42b4e6c29fa4e6ae331f7084180237f599116",
"size": "3349",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Engine/Source/Runtime/Serialization/Public/StructDeserializer.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "ASP",
"bytes": "238055"
},
{
"name": "Assembly",
"bytes": "184134"
},
{
"name": "Batchfile",
"bytes": "116983"
},
{
"name": "C",
"bytes": "84264210"
},
{
"name": "C#",
"bytes": "9612596"
},
{
"name": "C++",
"bytes": "242290999"
},
{
"name": "CMake",
"bytes": "548754"
},
{
"name": "CSS",
"bytes": "134910"
},
{
"name": "GLSL",
"bytes": "96780"
},
{
"name": "HLSL",
"bytes": "124014"
},
{
"name": "HTML",
"bytes": "4097051"
},
{
"name": "Java",
"bytes": "757767"
},
{
"name": "JavaScript",
"bytes": "2742822"
},
{
"name": "Makefile",
"bytes": "1976144"
},
{
"name": "Objective-C",
"bytes": "75778979"
},
{
"name": "Objective-C++",
"bytes": "312592"
},
{
"name": "PAWN",
"bytes": "2029"
},
{
"name": "PHP",
"bytes": "10309"
},
{
"name": "PLSQL",
"bytes": "130426"
},
{
"name": "Pascal",
"bytes": "23662"
},
{
"name": "Perl",
"bytes": "218656"
},
{
"name": "Python",
"bytes": "21593012"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "Shell",
"bytes": "2889614"
},
{
"name": "Tcl",
"bytes": "1452"
}
],
"symlink_target": ""
} |
//===----------------------------------------------------------------------===//
//
// Peloton
//
// tuple_sampler.cpp
//
// Identification: src/optimizer/tuple_sampler.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <cinttypes>
#include "optimizer/stats/tuple_sampler.h"
#include "storage/data_table.h"
#include "storage/tile_group.h"
#include "storage/tile_group_header.h"
#include "storage/tile.h"
#include "storage/tuple.h"
namespace peloton {
namespace optimizer {
/**
* AcquireSampleTuples - Sample a certain number of tuples from a given table.
* This function performs random sampling by generating random tile_group_offset
* and random tuple_offset.
*/
size_t TupleSampler::AcquireSampleTuples(size_t target_sample_count) {
size_t tuple_count = table->GetTupleCount();
size_t tile_group_count = table->GetTileGroupCount();
LOG_TRACE("tuple_count = %lu, tile_group_count = %lu", tuple_count,
tile_group_count);
if (tuple_count < target_sample_count) {
target_sample_count = tuple_count;
}
size_t rand_tilegroup_offset, rand_tuple_offset;
srand(time(NULL));
catalog::Schema *tuple_schema = table->GetSchema();
while (sampled_tuples.size() < target_sample_count) {
// Generate a random tilegroup offset
rand_tilegroup_offset = rand() % tile_group_count;
storage::TileGroup *tile_group =
table->GetTileGroup(rand_tilegroup_offset).get();
oid_t tuple_per_group = tile_group->GetActiveTupleCount();
LOG_TRACE("tile_group: offset: %lu, addr: %p, tuple_per_group: %u",
rand_tilegroup_offset, tile_group, tuple_per_group);
if (tuple_per_group == 0) {
continue;
}
rand_tuple_offset = rand() % tuple_per_group;
std::unique_ptr<storage::Tuple> tuple(
new storage::Tuple(tuple_schema, true));
LOG_TRACE("tuple_group_offset = %lu, tuple_offset = %lu",
rand_tilegroup_offset, rand_tuple_offset);
if (!GetTupleInTileGroup(tile_group, rand_tuple_offset, tuple)) {
continue;
}
LOG_TRACE("Add sampled tuple: %s", tuple->GetInfo().c_str());
sampled_tuples.push_back(std::move(tuple));
}
return sampled_tuples.size();
}
/**
* GetTupleInTileGroup - This function is a helper function to get a tuple in
* a tile group.
*/
bool TupleSampler::GetTupleInTileGroup(storage::TileGroup *tile_group,
size_t tuple_offset,
std::unique_ptr<storage::Tuple> &tuple) {
// Tile Group Header
storage::TileGroupHeader *tile_group_header = tile_group->GetHeader();
// Check whether tuple is valid at given offset in the tile_group
// Reference: TileGroupHeader::GetActiveTupleCount()
// Check whether the transaction ID is invalid.
txn_id_t tuple_txn_id = tile_group_header->GetTransactionId(tuple_offset);
LOG_TRACE("transaction ID: %" PRId64, tuple_txn_id);
if (tuple_txn_id == INVALID_TXN_ID) {
return false;
}
size_t tuple_column_itr = 0;
auto tile_schemas = tile_group->GetTileSchemas();
size_t tile_count = tile_group->GetTileCount();
LOG_TRACE("tile_count: %lu", tile_count);
for (oid_t tile_itr = 0; tile_itr < tile_count; tile_itr++) {
const catalog::Schema &schema = tile_schemas[tile_itr];
oid_t tile_column_count = schema.GetColumnCount();
storage::Tile *tile = tile_group->GetTile(tile_itr);
char *tile_tuple_location = tile->GetTupleLocation(tuple_offset);
storage::Tuple tile_tuple(&schema, tile_tuple_location);
for (oid_t tile_column_itr = 0; tile_column_itr < tile_column_count;
tile_column_itr++) {
type::Value val = (tile_tuple.GetValue(tile_column_itr));
tuple->SetValue(tuple_column_itr, val, pool_.get());
tuple_column_itr++;
}
}
LOG_TRACE("offset %lu, Tuple info: %s", tuple_offset,
tuple->GetInfo().c_str());
return true;
}
/**
* GetSampledTuples - This function returns the sampled tuples.
*/
std::vector<std::unique_ptr<storage::Tuple>> &TupleSampler::GetSampledTuples() {
return sampled_tuples;
}
} // namespace optimizer
} // namespace peloton
| {
"content_hash": "564afcb79854626ace4b347b621800f9",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 80,
"avg_line_length": 35.008,
"alnum_prop": 0.6192870201096892,
"repo_name": "seojungmin/peloton",
"id": "00b106becfc8b9ac343529cc9d52800151a4ccdb",
"size": "4376",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/optimizer/stats/tuple_sampler.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "50265"
},
{
"name": "C++",
"bytes": "6346729"
},
{
"name": "CMake",
"bytes": "117317"
},
{
"name": "Java",
"bytes": "45204"
},
{
"name": "PLpgSQL",
"bytes": "5855"
},
{
"name": "Python",
"bytes": "70827"
},
{
"name": "Ruby",
"bytes": "1278"
},
{
"name": "Shell",
"bytes": "16504"
}
],
"symlink_target": ""
} |
<?php
namespace Front\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Front\Model\ValiseTable;
use Front\Form\ValiseForm;
use Front\Model\Valise;
//use Front\Model\ValiseHasArticles;
use Front\Model\Voyage;
class ValiseController extends AbstractActionController
{
protected $valiseTable;
protected $voyageTable;
public function __construct($valise,$voyage)
{
$this->valiseTable = $valise;
$this->voyageTable = $voyage;
}
public function getValiseTable()
{
if (!$this->valiseTable) {
$sm = $this->getServiceLocator();
$this->valiseTable = $sm->get('Front\Model\ValiseTable');
}
return $this->valiseTable;
}
public function getVoyageTable()
{
if (!$this->voyageTable) {
$sm = $this->getServiceLocator();
$this->voyageTable = $sm->get('Front\Model\VoyageTable');
}
return $this->voyageTable;
}
public function setValiseTable($valise)
{
$this->valiseTable = $valise;
}
public function indexAction()
{
return new ViewModel(array(
'valise' => $this->getValiseTable()->fetchAll($this->getUserId()),
));
}
public function listAction()
{
$idvoy = (int) $this->params()->fromRoute('id', 0);
$lesvalises = $this->getValiseTable()->fetchAllById($idvoy);
$lesvalises->buffer();
$results=array();
foreach ($lesvalises as $valise) {
$voyages = $this->getVoyageTable()->getVoyage($valise->voyages_id);
$results[] = array('voyages' => $voyages, 'valise' => $valise);
}
return new ViewModel(
array(
'results' => $results,
'id' => $idvoy,
)
);
return new ViewModel();
}
public function addAction()
{
$form = new ValiseForm();
$form->get('submit')->setValue('Ajouter');
$idvoy = (int) $this->params()->fromRoute('id', 0);
$request = $this->getRequest();
if ($request->isPost()) {
$valise = new Valise();
//$form->setInputFilter($voyage->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$valise->exchangeArray($form->getData());
$this->getValiseTable()->saveValise($valise);
return $this->redirect()->toRoute('valise',array('action'=>'list', 'id' => $valise->voyages_id));
}
}
return array('form' => $form,
'id'=>$idvoy);
}
public function editAction()
{
}
public function deleteAction()
{
}
public function getUserId()
{
if ($this->zfcUserAuthentication()->hasIdentity()) {
//get the user_id of the user
$userid=$this->zfcUserAuthentication()->getIdentity()->getId();
}
return $userid;
}
} | {
"content_hash": "c04cd791337ba2f362f44f881a0136c9",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 113,
"avg_line_length": 25.076923076923077,
"alnum_prop": 0.5647580095432856,
"repo_name": "cooltravelling/cool",
"id": "5e7b2a30518c975db4d974460ef78237c6d46bd9",
"size": "2934",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "module/Front/src/Front/Controller/ValiseController.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "222912"
},
{
"name": "PHP",
"bytes": "109067"
}
],
"symlink_target": ""
} |
'use strict';
function ordinal(n) {
if (n < 10 || n > 20) //the number between 10 and 20 are all Nth (in case someone makes a crazy function)
{
var m = n%10;
if (m == 1) {
return n+"st";
} else if (m == 2) {
return n+"nd";
} else if (m == 3) {
return n+"rd";
}
}
return n+"th";
}
function BadTypeException(type, possible, n, where) {
this.message = "Tried to use the type '" + type + "'";
if (n !== undefined) {
this.message += " at the " + ordinal(n+1) + " argument";
}
if (where != undefined) {
this.message += " on '" + where + "'";
}
this.message += ". Expecting the type";
if (possible.length > 1) this.message += "s";
for (let i in possible) {
if (i > 1) {
this.message += " '" + possible[i] + "',";
} else if (i == 1) {
this.message += " '" + possible[i] + "' or";
} else {//i == 0
this.message += " '" + possible[i] + "'.";
}
}
this.type = 'BadTypeException';
this.where = where;
this.toString = function() { return this.type + ": " + this.message; };
}
function TooFewArgsException(current, expected, where) {
this.message = "Expected a minimum of " + expected + " arguments at " + where + ". Recived " + current;
this.type = "TooFewArgsException";
this.where = where;
this.toString = function() { return this.type + ": " + this.message; };
}
function testType(variable, possible, where, n) {
if (n < 0) n = undefined;
var found = false;
var type = variable.constructor.name;
var i;
for (i = 0; !found && i < possible.length; ++i) {
if (possible[i] !== undefined && (possible[i]).constructor !== String) {
possible[i] = (possible[i]).constructor.name;
}
if (type === possible[i]) {
found = true;
}
}
if (!found) {
throw new BadTypeException(type, possible, n, where);
}
}
function checkArgs(args, possibleTypes, where, minArgs) {
let u = 0;
for (let n of args) {
if (n === undefined) ++u;
}
var l = Math.min(args.length-u, possibleTypes.length);
if (minArgs && l < minArgs) {
throw new TooFewArgsException(l, minArgs, where);
}
for (let i = 0; i < l; ++i) {
if ((possibleTypes[i]).constructor !== Array) {
possibleTypes[i] = [possibleTypes[i]];
}
testType(args[i], possibleTypes[i], where, i);
}
}
module.exports = checkArgs; | {
"content_hash": "1c4bfdd3908801afa5935f3cf7a0fe81",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 106,
"avg_line_length": 24.236559139784948,
"alnum_prop": 0.5887311446317658,
"repo_name": "copying/DubBot",
"id": "226339bf1108c07f0f47a508c84726368968c120",
"size": "2254",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/utils/typecheck.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "47887"
}
],
"symlink_target": ""
} |
#include "public/web/WebAXObject.h"
#include "core/HTMLNames.h"
#include "core/css/CSSPrimitiveValueMappings.h"
#include "core/dom/Document.h"
#include "core/dom/Node.h"
#include "core/frame/FrameHost.h"
#include "core/frame/FrameView.h"
#include "core/frame/VisualViewport.h"
#include "core/input/EventHandler.h"
#include "core/layout/LayoutView.h"
#include "core/style/ComputedStyle.h"
#include "core/page/Page.h"
#include "modules/accessibility/AXObject.h"
#include "modules/accessibility/AXObjectCacheImpl.h"
#include "modules/accessibility/AXTable.h"
#include "modules/accessibility/AXTableCell.h"
#include "modules/accessibility/AXTableColumn.h"
#include "modules/accessibility/AXTableRow.h"
#include "platform/PlatformKeyboardEvent.h"
#include "public/platform/WebPoint.h"
#include "public/platform/WebRect.h"
#include "public/platform/WebString.h"
#include "public/platform/WebURL.h"
#include "public/web/WebDocument.h"
#include "public/web/WebElement.h"
#include "public/web/WebNode.h"
#include "web/WebLocalFrameImpl.h"
#include "web/WebViewImpl.h"
#include "wtf/text/StringBuilder.h"
namespace blink {
#if ENABLE(ASSERT)
// It's not safe to call some WebAXObject APIs if a layout is pending.
// Clients should call updateLayoutAndCheckValidity first.
static bool isLayoutClean(Document* document)
{
if (!document || !document->view())
return false;
return document->lifecycle().state() >= DocumentLifecycle::LayoutClean
|| ((document->lifecycle().state() == DocumentLifecycle::StyleClean || document->lifecycle().state() == DocumentLifecycle::LayoutSubtreeChangeClean)
&& !document->view()->needsLayout());
}
#endif
WebScopedAXContext::WebScopedAXContext(WebDocument& rootDocument)
: m_private(ScopedAXObjectCache::create(*rootDocument.unwrap<Document>()))
{
}
WebScopedAXContext::~WebScopedAXContext()
{
m_private.reset(0);
}
WebAXObject WebScopedAXContext::root() const
{
return WebAXObject(static_cast<AXObjectCacheImpl*>(m_private->get())->root());
}
void WebAXObject::reset()
{
m_private.reset();
}
void WebAXObject::assign(const WebAXObject& other)
{
m_private = other.m_private;
}
bool WebAXObject::equals(const WebAXObject& n) const
{
return m_private.get() == n.m_private.get();
}
bool WebAXObject::isDetached() const
{
if (m_private.isNull())
return true;
return m_private->isDetached();
}
int WebAXObject::axID() const
{
if (isDetached())
return -1;
return m_private->axObjectID();
}
bool WebAXObject::updateLayoutAndCheckValidity()
{
if (!isDetached()) {
Document* document = m_private->document();
if (!document || !document->topDocument().view())
return false;
document->view()->updateAllLifecyclePhases();
}
// Doing a layout can cause this object to be invalid, so check again.
return !isDetached();
}
WebString WebAXObject::actionVerb() const
{
if (isDetached())
return WebString();
return m_private->actionVerb();
}
bool WebAXObject::canDecrement() const
{
if (isDetached())
return false;
return m_private->isSlider();
}
bool WebAXObject::canIncrement() const
{
if (isDetached())
return false;
return m_private->isSlider();
}
bool WebAXObject::canPress() const
{
if (isDetached())
return false;
return m_private->actionElement() || m_private->isButton() || m_private->isMenuRelated();
}
bool WebAXObject::canSetFocusAttribute() const
{
if (isDetached())
return false;
return m_private->canSetFocusAttribute();
}
bool WebAXObject::canSetValueAttribute() const
{
if (isDetached())
return false;
return m_private->canSetValueAttribute();
}
unsigned WebAXObject::childCount() const
{
if (isDetached())
return 0;
return m_private->children().size();
}
WebAXObject WebAXObject::childAt(unsigned index) const
{
if (isDetached())
return WebAXObject();
if (m_private->children().size() <= index)
return WebAXObject();
return WebAXObject(m_private->children()[index]);
}
WebAXObject WebAXObject::parentObject() const
{
if (isDetached())
return WebAXObject();
return WebAXObject(m_private->parentObject());
}
bool WebAXObject::canSetSelectedAttribute() const
{
if (isDetached())
return false;
return m_private->canSetSelectedAttribute();
}
bool WebAXObject::isAnchor() const
{
if (isDetached())
return false;
return m_private->isAnchor();
}
bool WebAXObject::isAriaReadOnly() const
{
if (isDetached())
return false;
return equalIgnoringCase(m_private->getAttribute(HTMLNames::aria_readonlyAttr), "true");
}
WebString WebAXObject::ariaAutoComplete() const
{
if (isDetached())
return WebString();
return m_private->ariaAutoComplete();
}
bool WebAXObject::isButtonStateMixed() const
{
if (isDetached())
return false;
return m_private->checkboxOrRadioValue() == ButtonStateMixed;
}
bool WebAXObject::isChecked() const
{
if (isDetached())
return false;
return m_private->isChecked();
}
bool WebAXObject::isClickable() const
{
if (isDetached())
return false;
return m_private->isClickable();
}
bool WebAXObject::isCollapsed() const
{
if (isDetached())
return false;
return m_private->isCollapsed();
}
bool WebAXObject::isControl() const
{
if (isDetached())
return false;
return m_private->isControl();
}
bool WebAXObject::isEnabled() const
{
if (isDetached())
return false;
return m_private->isEnabled();
}
WebAXExpanded WebAXObject::isExpanded() const
{
if (isDetached())
return WebAXExpandedUndefined;
return static_cast<WebAXExpanded>(m_private->isExpanded());
}
bool WebAXObject::isFocused() const
{
if (isDetached())
return false;
return m_private->isFocused();
}
bool WebAXObject::isHovered() const
{
if (isDetached())
return false;
return m_private->isHovered();
}
bool WebAXObject::isLinked() const
{
if (isDetached())
return false;
return m_private->isLinked();
}
bool WebAXObject::isLoaded() const
{
if (isDetached())
return false;
return m_private->isLoaded();
}
bool WebAXObject::isMultiSelectable() const
{
if (isDetached())
return false;
return m_private->isMultiSelectable();
}
bool WebAXObject::isOffScreen() const
{
if (isDetached())
return false;
return m_private->isOffScreen();
}
bool WebAXObject::isPasswordField() const
{
if (isDetached())
return false;
return m_private->isPasswordField();
}
bool WebAXObject::isPressed() const
{
if (isDetached())
return false;
return m_private->isPressed();
}
bool WebAXObject::isReadOnly() const
{
if (isDetached())
return false;
return m_private->isReadOnly();
}
bool WebAXObject::isRequired() const
{
if (isDetached())
return false;
return m_private->isRequired();
}
bool WebAXObject::isSelected() const
{
if (isDetached())
return false;
return m_private->isSelected();
}
bool WebAXObject::isSelectedOptionActive() const
{
if (isDetached())
return false;
return m_private->isSelectedOptionActive();
}
bool WebAXObject::isVisible() const
{
if (isDetached())
return false;
return m_private->isVisible();
}
bool WebAXObject::isVisited() const
{
if (isDetached())
return false;
return m_private->isVisited();
}
WebString WebAXObject::accessKey() const
{
if (isDetached())
return WebString();
return WebString(m_private->accessKey());
}
unsigned WebAXObject::backgroundColor() const
{
if (isDetached())
return 0;
// RGBA32 is an alias for unsigned int.
return m_private->backgroundColor();
}
unsigned WebAXObject::color() const
{
if (isDetached())
return 0;
// RGBA32 is an alias for unsigned int.
return m_private->color();
}
// Deprecated.
void WebAXObject::colorValue(int& r, int& g, int& b) const
{
if (isDetached())
return;
unsigned color = m_private->colorValue();
r = (color >> 16) & 0xFF;
g = (color >> 8) & 0xFF;
b = color & 0xFF;
}
unsigned WebAXObject::colorValue() const
{
if (isDetached())
return 0;
// RGBA32 is an alias for unsigned int.
return m_private->colorValue();
}
WebAXObject WebAXObject::ariaActiveDescendant() const
{
if (isDetached())
return WebAXObject();
return WebAXObject(m_private->activeDescendant());
}
bool WebAXObject::ariaControls(WebVector<WebAXObject>& controlsElements) const
{
if (isDetached())
return false;
AXObject::AXObjectVector controls;
m_private->ariaControlsElements(controls);
WebVector<WebAXObject> result(controls.size());
for (size_t i = 0; i < controls.size(); i++)
result[i] = WebAXObject(controls[i]);
controlsElements.swap(result);
return true;
}
bool WebAXObject::ariaHasPopup() const
{
if (isDetached())
return false;
return m_private->ariaHasPopup();
}
bool WebAXObject::ariaFlowTo(WebVector<WebAXObject>& flowToElements) const
{
if (isDetached())
return false;
AXObject::AXObjectVector flowTo;
m_private->ariaFlowToElements(flowTo);
WebVector<WebAXObject> result(flowTo.size());
for (size_t i = 0; i < flowTo.size(); i++)
result[i] = WebAXObject(flowTo[i]);
flowToElements.swap(result);
return true;
}
bool WebAXObject::isEditable() const
{
if (isDetached())
return false;
return m_private->isEditable();
}
bool WebAXObject::isMultiline() const
{
if (isDetached())
return false;
return m_private->isMultiline();
}
bool WebAXObject::isRichlyEditable() const
{
if (isDetached())
return false;
return m_private->isRichlyEditable();
}
int WebAXObject::posInSet() const
{
if (isDetached())
return 0;
return m_private->posInSet();
}
int WebAXObject::setSize() const
{
if (isDetached())
return 0;
return m_private->setSize();
}
bool WebAXObject::isInLiveRegion() const
{
if (isDetached())
return false;
return 0 != m_private->liveRegionRoot();
}
bool WebAXObject::liveRegionAtomic() const
{
if (isDetached())
return false;
return m_private->liveRegionAtomic();
}
bool WebAXObject::liveRegionBusy() const
{
if (isDetached())
return false;
return m_private->liveRegionBusy();
}
WebString WebAXObject::liveRegionRelevant() const
{
if (isDetached())
return WebString();
return m_private->liveRegionRelevant();
}
WebString WebAXObject::liveRegionStatus() const
{
if (isDetached())
return WebString();
return m_private->liveRegionStatus();
}
bool WebAXObject::containerLiveRegionAtomic() const
{
if (isDetached())
return false;
return m_private->containerLiveRegionAtomic();
}
bool WebAXObject::containerLiveRegionBusy() const
{
if (isDetached())
return false;
return m_private->containerLiveRegionBusy();
}
WebString WebAXObject::containerLiveRegionRelevant() const
{
if (isDetached())
return WebString();
return m_private->containerLiveRegionRelevant();
}
WebString WebAXObject::containerLiveRegionStatus() const
{
if (isDetached())
return WebString();
return m_private->containerLiveRegionStatus();
}
bool WebAXObject::ariaOwns(WebVector<WebAXObject>& ownsElements) const
{
// aria-owns rearranges the accessibility tree rather than just
// exposing an attribute.
// FIXME(dmazzoni): remove this function after we stop calling it
// from Chromium. http://crbug.com/489590
return false;
}
WebRect WebAXObject::boundingBoxRect() const
{
if (isDetached())
return WebRect();
ASSERT(isLayoutClean(m_private->document()));
return pixelSnappedIntRect(m_private->elementRect());
}
float WebAXObject::fontSize() const
{
if (isDetached())
return 0.0f;
return m_private->fontSize();
}
bool WebAXObject::canvasHasFallbackContent() const
{
if (isDetached())
return false;
return m_private->canvasHasFallbackContent();
}
WebPoint WebAXObject::clickPoint() const
{
if (isDetached())
return WebPoint();
return WebPoint(m_private->clickPoint());
}
WebAXInvalidState WebAXObject::invalidState() const
{
if (isDetached())
return WebAXInvalidStateUndefined;
return static_cast<WebAXInvalidState>(m_private->invalidState());
}
// Only used when invalidState() returns WebAXInvalidStateOther.
WebString WebAXObject::ariaInvalidValue() const
{
if (isDetached())
return WebString();
return m_private->ariaInvalidValue();
}
double WebAXObject::estimatedLoadingProgress() const
{
if (isDetached())
return 0.0;
return m_private->estimatedLoadingProgress();
}
int WebAXObject::headingLevel() const
{
if (isDetached())
return 0;
return m_private->headingLevel();
}
int WebAXObject::hierarchicalLevel() const
{
if (isDetached())
return 0;
return m_private->hierarchicalLevel();
}
// FIXME: This method passes in a point that has page scale applied but assumes that (0, 0)
// is the top left of the visual viewport. In other words, the point has the VisualViewport
// scale applied, but not the VisualViewport offset. crbug.com/459591.
WebAXObject WebAXObject::hitTest(const WebPoint& point) const
{
if (isDetached())
return WebAXObject();
IntPoint contentsPoint = m_private->documentFrameView()->soonToBeRemovedUnscaledViewportToContents(point);
AXObject* hit = m_private->accessibilityHitTest(contentsPoint);
if (hit)
return WebAXObject(hit);
if (m_private->elementRect().contains(contentsPoint))
return *this;
return WebAXObject();
}
WebString WebAXObject::keyboardShortcut() const
{
if (isDetached())
return WebString();
String accessKey = m_private->accessKey();
if (accessKey.isNull())
return WebString();
DEFINE_STATIC_LOCAL(String, modifierString, ());
if (modifierString.isNull()) {
unsigned modifiers = EventHandler::accessKeyModifiers();
// Follow the same order as Mozilla MSAA implementation:
// Ctrl+Alt+Shift+Meta+key. MSDN states that keyboard shortcut strings
// should not be localized and defines the separator as "+".
StringBuilder modifierStringBuilder;
if (modifiers & PlatformEvent::CtrlKey)
modifierStringBuilder.appendLiteral("Ctrl+");
if (modifiers & PlatformEvent::AltKey)
modifierStringBuilder.appendLiteral("Alt+");
if (modifiers & PlatformEvent::ShiftKey)
modifierStringBuilder.appendLiteral("Shift+");
if (modifiers & PlatformEvent::MetaKey)
modifierStringBuilder.appendLiteral("Win+");
modifierString = modifierStringBuilder.toString();
}
return String(modifierString + accessKey);
}
WebString WebAXObject::language() const
{
if (isDetached())
return WebString();
return m_private->language();
}
bool WebAXObject::performDefaultAction() const
{
if (isDetached())
return false;
return m_private->performDefaultAction();
}
bool WebAXObject::increment() const
{
if (isDetached())
return false;
if (canIncrement()) {
m_private->increment();
return true;
}
return false;
}
bool WebAXObject::decrement() const
{
if (isDetached())
return false;
if (canDecrement()) {
m_private->decrement();
return true;
}
return false;
}
WebAXOrientation WebAXObject::orientation() const
{
if (isDetached())
return WebAXOrientationUndefined;
return static_cast<WebAXOrientation>(m_private->orientation());
}
bool WebAXObject::press() const
{
if (isDetached())
return false;
return m_private->press();
}
WebAXRole WebAXObject::role() const
{
if (isDetached())
return WebAXRoleUnknown;
return static_cast<WebAXRole>(m_private->roleValue());
}
void WebAXObject::selection(WebAXObject& anchorObject, int& anchorOffset,
WebAXObject& focusObject, int& focusOffset) const
{
if (isDetached()) {
anchorObject = WebAXObject();
anchorOffset = -1;
focusObject = WebAXObject();
focusOffset = -1;
return;
}
AXObject::AXRange axSelection = m_private->selection();
anchorObject = WebAXObject(axSelection.anchorObject);
anchorOffset = axSelection.anchorOffset;
focusObject = WebAXObject(axSelection.focusObject);
focusOffset = axSelection.focusOffset;
return;
}
void WebAXObject::setSelection(const WebAXObject& anchorObject, int anchorOffset,
const WebAXObject& focusObject, int focusOffset) const
{
if (isDetached())
return;
AXObject::AXRange axSelection(anchorObject, anchorOffset,
focusObject, focusOffset);
m_private->setSelection(axSelection);
return;
}
unsigned WebAXObject::selectionEnd() const
{
if (isDetached())
return 0;
AXObject::AXRange axSelection = m_private->selectionUnderObject();
if (axSelection.focusOffset < 0)
return 0;
return axSelection.focusOffset;
}
unsigned WebAXObject::selectionStart() const
{
if (isDetached())
return 0;
AXObject::AXRange axSelection = m_private->selectionUnderObject();
if (axSelection.anchorOffset < 0)
return 0;
return axSelection.anchorOffset;
}
unsigned WebAXObject::selectionEndLineNumber() const
{
if (isDetached())
return 0;
VisiblePosition position = m_private->visiblePositionForIndex(selectionEnd());
int lineNumber = m_private->lineForPosition(position);
if (lineNumber < 0)
return 0;
return lineNumber;
}
unsigned WebAXObject::selectionStartLineNumber() const
{
if (isDetached())
return 0;
VisiblePosition position = m_private->visiblePositionForIndex(selectionStart());
int lineNumber = m_private->lineForPosition(position);
if (lineNumber < 0)
return 0;
return lineNumber;
}
void WebAXObject::setFocused(bool on) const
{
if (!isDetached())
m_private->setFocused(on);
}
void WebAXObject::setSelectedTextRange(int selectionStart, int selectionEnd) const
{
if (isDetached())
return;
m_private->setSelection(AXObject::AXRange(selectionStart, selectionEnd));
}
void WebAXObject::setValue(WebString value) const
{
if (isDetached())
return;
m_private->setValue(value);
}
void WebAXObject::showContextMenu() const
{
if (isDetached())
return;
Node* node = m_private->node();
if (!node)
return;
Element* element = nullptr;
if (node->isElementNode()) {
element = toElement(node);
} else {
node->updateDistribution();
ContainerNode* parent = FlatTreeTraversal::parent(*node);
ASSERT_WITH_SECURITY_IMPLICATION(parent->isElementNode());
element = toElement(parent);
}
if (!element)
return;
LocalFrame* frame = element->document().frame();
if (!frame)
return;
WebViewImpl* view = WebLocalFrameImpl::fromFrame(frame)->viewImpl();
if (!view)
return;
view->showContextMenuForElement(WebElement(element));
}
WebString WebAXObject::stringValue() const
{
if (isDetached())
return WebString();
return m_private->stringValue();
}
WebAXTextDirection WebAXObject::textDirection() const
{
if (isDetached())
return WebAXTextDirectionLR;
return static_cast<WebAXTextDirection>(m_private->textDirection());
}
WebAXTextStyle WebAXObject::textStyle() const
{
if (isDetached())
return WebAXTextStyleNone;
return static_cast<WebAXTextStyle>(m_private->textStyle());
}
WebURL WebAXObject::url() const
{
if (isDetached())
return WebURL();
return m_private->url();
}
WebString WebAXObject::name(WebAXNameFrom& outNameFrom, WebVector<WebAXObject>& outNameObjects) const
{
if (isDetached())
return WebString();
AXNameFrom nameFrom = AXNameFromUninitialized;
HeapVector<Member<AXObject>> nameObjects;
WebString result = m_private->name(nameFrom, &nameObjects);
outNameFrom = static_cast<WebAXNameFrom>(nameFrom);
WebVector<WebAXObject> webNameObjects(nameObjects.size());
for (size_t i = 0; i < nameObjects.size(); i++)
webNameObjects[i] = WebAXObject(nameObjects[i]);
outNameObjects.swap(webNameObjects);
return result;
}
WebString WebAXObject::name() const
{
if (isDetached())
return WebString();
AXNameFrom nameFrom;
HeapVector<Member<AXObject>> nameObjects;
return m_private->name(nameFrom, &nameObjects);
}
WebString WebAXObject::description(WebAXNameFrom nameFrom, WebAXDescriptionFrom& outDescriptionFrom, WebVector<WebAXObject>& outDescriptionObjects) const
{
if (isDetached())
return WebString();
AXDescriptionFrom descriptionFrom = AXDescriptionFromUninitialized;
HeapVector<Member<AXObject>> descriptionObjects;
String result = m_private->description(static_cast<AXNameFrom>(nameFrom), descriptionFrom, &descriptionObjects);
outDescriptionFrom = static_cast<WebAXDescriptionFrom>(descriptionFrom);
WebVector<WebAXObject> webDescriptionObjects(descriptionObjects.size());
for (size_t i = 0; i < descriptionObjects.size(); i++)
webDescriptionObjects[i] = WebAXObject(descriptionObjects[i]);
outDescriptionObjects.swap(webDescriptionObjects);
return result;
}
WebString WebAXObject::placeholder(WebAXNameFrom nameFrom, WebAXDescriptionFrom descriptionFrom) const
{
if (isDetached())
return WebString();
return m_private->placeholder(static_cast<AXNameFrom>(nameFrom), static_cast<AXDescriptionFrom>(descriptionFrom));
}
bool WebAXObject::supportsRangeValue() const
{
if (isDetached())
return false;
return m_private->supportsRangeValue();
}
WebString WebAXObject::valueDescription() const
{
if (isDetached())
return WebString();
return m_private->valueDescription();
}
float WebAXObject::valueForRange() const
{
if (isDetached())
return 0.0;
return m_private->valueForRange();
}
float WebAXObject::maxValueForRange() const
{
if (isDetached())
return 0.0;
return m_private->maxValueForRange();
}
float WebAXObject::minValueForRange() const
{
if (isDetached())
return 0.0;
return m_private->minValueForRange();
}
WebNode WebAXObject::node() const
{
if (isDetached())
return WebNode();
Node* node = m_private->node();
if (!node)
return WebNode();
return WebNode(node);
}
WebDocument WebAXObject::document() const
{
if (isDetached())
return WebDocument();
Document* document = m_private->document();
if (!document)
return WebDocument();
return WebDocument(document);
}
bool WebAXObject::hasComputedStyle() const
{
if (isDetached())
return false;
Document* document = m_private->document();
if (document)
document->updateLayoutTree();
Node* node = m_private->node();
if (!node)
return false;
return node->ensureComputedStyle();
}
WebString WebAXObject::computedStyleDisplay() const
{
if (isDetached())
return WebString();
Document* document = m_private->document();
if (document)
document->updateLayoutTree();
Node* node = m_private->node();
if (!node)
return WebString();
const ComputedStyle* computedStyle = node->ensureComputedStyle();
if (!computedStyle)
return WebString();
return WebString(CSSPrimitiveValue::create(computedStyle->display())->cssText());
}
bool WebAXObject::accessibilityIsIgnored() const
{
if (isDetached())
return false;
return m_private->accessibilityIsIgnored();
}
bool WebAXObject::lineBreaks(WebVector<int>& result) const
{
if (isDetached())
return false;
Vector<int> lineBreaksVector;
m_private->lineBreaks(lineBreaksVector);
size_t vectorSize = lineBreaksVector.size();
WebVector<int> lineBreaksWebVector(vectorSize);
for (size_t i = 0; i< vectorSize; i++)
lineBreaksWebVector[i] = lineBreaksVector[i];
result.swap(lineBreaksWebVector);
return true;
}
unsigned WebAXObject::columnCount() const
{
if (isDetached())
return false;
if (!m_private->isAXTable())
return 0;
return toAXTable(m_private.get())->columnCount();
}
unsigned WebAXObject::rowCount() const
{
if (isDetached())
return false;
if (!m_private->isAXTable())
return 0;
return toAXTable(m_private.get())->rowCount();
}
WebAXObject WebAXObject::cellForColumnAndRow(unsigned column, unsigned row) const
{
if (isDetached())
return WebAXObject();
if (!m_private->isAXTable())
return WebAXObject();
AXTableCell* cell = toAXTable(m_private.get())->cellForColumnAndRow(column, row);
return WebAXObject(static_cast<AXObject*>(cell));
}
WebAXObject WebAXObject::headerContainerObject() const
{
if (isDetached())
return WebAXObject();
if (!m_private->isAXTable())
return WebAXObject();
return WebAXObject(toAXTable(m_private.get())->headerContainer());
}
WebAXObject WebAXObject::rowAtIndex(unsigned rowIndex) const
{
if (isDetached())
return WebAXObject();
if (!m_private->isAXTable())
return WebAXObject();
const AXObject::AXObjectVector& rows = toAXTable(m_private.get())->rows();
if (rowIndex < rows.size())
return WebAXObject(rows[rowIndex]);
return WebAXObject();
}
WebAXObject WebAXObject::columnAtIndex(unsigned columnIndex) const
{
if (isDetached())
return WebAXObject();
if (!m_private->isAXTable())
return WebAXObject();
const AXObject::AXObjectVector& columns = toAXTable(m_private.get())->columns();
if (columnIndex < columns.size())
return WebAXObject(columns[columnIndex]);
return WebAXObject();
}
unsigned WebAXObject::rowIndex() const
{
if (isDetached())
return 0;
if (!m_private->isTableRow())
return 0;
return toAXTableRow(m_private.get())->rowIndex();
}
WebAXObject WebAXObject::rowHeader() const
{
if (isDetached())
return WebAXObject();
if (!m_private->isTableRow())
return WebAXObject();
return WebAXObject(toAXTableRow(m_private.get())->headerObject());
}
void WebAXObject::rowHeaders(WebVector<WebAXObject>& rowHeaderElements) const
{
if (isDetached())
return;
if (!m_private->isAXTable())
return;
AXObject::AXObjectVector headers;
toAXTable(m_private.get())->rowHeaders(headers);
size_t headerCount = headers.size();
WebVector<WebAXObject> result(headerCount);
for (size_t i = 0; i < headerCount; i++)
result[i] = WebAXObject(headers[i]);
rowHeaderElements.swap(result);
}
unsigned WebAXObject::columnIndex() const
{
if (isDetached())
return 0;
if (m_private->roleValue() != ColumnRole)
return 0;
return toAXTableColumn(m_private.get())->columnIndex();
}
WebAXObject WebAXObject::columnHeader() const
{
if (isDetached())
return WebAXObject();
if (m_private->roleValue() != ColumnRole)
return WebAXObject();
return WebAXObject(toAXTableColumn(m_private.get())->headerObject());
}
void WebAXObject::columnHeaders(WebVector<WebAXObject>& columnHeaderElements) const
{
if (isDetached())
return;
if (!m_private->isAXTable())
return;
AXObject::AXObjectVector headers;
toAXTable(m_private.get())->columnHeaders(headers);
size_t headerCount = headers.size();
WebVector<WebAXObject> result(headerCount);
for (size_t i = 0; i < headerCount; i++)
result[i] = WebAXObject(headers[i]);
columnHeaderElements.swap(result);
}
unsigned WebAXObject::cellColumnIndex() const
{
if (isDetached())
return 0;
if (!m_private->isTableCell())
return 0;
std::pair<unsigned, unsigned> columnRange;
toAXTableCell(m_private.get())->columnIndexRange(columnRange);
return columnRange.first;
}
unsigned WebAXObject::cellColumnSpan() const
{
if (isDetached())
return 0;
if (!m_private->isTableCell())
return 0;
std::pair<unsigned, unsigned> columnRange;
toAXTableCell(m_private.get())->columnIndexRange(columnRange);
return columnRange.second;
}
unsigned WebAXObject::cellRowIndex() const
{
if (isDetached())
return 0;
if (!m_private->isTableCell())
return 0;
std::pair<unsigned, unsigned> rowRange;
toAXTableCell(m_private.get())->rowIndexRange(rowRange);
return rowRange.first;
}
unsigned WebAXObject::cellRowSpan() const
{
if (isDetached())
return 0;
if (!m_private->isTableCell())
return 0;
std::pair<unsigned, unsigned> rowRange;
toAXTableCell(m_private.get())->rowIndexRange(rowRange);
return rowRange.second;
}
WebAXSortDirection WebAXObject::sortDirection() const
{
if (isDetached())
return WebAXSortDirectionUndefined;
return static_cast<WebAXSortDirection>(m_private->sortDirection());
}
void WebAXObject::loadInlineTextBoxes() const
{
if (isDetached())
return;
m_private->loadInlineTextBoxes();
}
WebAXObject WebAXObject::nextOnLine() const
{
if (isDetached())
return WebAXObject();
return WebAXObject(m_private.get()->nextOnLine());
}
WebAXObject WebAXObject::previousOnLine() const
{
if (isDetached())
return WebAXObject();
return WebAXObject(m_private.get()->previousOnLine());
}
void WebAXObject::characterOffsets(WebVector<int>& offsets) const
{
if (isDetached())
return;
Vector<int> offsetsVector;
m_private->textCharacterOffsets(offsetsVector);
size_t vectorSize = offsetsVector.size();
WebVector<int> offsetsWebVector(vectorSize);
for (size_t i = 0; i < vectorSize; i++)
offsetsWebVector[i] = offsetsVector[i];
offsets.swap(offsetsWebVector);
}
void WebAXObject::wordBoundaries(WebVector<int>& starts, WebVector<int>& ends) const
{
if (isDetached())
return;
Vector<AXObject::AXRange> wordBoundaries;
m_private->wordBoundaries(wordBoundaries);
WebVector<int> wordStartOffsets(wordBoundaries.size());
WebVector<int> wordEndOffsets(wordBoundaries.size());
for (size_t i = 0; i < wordBoundaries.size(); ++i) {
ASSERT(wordBoundaries[i].isSimple());
wordStartOffsets[i] = wordBoundaries[i].anchorOffset;
wordEndOffsets[i] = wordBoundaries[i].focusOffset;
}
starts.swap(wordStartOffsets);
ends.swap(wordEndOffsets);
}
bool WebAXObject::isScrollableContainer() const
{
if (isDetached())
return false;
return m_private->isScrollableContainer();
}
WebPoint WebAXObject::scrollOffset() const
{
if (isDetached())
return WebPoint();
return m_private->scrollOffset();
}
WebPoint WebAXObject::minimumScrollOffset() const
{
if (isDetached())
return WebPoint();
return m_private->minimumScrollOffset();
}
WebPoint WebAXObject::maximumScrollOffset() const
{
if (isDetached())
return WebPoint();
return m_private->maximumScrollOffset();
}
void WebAXObject::setScrollOffset(const WebPoint& offset) const
{
if (isDetached())
return;
m_private->setScrollOffset(offset);
}
void WebAXObject::scrollToMakeVisible() const
{
if (!isDetached())
m_private->scrollToMakeVisible();
}
void WebAXObject::scrollToMakeVisibleWithSubFocus(const WebRect& subfocus) const
{
if (!isDetached())
m_private->scrollToMakeVisibleWithSubFocus(subfocus);
}
void WebAXObject::scrollToGlobalPoint(const WebPoint& point) const
{
if (!isDetached())
m_private->scrollToGlobalPoint(point);
}
WebAXObject::WebAXObject(AXObject* object)
: m_private(object)
{
}
WebAXObject& WebAXObject::operator=(AXObject* object)
{
m_private = object;
return *this;
}
WebAXObject::operator AXObject*() const
{
return m_private.get();
}
} // namespace blink
| {
"content_hash": "a278ffcaa26badd88c760e3ec2f3f430",
"timestamp": "",
"source": "github",
"line_count": 1489,
"max_line_length": 156,
"avg_line_length": 21.73606447280054,
"alnum_prop": 0.6716205777846439,
"repo_name": "ds-hwang/chromium-crosswalk",
"id": "19c5b6630fb645500123d034dbefa99fd08fc4f7",
"size": "33927",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "third_party/WebKit/Source/web/WebAXObject.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package msgraph
// AirPrintDestination undocumented
type AirPrintDestination struct {
// Object is the base model of AirPrintDestination
Object
// IPAddress The IP Address of the AirPrint destination.
IPAddress *string `json:"ipAddress,omitempty"`
// ResourcePath undocumented
ResourcePath *string `json:"resourcePath,omitempty"`
// Port The listening port of the AirPrint destination. If this key is not specified AirPrint will use the default port. Available in iOS 11.0 and later.
Port *int `json:"port,omitempty"`
// ForceTLS If true AirPrint connections are secured by Transport Layer Security (TLS). Default is false. Available in iOS 11.0 and later.
ForceTLS *bool `json:"forceTls,omitempty"`
}
| {
"content_hash": "e89400471aaa27a9acd85e061bbc0e7d",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 154,
"avg_line_length": 47.53333333333333,
"alnum_prop": 0.7812061711079944,
"repo_name": "42wim/matterbridge",
"id": "78b9020dab26dd885b7cbab6920808ab0b2782db",
"size": "763",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/github.com/yaegashi/msgraph.go/beta/ModelAir.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2029"
},
{
"name": "Go",
"bytes": "456275"
},
{
"name": "Shell",
"bytes": "513"
}
],
"symlink_target": ""
} |
@extends('laravel-authentication-acl::admin.layouts.base-2cols')
@section('title')
Admin area: {{ trans('sample::sample_admin.page_edit') }}
@stop
@section('content')
<div class="row">
<div class="col-md-12">
<div class="col-md-8">
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title bariol-thin">
{!! !empty($sample->sample_id) ? '<i class="fa fa-pencil"></i>'.trans('sample::sample_admin.form_edit') : '<i class="fa fa-users"></i>'.trans('sample::sample_admin.form_add') !!}
</h3>
</div>
{{-- model general errors from the form --}}
@if($errors->has('sample_name') )
<div class="alert alert-danger">{!! $errors->first('sample_name') !!}</div>
@endif
@if($errors->has('name_unvalid_length') )
<div class="alert alert-danger">{!! $errors->first('name_unvalid_length') !!}</div>
@endif
{{-- successful message --}}
<?php $message = Session::get('message'); ?>
@if( isset($message) )
<div class="alert alert-success">{{$message}}</div>
@endif
<div class="panel-body">
<div class="row">
<div class="col-md-12 col-xs-12">
<h4>{!! trans('sample::sample_admin.form_heading') !!}</h4>
{!! Form::open(['route'=>['admin_sample.post', 'id' => @$sample->sample_id], 'files'=>true, 'method' => 'post']) !!}
<!-- SAMPLE NAME TEXT-->
@include('sample::sample.elements.text', ['name' => 'sample_name'])
<!-- /END SAMPLE NAME TEXT -->
{!! Form::hidden('id',@$sample->sample_id) !!}
<!-- DELETE BUTTON -->
<a href="{!! URL::route('admin_sample.delete',['id' => @$sample->id, '_token' => csrf_token()]) !!}"
class="btn btn-danger pull-right margin-left-5 delete">
Delete
</a>
<!-- DELETE BUTTON -->
<!-- SAVE BUTTON -->
{!! Form::submit('Save', array("class"=>"btn btn-info pull-right ")) !!}
<!-- /SAVE BUTTON -->
{!! Form::close() !!}
</div>
</div>
</div>
</div>
</div>
<div class='col-md-4'>
@include('sample::sample.admin.sample_search')
</div>
</div>
</div>
@stop | {
"content_hash": "300bd736c9fb5940dd9a24a9e2c6c6d9",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 202,
"avg_line_length": 41.18840579710145,
"alnum_prop": 0.4099225897255454,
"repo_name": "duonghoanghiep/cdw1_2016_2017_D",
"id": "36e06efdc22b50f071028dedbe2f51024197205a",
"size": "2842",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "laravel/packages/foostart/sample/src/views/sample/admin/sample_edit.blade.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "573"
},
{
"name": "Batchfile",
"bytes": "57"
},
{
"name": "CSS",
"bytes": "72691"
},
{
"name": "HTML",
"bytes": "86512"
},
{
"name": "JavaScript",
"bytes": "174682"
},
{
"name": "PHP",
"bytes": "753514"
},
{
"name": "Vue",
"bytes": "586"
}
],
"symlink_target": ""
} |
layout: docs
title: Navbar
description: Documentation and examples for Bootstrap's powerful, responsive navigation header, the navbar. Includes support for branding, navigation, and more, including support for our collapse plugin.
group: components
toc: true
---
## How it works
Here's what you need to know before getting started with the navbar:
- Navbars require a wrapping `.navbar` with `.navbar-expand{-sm|-md|-lg|-xl|-xxl}` for responsive collapsing and [color scheme](#color-schemes) classes.
- Navbars and their contents are fluid by default. Change the [container](#containers) to limit their horizontal width in different ways.
- Use our [spacing]({{< docsref "/utilities/spacing" >}}) and [flex]({{< docsref "/utilities/flex" >}}) utility classes for controlling spacing and alignment within navbars.
- Navbars are responsive by default, but you can easily modify them to change that. Responsive behavior depends on our Collapse JavaScript plugin.
- Ensure accessibility by using a `<nav>` element or, if using a more generic element such as a `<div>`, add a `role="navigation"` to every navbar to explicitly identify it as a landmark region for users of assistive technologies.
- Indicate the current item by using `aria-current="page"` for the current page or `aria-current="true"` for the current item in a set.
{{< callout info >}}
{{< partial "callout-info-prefersreducedmotion.md" >}}
{{< /callout >}}
## Supported content
Navbars come with built-in support for a handful of sub-components. Choose from the following as needed:
- `.navbar-brand` for your company, product, or project name.
- `.navbar-nav` for a full-height and lightweight navigation (including support for dropdowns).
- `.navbar-toggler` for use with our collapse plugin and other [navigation toggling](#responsive-behaviors) behaviors.
- Flex and spacing utilities for any form controls and actions.
- `.navbar-text` for adding vertically centered strings of text.
- `.collapse.navbar-collapse` for grouping and hiding navbar contents by a parent breakpoint.
- Add an optional `.navbar-scroll` to set a `max-height` and [scroll expanded navbar content](#scrolling).
Here's an example of all the sub-components included in a responsive light-themed navbar that automatically collapses at the `lg` (large) breakpoint.
{{< example >}}
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Dropdown
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="#">Action</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="#">Something else here</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
</li>
</ul>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
{{< /example >}}
This example uses [background]({{< docsref "/utilities/background" >}}) (`bg-light`) and [spacing]({{< docsref "/utilities/spacing" >}}) (`my-2`, `my-lg-0`, `me-sm-0`, `my-sm-0`) utility classes.
### Brand
The `.navbar-brand` can be applied to most elements, but an anchor works best, as some elements might require utility classes or custom styles.
#### Text
Add your text within an element with the `.navbar-brand` class.
{{< example >}}
<!-- As a link -->
<nav class="navbar navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
</div>
</nav>
<!-- As a heading -->
<nav class="navbar navbar-light bg-light">
<div class="container-fluid">
<span class="navbar-brand mb-0 h1">Navbar</span>
</div>
</nav>
{{< /example >}}
#### Image
You can replace the text within the `.navbar-brand` with an `<img>`.
{{< example >}}
<nav class="navbar navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="#">
<img src="/docs/{{< param docs_version >}}/assets/brand/bootstrap-logo.svg" alt="" width="30" height="24">
</a>
</div>
</nav>
{{< /example >}}
#### Image and text
You can also make use of some additional utilities to add an image and text at the same time. Note the addition of `.d-inline-block` and `.align-text-top` on the `<img>`.
{{< example >}}
<nav class="navbar navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">
<img src="/docs/{{< param docs_version >}}/assets/brand/bootstrap-logo.svg" alt="" width="30" height="24" class="d-inline-block align-text-top">
Bootstrap
</a>
</div>
</nav>
{{< /example >}}
### Nav
Navbar navigation links build on our `.nav` options with their own modifier class and require the use of [toggler classes](#toggler) for proper responsive styling. **Navigation in navbars will also grow to occupy as much horizontal space as possible** to keep your navbar contents securely aligned.
Add the `.active` class on `.nav-link` to indicate the current page.
Please note that you should also add the `aria-current` attribute on the active `.nav-link`.
{{< example >}}
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
</li>
</ul>
</div>
</div>
</nav>
{{< /example >}}
And because we use classes for our navs, you can avoid the list-based approach entirely if you like.
{{< example >}}
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-link active" aria-current="page" href="#">Home</a>
<a class="nav-link" href="#">Features</a>
<a class="nav-link" href="#">Pricing</a>
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
</div>
</div>
</div>
</nav>
{{< /example >}}
You can also use dropdowns in your navbar. Dropdown menus require a wrapping element for positioning, so be sure to use separate and nested elements for `.nav-item` and `.nav-link` as shown below.
{{< example >}}
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Dropdown link
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<li><a class="dropdown-item" href="#">Action</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
<li><a class="dropdown-item" href="#">Something else here</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
{{< /example >}}
### Forms
Place various form controls and components within a navbar:
{{< example >}}
<nav class="navbar navbar-light bg-light">
<div class="container-fluid">
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</nav>
{{< /example >}}
Immediate child elements of `.navbar` use flex layout and will default to `justify-content: space-between`. Use additional [flex utilities]({{< docsref "/utilities/flex" >}}) as needed to adjust this behavior.
{{< example >}}
<nav class="navbar navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand">Navbar</a>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</nav>
{{< /example >}}
Input groups work, too. If your navbar is an entire form, or mostly a form, you can use the `<form>` element as the container and save some HTML.
{{< example >}}
<nav class="navbar navbar-light bg-light">
<form class="container-fluid">
<div class="input-group">
<span class="input-group-text" id="basic-addon1">@</span>
<input type="text" class="form-control" placeholder="Username" aria-label="Username" aria-describedby="basic-addon1">
</div>
</form>
</nav>
{{< /example >}}
Various buttons are supported as part of these navbar forms, too. This is also a great reminder that vertical alignment utilities can be used to align different sized elements.
{{< example >}}
<nav class="navbar navbar-light bg-light">
<form class="container-fluid justify-content-start">
<button class="btn btn-outline-success me-2" type="button">Main button</button>
<button class="btn btn-sm btn-outline-secondary" type="button">Smaller button</button>
</form>
</nav>
{{< /example >}}
### Text
Navbars may contain bits of text with the help of `.navbar-text`. This class adjusts vertical alignment and horizontal spacing for strings of text.
{{< example >}}
<nav class="navbar navbar-light bg-light">
<div class="container-fluid">
<span class="navbar-text">
Navbar text with an inline element
</span>
</div>
</nav>
{{< /example >}}
Mix and match with other components and utilities as needed.
{{< example >}}
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar w/ text</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarText">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
</ul>
<span class="navbar-text">
Navbar text with an inline element
</span>
</div>
</div>
</nav>
{{< /example >}}
## Color schemes
Theming the navbar has never been easier thanks to the combination of theming classes and `background-color` utilities. Choose from `.navbar-light` for use with light background colors, or `.navbar-dark` for dark background colors. Then, customize with `.bg-*` utilities.
<div class="bd-example">
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarColor01">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
</ul>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-light" type="submit">Search</button>
</form>
</div>
</div>
</nav>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarColor02" aria-controls="navbarColor02" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarColor02">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
</ul>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-light" type="submit">Search</button>
</form>
</div>
</div>
</nav>
<nav class="navbar navbar-expand-lg navbar-light" style="background-color: #e3f2fd;">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarColor03" aria-controls="navbarColor03" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarColor03">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
</ul>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-primary" type="submit">Search</button>
</form>
</div>
</div>
</nav>
</div>
```html
<nav class="navbar navbar-dark bg-dark">
<!-- Navbar content -->
</nav>
<nav class="navbar navbar-dark bg-primary">
<!-- Navbar content -->
</nav>
<nav class="navbar navbar-light" style="background-color: #e3f2fd;">
<!-- Navbar content -->
</nav>
```
## Containers
Although it's not required, you can wrap a navbar in a `.container` to center it on a page–though note that an inner container is still required. Or you can add a container inside the `.navbar` to only center the contents of a [fixed or static top navbar](#placement).
{{< example >}}
<div class="container">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
</div>
</nav>
</div>
{{< /example >}}
Use any of the responsive containers to change how wide the content in your navbar is presented.
{{< example >}}
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-md">
<a class="navbar-brand" href="#">Navbar</a>
</div>
</nav>
{{< /example >}}
## Placement
Use our [position utilities]({{< docsref "/utilities/position" >}}) to place navbars in non-static positions. Choose from fixed to the top, fixed to the bottom, or stickied to the top (scrolls with the page until it reaches the top, then stays there). Fixed navbars use `position: fixed`, meaning they're pulled from the normal flow of the DOM and may require custom CSS (e.g., `padding-top` on the `<body>`) to prevent overlap with other elements.
Also note that **`.sticky-top` uses `position: sticky`, which [isn't fully supported in every browser](https://caniuse.com/css-sticky)**.
{{< example >}}
<nav class="navbar navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">Default</a>
</div>
</nav>
{{< /example >}}
{{< example >}}
<nav class="navbar fixed-top navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">Fixed top</a>
</div>
</nav>
{{< /example >}}
{{< example >}}
<nav class="navbar fixed-bottom navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">Fixed bottom</a>
</div>
</nav>
{{< /example >}}
{{< example >}}
<nav class="navbar sticky-top navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">Sticky top</a>
</div>
</nav>
{{< /example >}}
## Scrolling
Add `.navbar-nav-scroll` to a `.navbar-nav` (or other navbar sub-component) to enable vertical scrolling within the toggleable contents of a collapsed navbar. By default, scrolling kicks in at `75vh` (or 75% of the viewport height), but you can override that with the local CSS custom property `--bs-navbar-height` or custom styles. At larger viewports when the navbar is expanded, content will appear as it does in a default navbar.
Please note that this behavior comes with a potential drawback of `overflow`—when setting `overflow-y: auto` (required to scroll the content here), `overflow-x` is the equivalent of `auto`, which will crop some horizontal content.
Here's an example navbar using `.navbar-nav-scroll` with `style="--bs-scroll-height: 100px;"`, with some extra margin utilities for optimum spacing.
{{< example >}}
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar scroll</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarScroll" aria-controls="navbarScroll" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarScroll">
<ul class="navbar-nav me-auto my-2 my-lg-0 navbar-nav-scroll" style="--bs-scroll-height: 100px;">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarScrollingDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Link
</a>
<ul class="dropdown-menu" aria-labelledby="navbarScrollingDropdown">
<li><a class="dropdown-item" href="#">Action</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="#">Something else here</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Link</a>
</li>
</ul>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
{{< /example >}}
## Responsive behaviors
Navbars can use `.navbar-toggler`, `.navbar-collapse`, and `.navbar-expand{-sm|-md|-lg|-xl|-xxl}` classes to determine when their content collapses behind a button. In combination with other utilities, you can easily choose when to show or hide particular elements.
For navbars that never collapse, add the `.navbar-expand` class on the navbar. For navbars that always collapse, don't add any `.navbar-expand` class.
### Toggler
Navbar togglers are left-aligned by default, but should they follow a sibling element like a `.navbar-brand`, they'll automatically be aligned to the far right. Reversing your markup will reverse the placement of the toggler. Below are examples of different toggle styles.
With no `.navbar-brand` shown at the smallest breakpoint:
{{< example >}}
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarTogglerDemo01">
<a class="navbar-brand" href="#">Hidden brand</a>
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
</li>
</ul>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
{{< /example >}}
With a brand name shown on the left and toggler on the right:
{{< example >}}
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02" aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarTogglerDemo02">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
</li>
</ul>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
{{< /example >}}
With a toggler on the left and brand name on the right:
{{< example >}}
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo03" aria-controls="navbarTogglerDemo03" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#">Navbar</a>
<div class="collapse navbar-collapse" id="navbarTogglerDemo03">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
</li>
</ul>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
{{< /example >}}
### External content
Sometimes you want to use the collapse plugin to trigger a container element for content that structurally sits outside of the `.navbar` . Because our plugin works on the `id` and `data-bs-target` matching, that's easily done!
{{< example >}}
<div class="collapse" id="navbarToggleExternalContent">
<div class="bg-dark p-4">
<h5 class="text-white h4">Collapsed content</h5>
<span class="text-muted">Toggleable via the navbar brand.</span>
</div>
</div>
<nav class="navbar navbar-dark bg-dark">
<div class="container-fluid">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarToggleExternalContent" aria-controls="navbarToggleExternalContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
</div>
</nav>
{{< /example >}}
When you do this, we recommend including additional JavaScript to move the focus programmatically to the container when it is opened. Otherwise, keyboard users and users of assistive technologies will likely have a hard time finding the newly revealed content - particularly if the container that was opened comes *before* the toggler in the document's structure. We also recommend making sure that the toggler has the `aria-controls` attribute, pointing to the `id` of the content container. In theory, this allows assistive technology users to jump directly from the toggler to the container it controls–but support for this is currently quite patchy.
## Sass
### Variables
{{< scss-docs name="navbar-variables" file="scss/_variables.scss" >}}
{{< scss-docs name="navbar-theme-variables" file="scss/_variables.scss" >}}
### Loop
[Responsive navbar expand/collapse classes](#responsive-behaviors) (e.g., `.navbar-expand-lg`) are combined with the `$breakpoints` map and generated through a loop in `scss/_navbar.scss`.
{{< scss-docs name="navbar-expand-loop" file="scss/_navbar.scss" >}}
| {
"content_hash": "916a1a19db9b9076fab1b4598967dcf1",
"timestamp": "",
"source": "github",
"line_count": 669,
"max_line_length": 653,
"avg_line_length": 42.79671150971599,
"alnum_prop": 0.6474101498375886,
"repo_name": "GerHobbelt/bootstrap",
"id": "7b57fd5c627325070607487b38b0cf96f302f1d9",
"size": "28641",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "site/content/docs/5.0/components/navbar.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "217829"
},
{
"name": "HTML",
"bytes": "491372"
},
{
"name": "JavaScript",
"bytes": "690450"
},
{
"name": "PowerShell",
"bytes": "1040"
},
{
"name": "SCSS",
"bytes": "261680"
},
{
"name": "Shell",
"bytes": "2057"
}
],
"symlink_target": ""
} |
package com.github.mmichaelis.hamcrest.nextdeed.concurrent;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.TimeUnit;
/**
* <p>
* A builder for WaitFunctions.
* </p>
*
* @param <T> input the function will receive
* @param <R> output the function will provide
* @since 1.0.0
*/
public interface WaitFunctionBuilder<T, R> extends Supplier<Function<T, R>>, WaitBuilder {
/**
* Predicate which the returned function value must fulfill. Defaults to
* always true.
*
* @param predicate predicate to use
* @return self-reference
*/
@NotNull
WaitFunctionBuilder<T, R> toFulfill(@NotNull Predicate<? super R> predicate);
/**
* <p>
* Function to apply to timeout event on timeout. The function might consider to throw an
* exception for example or ignore the actual timeout but return some default result
* instead.
* </p>
*
* @param timeoutFunction function to call on timeout
* @return self-reference
*/
@NotNull
WaitFunctionBuilder<T, R> onTimeout(@NotNull Function<WaitTimeoutEvent<T, R>, R> timeoutFunction);
@Override
@NotNull
WaitFunctionBuilder<T, R> withinMs(long timeoutMs);
@Override
@NotNull
WaitFunctionBuilder<T, R> within(long timeout, @NotNull TimeUnit timeUnit);
@Override
@NotNull
WaitFunctionBuilder<T, R> withFinalGracePeriodMs(long gracePeriodMs);
@Override
@NotNull
WaitFunctionBuilder<T, R> withFinalGracePeriod(long gracePeriod, @NotNull TimeUnit timeUnit);
@Override
@NotNull
WaitFunctionBuilder<T, R> withInitialDelayMs(long initialDelayMs);
@Override
@NotNull
WaitFunctionBuilder<T, R> withInitialDelay(long initialDelay, @NotNull TimeUnit timeUnit);
@Override
@NotNull
WaitFunctionBuilder<T, R> deceleratePollingBy(double decelerationFactor);
@Override
@NotNull
WaitFunctionBuilder<T, R> and();
}
| {
"content_hash": "896181cb0952eca86bba1c5e39ca6fef",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 100,
"avg_line_length": 25.474358974358974,
"alnum_prop": 0.7332662304982386,
"repo_name": "mmichaelis/hamcrest-nextdeed",
"id": "d45b1f37231bf3ce33ff9e11cbebbbc0c7d7ab18",
"size": "2582",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/github/mmichaelis/hamcrest/nextdeed/concurrent/WaitFunctionBuilder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "192878"
},
{
"name": "Shell",
"bytes": "365"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>[ES6] destructuring</title>
<meta name="keywords" content=" 비구조화 할당(destructuring assignment) 구문은 배열 또는 객체에서 데이터를 별개(distinct) 변수로 추출할 수 있게 하는 JavaScript 식(expression). Array Destructuring Object Destructuring">
<meta name="description" content=" 비구조화 할당(destructuring assignment) 구문은 배열 또는 객체에서 데이터를 별개(distinct) 변수로 추출할 수 있게 하는 JavaScript 식(expression). Array Destructuring Object Destructuring">
<!-- CSS files -->
<link rel="stylesheet" href="http://localhost:4000/css/font-awesome.min.css">
<link rel="stylesheet" href="http://localhost:4000/css/main.css">
<link rel="canonical" href="http://localhost:4000/articles/2017-01/Destructuring">
<link rel="alternate" type="application/rss+xml" title="Front-End Developer Skill Blog" href="http://localhost:4000/feed.xml" />
<!-- Icons -->
<!-- 16x16 -->
<link rel="shortcut icon" href="http://localhost:4000/favicon.ico">
<!-- 32x32 -->
<link rel="shortcut icon" href="http://localhost:4000/favicon.png">
</head>
<body>
<div class="row">
<div class="col s12 m3">
<div class="table cover">
<div class="cover-card table-cell table-middle">
<a href="http://localhost:4000/">
<img src="http://localhost:4000/img/coding.jpg" alt="" class="avatar">
</a>
<a href="http://localhost:4000/" class="author_name">Claire</a>
<span class="author_job">Front-End Developer</span>
<span class="author_bio mbm">KEEP CALM AND LOVE CODING</span>
<nav class="nav">
<ul class="nav-list">
<li class="nav-item">
<a href="http://localhost:4000/">home</a>
</li>
<li class="nav-item">
<a href="http://localhost:4000/archive/">Archive</a>
</li>
<li class="nav-item">
<a href="http://localhost:4000/categories/">Categories</a>
</li>
<li class="nav-item">
<a href="http://localhost:4000/tags/">Tags</a>
</li>
</ul>
</nav>
<script type="text/javascript">
// based on http://stackoverflow.com/a/10300743/280842
function gen_mail_to_link(hs, subject) {
var lhs,rhs;
var p = hs.split('@');
lhs = p[0];
rhs = p[1];
document.write("<a class=\"social-link-item\" target=\"_blank\" href=\"mailto");
document.write(":" + lhs + "@");
document.write(rhs + "?subject=" + subject + "\"><i class=\"fa fa-fw fa-envelope\"></i><\/a>");
}
</script>
<div class="social-links">
<ul>
<li>
<script>gen_mail_to_link('rockquai@gmail.com', 'Hello from website');</script>
</li>
<li><a href="http://facebook.com/rockquai" class="social-link-item" target="_blank"><i class="fa fa-fw fa-facebook"></i></a></li>
<li><a href="http://github.com/rockquai" class="social-link-item" target="_blank"><i class="fa fa-fw fa-github"></i></a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="col s12 m9">
<div class="post-listing">
<a class="btn" href= "http://localhost:4000/" >
Home
</a>
<a class="btn" href= "http://localhost:4000/categories" >
Categories
</a>
<div id="post">
<header class="post-header">
<h1 title="[ES6] destructuring">[ES6] destructuring</h1>
<span class="post-meta">
<span class="post-date">
15 JAN 2017
</span>
•
<span class="read-time" title="Estimated read time">
2 mins read
</span>
</span>
</header>
<article class="post-content">
<ul>
<li>비구조화 할당(destructuring assignment) 구문은 배열 또는 객체에서 데이터를 별개(distinct) 변수로 추출할 수 있게 하는 JavaScript 식(expression).</li>
<li>Array Destructuring</li>
<li>Object Destructuring</li>
</ul>
<!--more-->
<h3 id="destructuring"><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment0">Destructuring</a></h3>
<h4 id="1-array-destructuring">1. Array Destructuring</h4>
<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">numbers</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">];</span>
<span class="kd">const</span> <span class="p">[</span><span class="nx">one</span><span class="p">,</span> <span class="nx">two</span><span class="p">,</span> <span class="nx">three</span><span class="p">,</span> <span class="nx">four</span><span class="p">,</span> <span class="nx">five</span><span class="p">]</span> <span class="o">=</span> <span class="nx">numbers</span><span class="p">;</span>
<span class="c1">// const one = numbers[0];</span>
<span class="c1">// const two = numbers[1];</span>
<span class="c1">// const three = numbers[2];</span>
<span class="c1">// const four = numbers[3];</span>
<span class="c1">// const five = numbers[4];</span>
<span class="c1">// const six = numbers[5]; //undefined</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">one</span><span class="p">);</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">two</span><span class="p">);</span>
</code></pre></div></div>
<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">numbers</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">];</span>
<span class="kd">const</span> <span class="p">[</span><span class="nx">one</span><span class="p">,</span> <span class="p">,</span> <span class="p">,</span> <span class="p">,</span><span class="nx">five</span><span class="p">]</span> <span class="o">=</span> <span class="nx">numbers</span><span class="p">;</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">one</span><span class="p">);</span> <span class="c1">// 1</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">five</span><span class="p">);</span> <span class="c1">// 5</span>
<span class="kd">const</span> <span class="nx">sum1</span> <span class="o">=</span> <span class="p">([</span><span class="nx">a</span><span class="p">,</span> <span class="nx">b</span><span class="p">,</span> <span class="nx">c</span><span class="p">,</span> <span class="nx">d</span><span class="p">,</span> <span class="nx">e</span><span class="p">])</span> <span class="o">=></span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">a</span> <span class="o">+</span> <span class="nx">b</span> <span class="o">+</span> <span class="nx">c</span> <span class="o">+</span> <span class="nx">d</span> <span class="o">+</span> <span class="nx">e</span><span class="p">);</span>
<span class="p">}</span>
<span class="nx">sum1</span><span class="p">(</span><span class="nx">numbers</span><span class="p">);</span> <span class="c1">// 15</span>
<span class="kd">const</span> <span class="nx">sum2</span> <span class="o">=</span> <span class="p">([</span><span class="nx">a</span><span class="p">,</span> <span class="nx">b</span><span class="p">,</span> <span class="nx">c</span><span class="p">])</span> <span class="o">=></span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">a</span> <span class="o">+</span> <span class="nx">b</span> <span class="o">+</span> <span class="nx">c</span><span class="p">);</span> <span class="c1">// a:1, b:2, c: 3</span>
<span class="p">}</span>
<span class="nx">sum2</span><span class="p">(</span><span class="nx">numbers</span><span class="p">);</span> <span class="c1">// 6</span>
<span class="kd">const</span> <span class="nx">sum3</span> <span class="o">=</span> <span class="p">([</span><span class="nx">a</span><span class="p">,</span> <span class="nx">b</span><span class="p">,</span> <span class="p">...</span><span class="nx">c</span><span class="p">])</span> <span class="o">=></span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">c</span><span class="p">);</span>
<span class="p">}</span>
<span class="nx">sum3</span><span class="p">(</span><span class="nx">numbers</span><span class="p">);</span> <span class="c1">// [3, 4, 5]</span>
</code></pre></div></div>
<h4 id="2-object-destructuring">2. Object Destructuring</h4>
<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">address</span> <span class="o">=</span> <span class="p">{</span>
<span class="na">city</span> <span class="p">:</span> <span class="s1">'new york'</span><span class="p">,</span>
<span class="na">state</span> <span class="p">:</span> <span class="s1">'NY'</span><span class="p">,</span>
<span class="na">zipcode</span> <span class="p">:</span> <span class="s1">'10003'</span>
<span class="p">}</span>
<span class="kd">const</span> <span class="p">{</span> <span class="nx">city</span><span class="p">,</span> <span class="nx">state</span> <span class="p">}</span> <span class="o">=</span> <span class="nx">address</span><span class="p">;</span>
<span class="c1">// const city = address.city;</span>
<span class="c1">// const state = address.state;</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">city</span> <span class="o">+</span> <span class="s1">', '</span> <span class="o">+</span> <span class="nx">state</span><span class="p">);</span> <span class="c1">// new your, NY</span>
<span class="kd">const</span> <span class="p">{</span> <span class="na">city</span><span class="p">:</span> <span class="nx">c</span><span class="p">,</span> <span class="na">state</span><span class="p">:</span> <span class="nx">s</span> <span class="p">}</span> <span class="o">=</span> <span class="nx">address</span><span class="p">;</span>
<span class="c1">// const c = address.city;</span>
<span class="c1">// const s = address.state;</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">c</span> <span class="o">+</span> <span class="s1">', '</span> <span class="o">+</span> <span class="nx">s</span><span class="p">);</span> <span class="c1">// new your, NY</span>
<span class="kd">function</span> <span class="nx">logAddress</span><span class="p">({</span> <span class="nx">city</span><span class="p">,</span> <span class="nx">state</span> <span class="p">})</span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">city</span> <span class="o">+</span> <span class="s1">', '</span> <span class="o">+</span> <span class="nx">state</span><span class="p">);</span>
<span class="p">}</span>
<span class="nx">logAddress</span><span class="p">(</span><span class="nx">address</span><span class="p">);</span> <span class="c1">// new your, NY</span>
</code></pre></div></div>
</article>
</div>
<div class="share-buttons">
<h6>Share on: </h6>
<ul>
<li>
<a href="https://twitter.com/intent/tweet?text=http://localhost:4000/articles/2017-01/Destructuring" class="twitter btn" title="Share on Twitter"><i class="fa fa-twitter"></i><span> Twitter</span></a>
</li>
<li>
<a href="https://www.facebook.com/sharer/sharer.php=http://localhost:4000/articles/2017-01/Destructuring" class="facebook btn" title="Share on Facebook"><i class="fa fa-facebook"></i><span> Facebook</span></a>
</li>
<li>
<a href="https://plus.google.com/share?url=http://localhost:4000/articles/2017-01/Destructuring" class="google-plus btn" title="Share on Google Plus"><i class="fa fa-google-plus"></i><span> Google+</span></a>
</li>
<li>
<a href="https://news.ycombinator.com/submitlink?u=http://localhost:4000/articles/2017-01/Destructuring" class="hacker-news btn" title="Share on Hacker News"><i class="fa fa-hacker-news"></i><span> Hacker News</span></a>
</li>
<li>
<a href="https://www.reddit.com/submit?url=http://localhost:4000/articles/2017-01/Destructuring" class="reddit btn" title="Share on Reddit"><i class="fa fa-reddit"></i><span> Reddit</span></a>
</li>
</ul>
</div><!-- end share-buttons -->
<footer>
© 2018 Claire. Powered by <a href="http://jekyllrb.com/">Jekyll</a>, <a href="http://github.com/renyuanz/leonids/">leonids theme</a> made with <i class="fa fa-heart heart-icon"></i>
</footer>
</div>
</div>
</div>
<script type="text/javascript" src="http://localhost:4000/js/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="http://localhost:4000/js/main.js"></script>
</body>
</html>
| {
"content_hash": "b901c59cb799504b740a8e6075330c1a",
"timestamp": "",
"source": "github",
"line_count": 257,
"max_line_length": 452,
"avg_line_length": 53.400778210116734,
"alnum_prop": 0.615126785193821,
"repo_name": "rockquai/rockquai.github.io",
"id": "688c53d669087f60b77eada6395824c6aec3aabf",
"size": "13936",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_site/articles/2017-01/Destructuring.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "79263"
},
{
"name": "HTML",
"bytes": "877384"
},
{
"name": "JavaScript",
"bytes": "70"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>cdmf-transport-adapters</artifactId>
<version>4.1.19-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.input.adapter.mqtt</artifactId>
<packaging>bundle</packaging>
<name>WSO2 Carbon - Device Mgt Input Adaptor Module - MQTT</name>
<description>Provides the back-end functionality of Input adaptor</description>
<url>http://wso2.org</url>
<dependencies>
<dependency>
<groupId>commons-codec.wso2</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.input.adapter.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.core</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents.wso2</groupId>
<artifactId>httpcore</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.orbit.org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple.wso2</groupId>
<artifactId>json-simple</artifactId>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity.inbound.auth.oauth2</groupId>
<artifactId>org.wso2.carbon.identity.oauth.stub</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.input.adapter.extension</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
<executions>
<execution>
<id>generate-scr-descriptor</id>
<goals>
<goal>scr</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Private-Package>
org.wso2.carbon.device.mgt.input.adapter.mqtt.internal,
org.wso2.carbon.device.mgt.input.adapter.mqtt.internal.*
</Private-Package>
<Export-Package>
!org.wso2.carbon.device.mgt.input.adapter.mqtt.internal,
!org.wso2.carbon.device.mgt.input.adapter.mqtt.internal.*,
org.wso2.carbon.device.mgt.input.adapter.mqtt.*
</Export-Package>
<Import-Package>
org.wso2.carbon.event.input.adapter.core,
org.wso2.carbon.event.input.adapter.core.*,
javax.xml.namespace; version=0.0.0,
org.eclipse.paho.client.mqttv3.*,
org.apache.http;version="${httpclient.version.range}",
org.apache.http.message;version="${httpclient.version.range}",
org.apache.http.client;version="${httpclient.version.range}",
org.apache.http.impl;version="${httpclient.version.range}",
org.apache.http.conn.*;version="${httpclient.version.range}",
org.apache.http.util;version="${httpclient.version.range}",
org.apache.http.client.entity;version="${httpclient.version.range}",
org.apache.http.client.methods;version="${httpclient.version.range}",
org.apache.http.impl.client;version="${httpclient.version.range}",
org.json.simple.*,
com.jayway.jsonpath.*,
org.wso2.carbon.identity.jwt.client.extension.*,
javax.net.ssl,
org.apache.commons.codec.binary,
org.apache.commons.logging,
org.apache.http.entity,
org.osgi.framework,
org.osgi.service.component,
org.osgi.service.http,
org.wso2.carbon.context,
org.wso2.carbon.core,
org.wso2.carbon.device.mgt.input.adapter.extension,
org.wso2.carbon.user.api,
org.wso2.carbon.utils.multitenancy,
org.apache.axis2.context,
org.wso2.carbon.core.multitenancy.utils,
org.wso2.carbon.utils
</Import-Package>
</instructions>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<configuration>
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
</configuration>
<executions>
<execution>
<id>jacoco-initialize</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>jacoco-site</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "88cc8d04ba63304d8bd7a8f6fa568a96",
"timestamp": "",
"source": "github",
"line_count": 185,
"max_line_length": 204,
"avg_line_length": 46.65405405405406,
"alnum_prop": 0.5225350480824933,
"repo_name": "lasanthaDLPDS/carbon-device-mgt-plugins",
"id": "6fba1679b4e10d83d387d51e5b56373894530f2f",
"size": "8631",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "912"
},
{
"name": "C",
"bytes": "2475"
},
{
"name": "C++",
"bytes": "14451"
},
{
"name": "CSS",
"bytes": "565755"
},
{
"name": "HTML",
"bytes": "679943"
},
{
"name": "Java",
"bytes": "3860603"
},
{
"name": "JavaScript",
"bytes": "9901466"
},
{
"name": "PLSQL",
"bytes": "4277"
},
{
"name": "Python",
"bytes": "36818"
},
{
"name": "Shell",
"bytes": "16631"
}
],
"symlink_target": ""
} |
jname=restupAgent
if [ ! -d ./org/net ]
then mkdir -p ./org/net/restupAgent
else rm -f ./org/net/restupAgent/*.*
fi
javac -Xstdout ./compile.log -Xlint:unchecked -cp ./org/net/restupAgent -d ./ \
RESTup.java ResultFile.java Job.java Service.java Agent.java
if [ $? -eq 0 ] ; then
jar cvf ./${jname}.jar ./org/net/restupAgent/*.class
javadoc -d ./agentDoc -nodeprecated -use package-info.java Agent.java Service.java Job.java ResultFile.java
fi
more < ./compile.log
| {
"content_hash": "2ed5ae9a708f6337fb1297a01bce06c9",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 109,
"avg_line_length": 36.69230769230769,
"alnum_prop": 0.6981132075471698,
"repo_name": "miktim/RESTup",
"id": "67bf584fa33734acf681d2785265975eb22707aa",
"size": "490",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Agents/Java/buildAgent.sh",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "570"
},
{
"name": "Java",
"bytes": "102989"
},
{
"name": "JavaScript",
"bytes": "6464"
},
{
"name": "PLSQL",
"bytes": "16003"
},
{
"name": "Shell",
"bytes": "3022"
}
],
"symlink_target": ""
} |
using namespace arangodb;
using namespace arangodb::graph;
ConstantWeightShortestPathFinder::PathSnippet::PathSnippet(arangodb::velocypack::StringRef& pred,
EdgeDocumentToken&& path)
: _pred(pred), _path(std::move(path)) {}
ConstantWeightShortestPathFinder::ConstantWeightShortestPathFinder(ShortestPathOptions& options)
: ShortestPathFinder(options) {
// cppcheck-suppress *
_forwardCursor = _options.buildCursor(false);
// cppcheck-suppress *
_backwardCursor = _options.buildCursor(true);
}
ConstantWeightShortestPathFinder::~ConstantWeightShortestPathFinder() {
clearVisited();
}
void ConstantWeightShortestPathFinder::clear() {
clearVisited();
options().cache()->clear();
}
bool ConstantWeightShortestPathFinder::shortestPath(
arangodb::velocypack::Slice const& s, arangodb::velocypack::Slice const& e,
arangodb::graph::ShortestPathResult& result) {
result.clear();
TRI_ASSERT(s.isString());
TRI_ASSERT(e.isString());
arangodb::velocypack::StringRef start(s);
arangodb::velocypack::StringRef end(e);
// Init
if (start == end) {
result._vertices.emplace_back(start);
_options.fetchVerticesCoordinator(result._vertices);
return true;
}
_leftClosure.clear();
_rightClosure.clear();
clearVisited();
_leftFound.try_emplace(start, nullptr);
_rightFound.try_emplace(end, nullptr);
_leftClosure.emplace_back(start);
_rightClosure.emplace_back(end);
TRI_IF_FAILURE("TraversalOOMInitialize") {
THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG);
}
arangodb::velocypack::StringRef n;
while (!_leftClosure.empty() && !_rightClosure.empty()) {
options().isQueryKilledCallback();
if (_leftClosure.size() < _rightClosure.size()) {
if (expandClosure(_leftClosure, _leftFound, _rightFound, false, n)) {
fillResult(n, result);
return true;
}
} else {
if (expandClosure(_rightClosure, _rightFound, _leftFound, true, n)) {
fillResult(n, result);
return true;
}
}
}
return false;
}
bool ConstantWeightShortestPathFinder::expandClosure(
Closure& sourceClosure, Snippets& sourceSnippets, Snippets& targetSnippets,
bool isBackward, arangodb::velocypack::StringRef& result) {
_nextClosure.clear();
for (auto& v : sourceClosure) {
_edges.clear();
_neighbors.clear();
expandVertex(isBackward, v);
size_t const neighborsSize = _neighbors.size();
TRI_ASSERT(_edges.size() == neighborsSize);
for (size_t i = 0; i < neighborsSize; ++i) {
auto const& n = _neighbors[i];
bool emplaced = false;
std::tie(std::ignore, emplaced) =
sourceSnippets.try_emplace(_neighbors[i], arangodb::lazyConstruct([&] {
return new PathSnippet(v, std::move(_edges[i]));
}));
if (emplaced) {
// NOTE: _edges[i] stays intact after move
// and is reset to a nullptr. So if we crash
// here no mem-leaks. or undefined behavior
// Just make sure _edges is not used after
auto targetFoundIt = targetSnippets.find(n);
if (targetFoundIt != targetSnippets.end()) {
result = n;
return true;
}
_nextClosure.emplace_back(n);
}
}
}
_edges.clear();
_neighbors.clear();
sourceClosure.swap(_nextClosure);
_nextClosure.clear();
return false;
}
void ConstantWeightShortestPathFinder::fillResult(arangodb::velocypack::StringRef& n,
arangodb::graph::ShortestPathResult& result) {
result._vertices.emplace_back(n);
auto it = _leftFound.find(n);
TRI_ASSERT(it != _leftFound.end());
arangodb::velocypack::StringRef next;
while (it != _leftFound.end() && it->second != nullptr) {
next = it->second->_pred;
result._vertices.push_front(next);
result._edges.push_front(std::move(it->second->_path));
it = _leftFound.find(next);
}
it = _rightFound.find(n);
TRI_ASSERT(it != _rightFound.end());
while (it != _rightFound.end() && it->second != nullptr) {
next = it->second->_pred;
result._vertices.emplace_back(next);
result._edges.emplace_back(std::move(it->second->_path));
it = _rightFound.find(next);
}
TRI_IF_FAILURE("TraversalOOMPath") {
THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG);
}
_options.fetchVerticesCoordinator(result._vertices);
clearVisited();
}
void ConstantWeightShortestPathFinder::expandVertex(bool backward,
arangodb::velocypack::StringRef vertex) {
EdgeCursor* cursor = backward ? _backwardCursor.get() : _forwardCursor.get();
cursor->rearm(vertex, 0);
cursor->readAll([&](EdgeDocumentToken&& eid, VPackSlice edge, size_t cursorIdx) -> void {
if (edge.isString()) {
if (edge.compareString(vertex.data(), vertex.length()) != 0) {
arangodb::velocypack::StringRef id =
_options.cache()->persistString(arangodb::velocypack::StringRef(edge));
_edges.emplace_back(std::move(eid));
_neighbors.emplace_back(id);
}
} else {
arangodb::velocypack::StringRef other(
transaction::helpers::extractFromFromDocument(edge));
if (other == vertex) {
other = arangodb::velocypack::StringRef(
transaction::helpers::extractToFromDocument(edge));
}
if (other != vertex) {
arangodb::velocypack::StringRef id = _options.cache()->persistString(other);
_edges.emplace_back(std::move(eid));
_neighbors.emplace_back(id);
}
}
});
}
void ConstantWeightShortestPathFinder::clearVisited() {
for (auto& it : _leftFound) {
delete it.second;
}
_leftFound.clear();
for (auto& it : _rightFound) {
delete it.second;
}
_rightFound.clear();
}
| {
"content_hash": "e242a130fc833a306497ae658703c431",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 97,
"avg_line_length": 32.720670391061454,
"alnum_prop": 0.6361618576062831,
"repo_name": "Simran-B/arangodb",
"id": "b7d32dbcfa81baed2336c57f652eb1d032fd17c1",
"size": "7324",
"binary": false,
"copies": "1",
"ref": "refs/heads/devel",
"path": "arangod/Graph/ConstantWeightShortestPathFinder.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "61827"
},
{
"name": "Batchfile",
"bytes": "3282"
},
{
"name": "C",
"bytes": "275955"
},
{
"name": "C++",
"bytes": "29221660"
},
{
"name": "CMake",
"bytes": "375992"
},
{
"name": "CSS",
"bytes": "212174"
},
{
"name": "EJS",
"bytes": "218744"
},
{
"name": "HTML",
"bytes": "23114"
},
{
"name": "JavaScript",
"bytes": "30616196"
},
{
"name": "LLVM",
"bytes": "14753"
},
{
"name": "Makefile",
"bytes": "526"
},
{
"name": "NASL",
"bytes": "129286"
},
{
"name": "NSIS",
"bytes": "49153"
},
{
"name": "PHP",
"bytes": "46519"
},
{
"name": "Pascal",
"bytes": "75391"
},
{
"name": "Perl",
"bytes": "9811"
},
{
"name": "PowerShell",
"bytes": "7885"
},
{
"name": "Python",
"bytes": "181384"
},
{
"name": "Ruby",
"bytes": "1041531"
},
{
"name": "SCSS",
"bytes": "254419"
},
{
"name": "Shell",
"bytes": "128175"
},
{
"name": "TypeScript",
"bytes": "25245"
},
{
"name": "Yacc",
"bytes": "68516"
}
],
"symlink_target": ""
} |
#define domains to query
$domains = "cva.local","corp.local","dynutil.com"
#Query listed defined domains for each domain controller and return information listed
$DCs = foreach ($domain in $domains)
{
Get-ADDomainController -Filter * -server $domain
}
$Results = New-Object -TypeName System.Collections.ArrayList
foreach($DC in $DCs){
[string]$OMRoles = ""
$ThisResult = New-Object -TypeName System.Object
Add-Member -InputObject $ThisResult -MemberType NoteProperty -Name Name -Value $DC.Name
Add-Member -InputObject $ThisResult -MemberType NoteProperty -Name Forest -Value $DC.Forest
Add-Member -InputObject $ThisResult -MemberType NoteProperty -Name Domain -Value $DC.Domain
Add-Member -InputObject $ThisResult -MemberType NoteProperty -Name Site -Value $DC.Site
Add-Member -InputObject $ThisResult -MemberType NoteProperty -Name IPv4Address -Value $DC.IPv4Address
Add-Member -InputObject $ThisResult -MemberType NoteProperty -Name OperatingSystem -Value $DC.OperatingSystem
Add-Member -InputObject $ThisResult -MemberType NoteProperty -Name OperatingSystemVersion -Value $DC.OperatingSystemVersion
Add-Member -InputObject $ThisResult -MemberType NoteProperty -Name IsGlobalCatalog -Value $DC.IsGlobalCatalog
Add-Member -InputObject $ThisResult -MemberType NoteProperty -Name IsReadOnly -Value $DC.IsReadOnly
foreach($OMRole in $DC.OperationMasterRoles){
$OMRoles += ([string]$OMRole+" ")
}
Add-Member -InputObject $ThisResult -MemberType NoteProperty -Name OperationMasterRoles -Value $OMRoles
$Results.Add($ThisResult) | Out-Null
}
$Results = $Results | Sort-Object -Property Domain,site
$Results | export-csv c:\temp\dynutilDCs.csv -NoTypeInformation | {
"content_hash": "4dc5f43ef53cb54666c56f2e18cd5961",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 127,
"avg_line_length": 58.7,
"alnum_prop": 0.7524134014764339,
"repo_name": "failbringerUD/powershell",
"id": "ce44812a96f2b9a5eb14101dc0c380aa108ba0f8",
"size": "1860",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Dycom/get-dcinfo.ps1",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1095"
},
{
"name": "PowerShell",
"bytes": "1126373"
},
{
"name": "Visual Basic",
"bytes": "541"
}
],
"symlink_target": ""
} |
I'm learning Git.
## Title
This is a para.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
### Level 3
Test
#### Level 4
Test | {
"content_hash": "f69fa31ddee2f23fce22e3aa1ff29339",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 446,
"avg_line_length": 35.4,
"alnum_prop": 0.7890772128060264,
"repo_name": "rsgranne/webster-test-1",
"id": "5d07265ee2749de13dfdcc88d2a18e459facd441",
"size": "549",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "658"
},
{
"name": "HTML",
"bytes": "4362"
}
],
"symlink_target": ""
} |
struct default_init_tag;
class poi::hssf::record::FormulaRecord_SpecialCachedValue final
: public ::java::lang::Object
{
public:
typedef ::java::lang::Object super;
private:
static constexpr int64_t BIT_MARKER { int64_t(-281474976710656LL) };
static constexpr int32_t VARIABLE_DATA_LENGTH { int32_t(6) };
static constexpr int32_t DATA_INDEX { int32_t(2) };
public:
static constexpr int32_t STRING { int32_t(0) };
static constexpr int32_t BOOLEAN { int32_t(1) };
static constexpr int32_t ERROR_CODE { int32_t(2) };
static constexpr int32_t EMPTY { int32_t(3) };
private:
::int8_tArray* _variableData { };
protected:
void ctor(::int8_tArray* data);
public:
int32_t getTypeCode();
static FormulaRecord_SpecialCachedValue* create(int64_t valueLongBits);
void serialize(::poi::util::LittleEndianOutput* out);
::java::lang::String* formatDebugString();
private:
::java::lang::String* formatValue();
int32_t getDataValue();
public:
static FormulaRecord_SpecialCachedValue* createCachedEmptyValue();
static FormulaRecord_SpecialCachedValue* createForString();
static FormulaRecord_SpecialCachedValue* createCachedBoolean(bool b);
static FormulaRecord_SpecialCachedValue* createCachedErrorCode(int32_t errorCode);
private:
static FormulaRecord_SpecialCachedValue* create(int32_t code, int32_t data);
public:
::java::lang::String* toString() override;
int32_t getValueType();
bool getBooleanValue();
int32_t getErrorValue();
// Generated
private:
FormulaRecord_SpecialCachedValue(::int8_tArray* data);
protected:
FormulaRecord_SpecialCachedValue(const ::default_init_tag&);
public:
static ::java::lang::Class *class_();
private:
virtual ::java::lang::Class* getClass0();
friend class FormulaRecord;
};
| {
"content_hash": "b46b52968fb97e8e3d20512103a2189f",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 86,
"avg_line_length": 28.246153846153845,
"alnum_prop": 0.710239651416122,
"repo_name": "pebble2015/cpoi",
"id": "89ea76728a3a81c229e4a6aa894f487b8efb3fbf",
"size": "2107",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/org/apache/poi/hssf/record/FormulaRecord_SpecialCachedValue.hpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "15964112"
},
{
"name": "Makefile",
"bytes": "138107"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
Agron. lusit. 3(1): 27 (1941)
#### Original name
Kalmusia jasmini Sousa da Câmara & Luz
### Remarks
null | {
"content_hash": "b5b3a15e05a81bd06dc8802b5b714e6d",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 38,
"avg_line_length": 12.923076923076923,
"alnum_prop": 0.6845238095238095,
"repo_name": "mdoering/backbone",
"id": "5b18320afec7ed861fba9cc0843c9e4ab3393fbe",
"size": "232",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Montagnulaceae/Kalmusia/Kalmusia jasmini/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace OnTheRoad.CustomControllers {
public partial class TagsSelect {
/// <summary>
/// TagsUpdatePanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.UpdatePanel TagsUpdatePanel;
/// <summary>
/// TagsRepeater control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Repeater TagsRepeater;
/// <summary>
/// TagsTextBox control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox TagsTextBox;
/// <summary>
/// TagSelectButton control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button TagSelectButton;
/// <summary>
/// TagsAutoComplete control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::AjaxControlToolkit.AutoCompleteExtender TagsAutoComplete;
}
}
| {
"content_hash": "b90407f57e794d192d46f1e5681c9ee7",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 84,
"avg_line_length": 35.03333333333333,
"alnum_prop": 0.5318744053282588,
"repo_name": "WeWantAngular/on-the-road",
"id": "71ff6aa14b114a621ac3bbfe7eb7390267e93806",
"size": "2104",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "OnTheRoad/OnTheRoad/CustomControllers/TagsSelect.ascx.designer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "62277"
},
{
"name": "C#",
"bytes": "550599"
},
{
"name": "CSS",
"bytes": "171354"
},
{
"name": "HTML",
"bytes": "1035"
},
{
"name": "JavaScript",
"bytes": "170489"
}
],
"symlink_target": ""
} |
@interface ApigeeResultViewController : UIViewController
@property NSString *action;
@property (weak, nonatomic) IBOutlet UITextView *resultTextView;
@end
| {
"content_hash": "95be60194e3e6eb1804774d39106ef3e",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 64,
"avg_line_length": 31.2,
"alnum_prop": 0.8269230769230769,
"repo_name": "RobertWalsh/apigee-ios-sdk",
"id": "c3b15c295aa94433badab82bcf68fb6fd2706dc9",
"size": "332",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "samples/geolocation/geolocation/ApigeeResultViewController.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "7524"
},
{
"name": "C",
"bytes": "530343"
},
{
"name": "C++",
"bytes": "326040"
},
{
"name": "CSS",
"bytes": "1255"
},
{
"name": "HTML",
"bytes": "5765"
},
{
"name": "Objective-C",
"bytes": "1822027"
},
{
"name": "Objective-C++",
"bytes": "17194"
},
{
"name": "Perl",
"bytes": "39138"
},
{
"name": "Protocol Buffer",
"bytes": "9304"
},
{
"name": "Ruby",
"bytes": "1224"
},
{
"name": "Shell",
"bytes": "11934"
}
],
"symlink_target": ""
} |
A weather station project based on Arduino. Some more info and background in my [blog post about the project][BLOG].
## Compontents
The current parts of the setup consists of a humidity monitor and a server to monitor, display and log values
### humidity1
The Arduino script that currently takes the measurements, in my case with a [CM-R resistive humidity detector][HUM].
### Server
A Node.js server that takes the data and displays in your browser on a [graph][GRAPH]. Also longs into MongoDB, with parameters adjusted through the `MONGO_URL` and `MONGO_DB` environmental variables.
## License
[MIT license][MIT]: do whatever you like. See more info in `License`.
[BLOG]: http://gergely.imreh.net/blog/2012/06/lets-talk-about-humidity/ "Let's talk about humidity, on ClickedyClick"
[HUM]: http://file.yizimg.com/3381/20061221103057890280486.pdf "English spec sheet"
[GRAPH]: http://file.yizimg.com/3381/20061221103057890280486.pdf "Example plot of humidity data"
[MIT]: http://en.wikipedia.org/wiki/MIT_License "MIT License on Wikipedia" | {
"content_hash": "3702bd50e197a6bb3a14a7744d8dfc30",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 200,
"avg_line_length": 47.81818181818182,
"alnum_prop": 0.7642585551330798,
"repo_name": "UltracoldAtomsLab/weatherstation",
"id": "128ee148d8f0134d03d561062a584813f4bbf23b",
"size": "1070",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Readme.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Arduino",
"bytes": "3999"
},
{
"name": "JavaScript",
"bytes": "110007"
}
],
"symlink_target": ""
} |
var internal = require("internal");
var console = require("console");
var fs = require("fs");
var printf = internal.printf;
////////////////////////////////////////////////////////////////////////////////
/// @brief unload a collection
////////////////////////////////////////////////////////////////////////////////
function UnloadCollection (collection) {
var last = Math.round(internal.time());
// unload collection if not yet unloaded (2) & not corrupted (0)
while (collection.status() !== 2 && collection.status() !== 0) {
collection.unload();
var next = Math.round(internal.time());
if (next !== last) {
printf("Trying to unload collection '%s'\n", collection.name());
last = next;
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief remove datafile
////////////////////////////////////////////////////////////////////////////////
function RemoveDatafile (collection, type, datafile) {
var backup = datafile + ".corrupt";
fs.move(datafile, backup);
printf("Removed %s at %s\n", type, datafile);
printf("Backup is in %s\n", backup);
printf("\n");
}
////////////////////////////////////////////////////////////////////////////////
/// @brief try to repair a datafile
////////////////////////////////////////////////////////////////////////////////
function TryRepairDatafile (collection, datafile) {
UnloadCollection(collection);
return collection.tryRepairDatafile(datafile);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief wipe entries
////////////////////////////////////////////////////////////////////////////////
function WipeDatafile (collection, type, datafile, lastGoodPos) {
UnloadCollection(collection);
collection.truncateDatafile(datafile, lastGoodPos);
printf("Truncated and sealed datafile\n");
}
////////////////////////////////////////////////////////////////////////////////
/// @brief queries user to wipe a datafile
////////////////////////////////////////////////////////////////////////////////
function QueryWipeDatafile (collection, type, datafile, scan, lastGoodPos) {
var entries = scan.entries;
if (entries.length === 0) {
if (type === "journal" || type === "compactor") {
printf("WARNING: The journal is empty. Even the header is missing. Going\n");
printf(" to remove the file.\n");
}
else {
printf("WARNING: The datafile is empty. Even the header is missing. Going\n");
printf(" to remove the datafile. This should never happen. Datafiles\n");
printf(" are append-only. Make sure your hard disk does not contain\n");
printf(" any hardware errors.\n");
}
printf("\n");
RemoveDatafile(collection, type, datafile);
return;
}
var ask = true;
var tryRepair = false;
if (type === "journal") {
if (entries.length === lastGoodPos + 3 && entries[lastGoodPos + 2].status === 2) {
printf("WARNING: The journal was not closed properly, the last entry is corrupted.\n");
printf(" This might happen if ArangoDB was killed and the last entry was not\n");
printf(" fully written to disk. Going to remove the last entry.\n");
ask = false;
}
else {
printf("WARNING: The journal was not closed properly, the last entries are corrupted.\n");
printf(" This might happen if ArangoDB was killed and the last entries were not\n");
printf(" fully written to disk.\n");
}
}
else {
printf("WARNING: The datafile contains corrupt entries. This should never happen.\n");
printf(" Datafiles are append-only. Make sure your hard disk does not contain\n");
printf(" any hardware errors.\n");
tryRepair = true;
}
printf("\n");
var entry = entries[lastGoodPos];
if (ask) {
var line;
if (tryRepair) {
printf("Try to repair the error(s) (Y/N)? ");
line = console.getline();
if (line === "yes" || line === "YES" || line === "y" || line === "Y") {
if (TryRepairDatafile(collection, datafile)) {
printf("Repair succeeded.\n");
return;
}
printf("Repair failed.\n");
}
}
printf("Wipe the last entries (Y/N)? ");
line = console.getline();
if (line !== "yes" && line !== "YES" && line !== "y" && line !== "Y") {
printf("ABORTING\n");
return;
}
}
WipeDatafile(collection, type, datafile, entry.position + entry.realSize);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief prints details about entries
////////////////////////////////////////////////////////////////////////////////
function PrintEntries (entries, amount) {
var start, end;
if (amount > 0) {
start = 0;
end = amount;
if (end > entries.length) {
end = entries.length;
}
}
else {
start = entries.length + amount - 1;
if (start < 0) {
return;
}
if (start < Math.abs(amount)) {
return;
}
end = entries.length;
}
for (var i = start; i < end; ++i) {
var entry = entries[i], extra;
var s = "unknown";
switch (entry.status) {
case 1: s = "OK"; break;
case 2: s = "OK (end)"; break;
case 3: s = "FAILED (empty)"; break;
case 4: s = "FAILED (too small)"; break;
case 5: s = "FAILED (crc mismatch)"; break;
}
if (entry.key) {
extra = " - key: " + entry.key;
}
else {
extra = "";
}
printf(" %d: status %s type %d (%s) size %d, tick %s%s\n", i, s, entry.type, entry.typeName, entry.realSize, entry.tick, extra);
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief checks a datafile deeply
////////////////////////////////////////////////////////////////////////////////
function DeepCheckDatafile (collection, type, datafile, scan) {
var entries = scan.entries;
var diagnosis = "";
var lastGood, firstBad;
var lastGoodPos = 0;
var stillGood = true;
for (var i = 0; i < entries.length; ++i) {
var entry = entries[i];
if (entry.status === 1 || entry.status === 2) {
if (stillGood) {
lastGood = entry;
lastGoodPos = i;
}
}
else {
stillGood = false;
diagnosis = entry.diagnosis || "";
firstBad = entry;
break;
}
}
if (! stillGood) {
printf(" Last good marker: start: %d (hex %s), length: %d (hex %s)\n",
lastGood.position,
lastGood.position.toString(16),
lastGood.realSize,
lastGood.realSize.toString(16));
printf(" First bad marker: start: %d (hex %s), length: %d (hex %s)\n",
firstBad.position,
firstBad.position.toString(16),
firstBad.realSize,
firstBad.realSize.toString(16));
if (diagnosis) {
printf(" Diagnosis: %s\n", diagnosis);
}
printf("\n");
QueryWipeDatafile(collection, type, datafile, scan, lastGoodPos);
}
printf("\n");
}
////////////////////////////////////////////////////////////////////////////////
/// @brief checks a datafile
////////////////////////////////////////////////////////////////////////////////
function CheckDatafile (collection, type, datafile, issues, details) {
printf("Datafile\n");
printf(" path: %s\n", datafile);
printf(" type: %s\n", type);
var scan = collection.datafileScan(datafile);
printf(" current size: %d\n", scan.currentSize);
printf(" maximal size: %d\n", scan.maximalSize);
printf(" total used: %d\n", scan.endPosition);
printf(" # of entries: %d\n", scan.numberMarkers);
printf(" status: %d\n", scan.status);
printf(" isSealed: %s\n", scan.isSealed ? "yes" : "no");
// set default value to unknown
var statusMessage = "UNKNOWN (" + scan.status + ")";
var color = internal.COLORS.COLOR_YELLOW;
switch (scan.status) {
case 1:
statusMessage = "OK";
color = internal.COLORS.COLOR_GREEN;
if (! scan.isSealed && type === "datafile") {
color = internal.COLORS.COLOR_YELLOW;
}
break;
case 2:
statusMessage = "NOT OK (reached empty marker)";
color = internal.COLORS.COLOR_RED;
break;
case 3:
statusMessage = "FATAL (reached corrupted marker)";
color = internal.COLORS.COLOR_RED;
break;
case 4:
statusMessage = "FATAL (crc failed)";
color = internal.COLORS.COLOR_RED;
break;
case 5:
statusMessage = "FATAL (cannot open datafile or too small)";
color = internal.COLORS.COLOR_RED;
break;
}
printf(color);
printf(" status: %s\n\n", statusMessage);
printf(internal.COLORS.COLOR_RESET);
if (scan.status !== 1) {
issues.push({
collection: collection.name(),
path: datafile,
type: type,
status: scan.status,
message: statusMessage,
color: color
});
}
if (scan.numberMarkers === 0) {
statusMessage = "datafile contains no entries";
color = internal.COLORS.COLOR_YELLOW;
issues.push({
collection: collection.name(),
path: datafile,
type: type,
status: scan.status,
message: statusMessage,
color: color
});
printf(color);
printf("WARNING: %s\n", statusMessage);
printf(internal.COLORS.COLOR_RESET);
RemoveDatafile(collection, type, datafile);
return;
}
const TRI_DF_MARKER_HEADER = 10;
const TRI_DF_MARKER_COL_HEADER = 20;
if (scan.entries[0].type !== TRI_DF_MARKER_HEADER) {
// asserting a TRI_DF_MARKER_HEADER as first marker
statusMessage = "datafile contains no datafile header marker at pos #0!";
color = internal.COLORS.COLOR_YELLOW;
issues.push({
collection: collection.name(),
path: datafile,
type: type,
status: scan.status,
message: statusMessage,
color: color
});
printf(color);
printf("WARNING: %s\n", statusMessage);
printf(internal.COLORS.COLOR_RESET);
RemoveDatafile(collection, type, datafile);
return;
}
if (scan.entries.length === 2 && scan.entries[1].type !== TRI_DF_MARKER_COL_HEADER) {
// asserting a TRI_COL_MARKER_HEADER as second marker
statusMessage = "datafile contains no collection header marker at pos #1!";
color = internal.COLORS.COLOR_YELLOW;
issues.push({
collection: collection.name(),
path: datafile,
type: type,
status: scan.status,
message: statusMessage,
color: color
});
printf(color);
printf("WARNING: %s\n", statusMessage);
printf(internal.COLORS.COLOR_RESET);
RemoveDatafile(collection, type, datafile);
return;
}
if (type !== "journal" && scan.entries.length === 3 && scan.entries[2].type === 0) {
// got the two initial header markers but nothing else...
statusMessage = "datafile is empty but not sealed";
color = internal.COLORS.COLOR_YELLOW;
issues.push({
collection: collection.name(),
path: datafile,
type: type,
status: scan.status,
message: statusMessage,
color: color
});
printf(color);
printf("WARNING: %s\n", statusMessage);
printf(internal.COLORS.COLOR_RESET);
RemoveDatafile(collection, type, datafile);
return;
}
if (details) {
// print details
printf("Entries\n");
if (details === "FULL") {
// print all markers
PrintEntries(scan.entries, scan.entries.length);
}
else {
// print an excerpt of the markers
PrintEntries(scan.entries, 10);
if (scan.entries.length > 20) {
printf("...\n");
}
PrintEntries(scan.entries, -10);
}
}
if (scan.status === 1 && scan.isSealed) {
return;
}
DeepCheckDatafile(collection, type, datafile, scan);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief checks a collection
////////////////////////////////////////////////////////////////////////////////
function CheckCollection (collection, issues, details) {
printf("Database\n");
printf(" name: %s\n", internal.db._name());
printf(" path: %s\n", internal.db._path());
printf("\n");
printf("Collection\n");
printf(" name: %s\n", collection.name());
printf(" identifier: %s\n", collection._id);
printf("\n");
var datafiles = collection.datafiles();
printf("Datafiles\n");
printf(" # of journals: %d\n", datafiles.journals.length);
printf(" # of compactors: %d\n", datafiles.compactors.length);
printf(" # of datafiles: %d\n", datafiles.datafiles.length);
printf("\n");
for (var i = 0; i < datafiles.journals.length; ++i) {
CheckDatafile(collection, "journal", datafiles.journals[i], issues, details);
}
for (var i = 0; i < datafiles.datafiles.length; ++i) {
CheckDatafile(collection, "datafile", datafiles.datafiles[i], issues, details);
}
for (var i = 0; i < datafiles.compactors.length; ++i) {
CheckDatafile(collection, "compactor", datafiles.compactors[i], issues, details);
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief select and check a collection
////////////////////////////////////////////////////////////////////////////////
function main (argv) {
var databases = internal.db._databases();
var i;
var collectionSorter = function (l, r) {
var lName = l.name().toLowerCase();
var rName = r.name().toLowerCase();
if (lName !== rName) {
return lName < rName ? -1 : 1;
}
return 0;
};
printf("%s\n", " ___ _ __ _ _ ___ ___ ___ ");
printf("%s\n", " / \\__ _| |_ __ _ / _(_) | ___ / \\/ __\\ / _ \\");
printf("%s\n", " / /\\ / _` | __/ _` | |_| | |/ _ \\ / /\\ /__\\// / /_\\/");
printf("%s\n", " / /_// (_| | || (_| | _| | | __/ / /_// \\/ \\/ /_\\\\ ");
printf("%s\n", "/___,' \\__,_|\\__\\__,_|_| |_|_|\\___| /___,'\\_____/\\____/ ");
printf("\n");
var pad = function (s, l) {
if (s.length < l) {
s += Array(l - s.length).join(" ");
}
return s;
};
if (databases.length == 0) {
printf("No databases available. Exiting\n");
return;
}
databases.sort();
printf("Available databases:\n");
for (i = 0; i < databases.length; ++i) {
printf(" %d: %s\n", i, pad(databases[i], 4));
}
var line;
printf("Database to check: ");
while (true) {
line = console.getline();
if (line == "") {
printf("Exiting. Please wait.\n");
return;
}
else {
var l = parseInt(line);
if (l < 0 || l >= databases.length || l === null || l === undefined || isNaN(l)) {
printf("Please select a number between 0 and %d: ", databases.length - 1);
}
else {
internal.db._useDatabase(databases[l]);
break;
}
}
}
printf("\n");
var collections = internal.db._collections();
if (collections.length == 0) {
printf("No collections available. Exiting\n");
return;
}
// sort the collections
collections.sort(collectionSorter);
printf("Available collections:\n");
for (i = 0; i < collections.length; ++i) {
printf(" %d: %s (%s)\n", pad(i, 4), pad(collections[i].name(), 40), collections[i]._id);
}
printf(" *: all\n");
printf("\n");
printf("Collection to check: ");
var a = [];
while (true) {
line = console.getline();
if (line == "") {
printf("Exiting. Please wait.\n");
return;
}
if (line === "*") {
for (i = 0; i < collections.length; ++i) {
a.push(i);
}
break;
}
else {
var l = parseInt(line);
if (l < 0 || l >= collections.length || l === null || l === undefined || isNaN(l)) {
printf("Please select a number between 0 and %d: ", collections.length - 1);
}
else {
a.push(l);
break;
}
}
}
printf("\n");
printf("Prints details (Y/N/full)? ");
var details = false;
while (true) {
line = console.getline();
if (line === "") {
printf("Exiting. Please wait.\n");
return;
}
line = line.toUpperCase();
if (line === "Y" || line === "YES") {
details = true;
}
else if (line === "F" || line === "FULL") {
details = "FULL";
}
break;
}
var issues = [ ];
for (i = 0; i < a.length; ++i) {
var collection = collections[a[i]];
printf("Checking collection #%d: %s\n", a[i], collection.name());
printf("-------------------------------------------------------------------\n");
UnloadCollection(collection);
printf("\n");
CheckCollection(collection, issues, details);
}
if (issues.length > 0) {
// report issues
printf("\n%d issue(s) found:\n------------------------------------------\n", issues.length);
for (i = 0; i < issues.length; ++i) {
var issue = issues[i];
printf(" issue #%d\n collection: %s\n path: %s\n type: %s\n",
i,
issue.collection,
issue.path,
String(issue.type));
printf("%s", issue.color);
printf(" message: %s", issue.message);
printf("%s", internal.COLORS.COLOR_RESET);
printf("\n\n");
}
}
else {
printf("\nNo issues found.\n");
}
}
| {
"content_hash": "2fe4e3bd051de76268f2e8b3b8797b4a",
"timestamp": "",
"source": "github",
"line_count": 642,
"max_line_length": 133,
"avg_line_length": 27.0202492211838,
"alnum_prop": 0.5113276070790338,
"repo_name": "m0ppers/arangodb",
"id": "878cff86fefe6ac59b31e32a7fe003c7ec0e06ba",
"size": "18473",
"binary": false,
"copies": "2",
"ref": "refs/heads/devel",
"path": "js/server/arango-dfdb.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ada",
"bytes": "89080"
},
{
"name": "Assembly",
"bytes": "397438"
},
{
"name": "Batchfile",
"bytes": "36479"
},
{
"name": "C",
"bytes": "4981599"
},
{
"name": "C#",
"bytes": "96430"
},
{
"name": "C++",
"bytes": "273207213"
},
{
"name": "CLIPS",
"bytes": "5291"
},
{
"name": "CMake",
"bytes": "526333"
},
{
"name": "CSS",
"bytes": "634304"
},
{
"name": "Cuda",
"bytes": "52444"
},
{
"name": "DIGITAL Command Language",
"bytes": "33549"
},
{
"name": "Emacs Lisp",
"bytes": "14357"
},
{
"name": "Fortran",
"bytes": "1856"
},
{
"name": "Groff",
"bytes": "272212"
},
{
"name": "Groovy",
"bytes": "131"
},
{
"name": "HTML",
"bytes": "3470113"
},
{
"name": "IDL",
"bytes": "14"
},
{
"name": "Java",
"bytes": "2325801"
},
{
"name": "JavaScript",
"bytes": "66968092"
},
{
"name": "LLVM",
"bytes": "38070"
},
{
"name": "Lex",
"bytes": "1231"
},
{
"name": "Lua",
"bytes": "16189"
},
{
"name": "M4",
"bytes": "64965"
},
{
"name": "Makefile",
"bytes": "1268118"
},
{
"name": "Max",
"bytes": "36857"
},
{
"name": "Module Management System",
"bytes": "1545"
},
{
"name": "NSIS",
"bytes": "28404"
},
{
"name": "Objective-C",
"bytes": "30435"
},
{
"name": "Objective-C++",
"bytes": "2503"
},
{
"name": "PHP",
"bytes": "39473"
},
{
"name": "Pascal",
"bytes": "145688"
},
{
"name": "Perl",
"bytes": "205308"
},
{
"name": "Python",
"bytes": "6937381"
},
{
"name": "QML",
"bytes": "593"
},
{
"name": "QMake",
"bytes": "16692"
},
{
"name": "R",
"bytes": "5123"
},
{
"name": "Rebol",
"bytes": "354"
},
{
"name": "Ruby",
"bytes": "910409"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "Scheme",
"bytes": "10604"
},
{
"name": "Shell",
"bytes": "986221"
},
{
"name": "Swift",
"bytes": "116"
},
{
"name": "Vim script",
"bytes": "4075"
},
{
"name": "XSLT",
"bytes": "473118"
},
{
"name": "Yacc",
"bytes": "72510"
}
],
"symlink_target": ""
} |
namespace clang {
class ASTContext;
}
namespace gtclang {
/// @brief Context of the GTClang tool
/// @ingroup frontend
class GTClangContext : dawn::NonCopyable {
std::unique_ptr<Options> options_;
std::unique_ptr<Diagnostics> diagnostics_;
// Map of attributes for stencil and stencil-functions
std::unordered_map<std::string, dawn::ast::Attr> stencilNameToAttributeMap_;
// Raw points are always non-owning
clang::ASTContext* astContext_;
bool useDawn_;
public:
GTClangContext();
/// @name Get/Set useDawn boolean
/// @{
bool& useDawn();
const bool& useDawn() const;
/// @}
/// @name Get configuration options parsed from command-line
/// @{
Options& getOptions();
const Options& getOptions() const;
/// @}
/// @name Get diagnostics
/// @{
Diagnostics& getDiagnostics();
const Diagnostics& getDiagnostics() const;
void setDiagnostics(clang::DiagnosticsEngine* diags);
bool hasDiagnostics() const;
/// @}
/// @name Get/Set AST context
/// @{
clang::ASTContext& getASTContext();
const clang::ASTContext& getASTContext() const;
void setASTContext(clang::ASTContext* astContext);
/// @}
/// @name Get SourceManager
/// @{
clang::SourceManager& getSourceManager();
const clang::SourceManager& getSourceManager() const;
/// @}
/// @name Get Clang DiagnosticsEngine
/// @{
clang::DiagnosticsEngine& getDiagnosticsEngine();
const clang::DiagnosticsEngine& getDiagnosticsEngine() const;
/// @}
/// @brief Get/Set attribute of stencil and stencil functions
///
/// If attribute was not set for the given stencil or stencil function, the default constructed
/// attribute is returned.
///
/// @see dawn::ast::Attr
/// @{
dawn::ast::Attr getStencilAttribute(const std::string& name) const;
void setStencilAttribute(const std::string& name, dawn::ast::Attr attr);
/// @}
};
} // namespace gtclang
#endif
| {
"content_hash": "f4f716b6061a6c9d634ed466ebf44a18",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 97,
"avg_line_length": 24.792207792207794,
"alnum_prop": 0.6804609743321111,
"repo_name": "MeteoSwiss-APN/dawn",
"id": "2e5dffaa97271c3f2965a12af1852ac9337f9652",
"size": "2910",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gtclang/src/gtclang/Frontend/GTClangContext.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "3780402"
},
{
"name": "CMake",
"bytes": "125177"
},
{
"name": "Cuda",
"bytes": "73606"
},
{
"name": "Dockerfile",
"bytes": "4895"
},
{
"name": "Fortran",
"bytes": "2880"
},
{
"name": "Python",
"bytes": "265722"
},
{
"name": "Shell",
"bytes": "13029"
}
],
"symlink_target": ""
} |
package org.geomajas.hammergwt.client.handler;
import org.geomajas.hammergwt.client.event.NativeHammerEvent;
/**
* @author Dosi Bingov
*/
public interface HammerDragEndHandler {
void onDragEnd(NativeHammerEvent event);
}
| {
"content_hash": "9ec5a9e774975395ad973a8d82af692e",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 61,
"avg_line_length": 19,
"alnum_prop": 0.7894736842105263,
"repo_name": "dosi-bingov/hammergwt",
"id": "a4337cd9ca5ee4e179cd8dbcadf7ed39d21c55da",
"size": "228",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hammer-gwt-impl/src/main/java/org/geomajas/hammergwt/client/handler/HammerDragEndHandler.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "34703"
},
{
"name": "JavaScript",
"bytes": "61955"
}
],
"symlink_target": ""
} |
package mysql_dao
import (
"fmt"
"github.com/golang/glog"
"github.com/jmoiron/sqlx"
"github.com/nebulaim/telegramd/proto/mtproto"
"github.com/nebulaim/telegramd/service/auth_session/biz/dal/dataobject"
)
type AuthOpLogsDAO struct {
db *sqlx.DB
}
func NewAuthOpLogsDAO(db *sqlx.DB) *AuthOpLogsDAO {
return &AuthOpLogsDAO{db}
}
// insert into auth_op_logs(auth_key_id, ip, op_type, log_text) values (:auth_key_id, :ip, :op_type, :log_text)
// TODO(@benqi): sqlmap
func (dao *AuthOpLogsDAO) InsertOrUpdate(do *dataobject.AuthOpLogsDO) int64 {
var query = "insert into auth_op_logs(auth_key_id, ip, op_type, log_text) values (:auth_key_id, :ip, :op_type, :log_text)"
r, err := dao.db.NamedExec(query, do)
if err != nil {
errDesc := fmt.Sprintf("NamedExec in InsertOrUpdate(%v), error: %v", do, err)
glog.Error(errDesc)
panic(mtproto.NewRpcError(int32(mtproto.TLRpcErrorCodes_DBERR), errDesc))
}
id, err := r.LastInsertId()
if err != nil {
errDesc := fmt.Sprintf("LastInsertId in InsertOrUpdate(%v)_error: %v", do, err)
glog.Error(errDesc)
panic(mtproto.NewRpcError(int32(mtproto.TLRpcErrorCodes_DBERR), errDesc))
}
return id
}
| {
"content_hash": "1864abfcd86822761b9dfe3eab5e7bcb",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 123,
"avg_line_length": 29.666666666666668,
"alnum_prop": 0.7104580812445981,
"repo_name": "nebulaim/telegramd",
"id": "8a1e91d2cb0307f87acf40b0a3c2cd9d4ed1b30f",
"size": "1796",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "service/auth_session/biz/dal/dao/mysql_dao/auth_op_logs_dao.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "3708"
},
{
"name": "Go",
"bytes": "4917881"
},
{
"name": "Makefile",
"bytes": "43"
},
{
"name": "Python",
"bytes": "2877"
},
{
"name": "Shell",
"bytes": "7922"
},
{
"name": "Smarty",
"bytes": "67081"
}
],
"symlink_target": ""
} |
/* -*- C++ -*- */
/**
* @file Container_T.h
*
* $Id: Container_T.h 935 2008-12-10 21:47:27Z mitza $
*
* @author Pradeep Gore <pradeep@oomworks.com>
*
*
*/
#ifndef TAO_Notify_CONTAINER_T_H
#define TAO_Notify_CONTAINER_T_H
#include /**/ "ace/pre.h"
#include "orbsvcs/Notify/notify_serv_export.h"
#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */
#include "orbsvcs/ESF/ESF_Proxy_Collection.h"
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
/**
* @class TAO_Notify_Container_T
*
* @brief A template class that manages a collection.
* TYPE = type of collection
*
*/
template <class TYPE>
class TAO_Notify_Serv_Export TAO_Notify_Container_T
{
typedef TAO_ESF_Proxy_Collection<TYPE> COLLECTION;
public:
/// Constructor
TAO_Notify_Container_T (void);
/// Destructor
virtual ~TAO_Notify_Container_T ();
/// Init this object.
void init (void);
/// Insert object to this container.
virtual void insert (TYPE* type);
/// Remove type from container_
virtual void remove (TYPE* type);
/// Shutdown
virtual void shutdown (void);
/// Call destroy on each contained object
virtual void destroy (void);
/// Collection
COLLECTION* collection (void);
protected:
/// The collection data structure that we add objects to.
COLLECTION* collection_;
private:
class Destroyer: public TAO_ESF_Worker<TYPE>
{
/// Call destroy on the object
virtual void work (TYPE* type);
};
};
TAO_END_VERSIONED_NAMESPACE_DECL
#if defined (__ACE_INLINE__)
#include "orbsvcs/Notify/Container_T.inl"
#endif /* __ACE_INLINE__ */
#if defined (ACE_TEMPLATES_REQUIRE_SOURCE)
#include "orbsvcs/Notify/Container_T.cpp"
#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */
#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA)
#pragma implementation ("Container_T.cpp")
#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */
#include /**/ "ace/post.h"
#endif /* TAO_Notify_CONTAINER_T_H */
| {
"content_hash": "17f6f8b845a18f0224f70e02f5de6fbd",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 59,
"avg_line_length": 20.858695652173914,
"alnum_prop": 0.6836894215737364,
"repo_name": "binary42/OCI",
"id": "58d6f4d5f71288c907a18e859aca8f3b69b4202c",
"size": "1919",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "orbsvcs/Notify/Container_T.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "176672"
},
{
"name": "C++",
"bytes": "28193015"
},
{
"name": "HTML",
"bytes": "19914"
},
{
"name": "IDL",
"bytes": "89802"
},
{
"name": "LLVM",
"bytes": "4067"
},
{
"name": "Lex",
"bytes": "6305"
},
{
"name": "Makefile",
"bytes": "509509"
},
{
"name": "Yacc",
"bytes": "18367"
}
],
"symlink_target": ""
} |
import numpy
import matplotlib
import pylab
from numba import autojit
@autojit
def iterMandel(x, y, iterMax):
"""
Dadas las partes real e imaginaria de un numero complejo,
determina la iteracion en la cual el candidato al conjunto
de Mandelbrot se escapa.
"""
c = complex(x, y)
z = 0.0j
for i in range(iterMax):
z = z**2 + c
if abs(z) >= 2:
return i
return iterMax
@autojit
def crearFractal(minX, maxX, minY, maxY, imagen, iteraciones):
"""
Dada la region de la grafica que se quiere obtener, y el
tamano de la imagen, determina el valor numerico de cada
pixel en la grafica y determina si es parte o no del conjunto
de Mandelbrot.
"""
altura = imagen.shape[0]
ancho = imagen.shape[1]
pixelX = (maxX - minX) / ancho
pixelY = (maxY - minY) / altura
for x in range(ancho):
real = minX + x*pixelX
for y in range(altura):
imag = minY + y*pixelY
color = iterMandel(real, imag, iteraciones)
imagen[y, x] = color
imagen = numpy.zeros((800, 2000), dtype = numpy.uint8)
crearFractal(-2.0, 0.0, -0.4, 0.4, imagen, 40)
ax = pylab.imshow(imagen, cmap="Greys")
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
ax.axes.spines["right"].set_color("none")
ax.axes.spines["left"].set_color("none")
ax.axes.spines["top"].set_color("none")
ax.axes.spines["bottom"].set_color("none")
fig = pylab.gcf()
fig.savefig("mandel1.png", dpi=300, pad_inches=0.0, bbox_inches='tight', figsize=(20,8)) | {
"content_hash": "3d76cf5c1e168b80e2d04de324f3d4f4",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 88,
"avg_line_length": 27.736842105263158,
"alnum_prop": 0.6306135357368754,
"repo_name": "robblack007/mandelbrot-sets",
"id": "4f573ce2c8275f24e89363de115feffd9addd618",
"size": "1581",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mandel1.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "13185"
}
],
"symlink_target": ""
} |
This is a [Sponge](http://spongepowered.com) plugin to integrate [Minecraft](https://minecraft.net) server with a [Discord](https://discordapp.com) channel.
## Features
- Player's chat messages in Minecraft are sent to specified Discord channels, and chat messages in specific Discord channels are also sent to online players in Minecraft.
- Admins and mods can log in to their own Discord account, so that chat messages show under their names in Discord.
- Emoji is converted between Minecraft and Discord format. Details are showed in [EMOJI.md](EMOJI.md).
- Clickable URL.
- Multiple channels with custom configuration for each channel. E.g.:
- 1 public channel to send & receive messages between Discord and Minecraft
- 1 monitoring channel to record only server start/stop and player join/leave events
- 1 staff-only channel that send message one-way from Discord to Minecraft with a special announcement template
- Set game activity of the bot
- Ignore Discord messages from all bots and/or blacklist certain prefixes
- Support One-Time Password
- **New in 2.3.0**
- Mentions in Discord show properly in Minecraft with configurable templates
- Mentions from Minecraft are supported with permission control (check **Additional Permissions**)
- Attachments in Discord shows proper links in Minecraft
- Support Minecraft templates based on Discord roles
## Getting Started for server owners and players
[GETTING STARTED.md](GETTING STARTED.md)
## Migrating from 1.x.x or 2.0.0
[MIGRATE.md](MIGRATE.md)
## Build your own .jar
1. Clone this repository
1. Run `gradlew`
1. The jar file will be in `build/libs/DiscordBridge-{version}-all.jar`.
## Commands
- `/discord login`: login to Discord and bind the Discord account to the Minecraft account for automatic login in the future. The email and password will not be stored; instead, the access token of the user will be stored in the config folder on the server.
- `/discord otp`: One-time password for Discord login _(thanks Prototik)_.
- `/discord logout`: logout of Discord and unbind the Discord account from the Minecraft account.
- `/discord broadcast`: as this plugin cannot capture server's `/say` at the moment, this command is to send a message to all online players and Discord. This command requires having the default account set up.
- `/discord status`: show current connection status.
- `/discord reload`: reload configurations.
- `/discord reconnect`: reconnect Discord connection.
A short summary is below:
| Command | Shorthand | Permission |
|---------|-----------|------------|
| `/discord login` | `/d l` | `discordbridge.login` |
| `/discord otp` | `/d otp` | `discordbridge.login` |
| `/discord logout` | `/d lo` | `discordbridge.login` |
| `/discord broadcast <message>` | `/d b <message>` | `discordbridge.broadcast` |
| `/discord status` | `/d s` | `discordbridge.status` |
| `/discord reload` | `/d reload` | `discordbridge.reload` |
| `/discord reconnect` | `/d reconnect` | `discordbridge.reconnect` |
Some ideas for future commands
| Command | Note |
|---------|------|
| `/discord config` | Show current configuration |
| `/discord status` | Show current Discord account |
## Configurations
Configuration is stored in `config.json` file.
- Global config
- `botToken`: App Bot User's token
- `botDiscordGame`: sets the current game activity of the bot in Discord _(thanks, Vankka)_
- `tokenStore`: `JSON` (default) or `NONE` (user authentication will be disabled) or `InMemory` (mainly for testing). This is used for player authentication.
- `minecraftBroadcastTemplate`: template for messages in Minecraft from `/discord broadcast` command
- `prefixBlacklist`: a list of prefix string (e.g. `["!"]`) that will be ignored by the plugin _(thanks, Vankka)_
- `ignoreBots`: ignore all messages from any Discord Bots _(thanks, Vankka)_
- `channels`: a list of channel configurations
- Channel config
- `discordId`: the ID of the Discord channel (usually a 18-digit number)
- `discord`: templates in Discord
- `joinedTemplate`: (optional) template for a message in Discord when a player joins the server
- `leftTemplate`: (optional) template for a message in Discord when a player leaves the server
- `anonymousChatTemplate`: (optional) template for messages from Minecraft to Discord for unauthenticated user
- `authenticatedChatTemplate`: (optional) template for messages from Minecraft to Discord for authenticated user
- `broadcastTemplate`: (optional) template for messages in Discord from `/discord broadcast` command
- `deathTemplate`: (optional) template for a message in Discord when a player dies _(thanks, Mohron)_
- `minecraft`: templates in Minecraft
- `chatTemplate`: (optional) template for messages from Discord to Minecraft. For supporting placeholders in the template, check the section **Chat placeholder**
- `attachment`: _(thanks, Mohron)_
- `template`: template for Discord attachments linked in Minecraft
- `hoverTemplate`: template for the message shown when you hover over an attachment link
- `allowLink`: adds a clickable link in game for attachments sent via discord
- `emoji`: _(thanks, Mohron)_
- `template`: template for custom emoji viewed in Minecraft - accepts `%n`
- `hoverTemplate`: template for the message shown when you hover over an emoji
- `allowLink`: adds a clickable link in game to view the emoji image
- `mention`: _(thanks, Mohron)_
- `userTemplate`: template for @user mentions - accepts `%s`/`%u`
- `roleTemplate`: template for @role mentions - accepts `%s`
- `everyoneTemplate`: template for @here & @everyone mentions - accepts `%s`
- `channelTemplate`: template for @here & @everyone mentions - accepts `%s`
- `roles`: `minecraft` configurations that are for a specific Discord role
You can find some example configurations in `examples` folders.
### Chat Placeholders
- `%s` - the message sent via discord
- `%a` - the nickname of the message author or username if nickname is unavailable
- `%u` - the username of the author. This is used if you want to disallow Discord nickname.
- `%r` - the name of the highest Discord role held by the message author. Color of the role will also be translated into Minecraft color automatically.
- `%g` - the current game of the message author
- `%n` - the name of of custom emoji
### Additional Permissions
*NOTE: The below permissions are applicable only to unathenticated users. Authenticated users chat under their own Discord accounts, so you can restrict using Text permission of Discord roles.*
| Permission | Use |
|---------|-----------|
| `discordbridge.mention.name` <br> `discordbridge.mention.name.<name>` | Allows `@username`/`@nickname` mentions to be sent from Minecraft |
| `discordbridge.mention.role` <br> `discordbridge.mention.role.<role>` | Allows `@role` mentions - the role must have "Allow anyone to @mention" set |
| `discordbridge.mention.channel` <br> `discordbridge.mention.channel.<channel>` | Allows `#channel` mention |
| `discordbridge.mention.here` | Allows the `@here` mention<sup>1</sup> |
| `discordbridge.mention.everyone` | Allows the `@everyone` mention<sup>1</sup> |
> <sup>1</sup> The bot must have permission to "Mention Everyone" in order to use `@here` & `@everyone`.
## Frequently Asked Questions
### How to get channel ID
1. Open `User Settings` in Discord, then open `Appearance` section and tick `Developer Mode`
1. Right click any channel and click `Copy ID`
## CHANGELOG
[CHANGELOG.md](CHANGELOG.md)
## TODO
* 2.4.0
- [ ] New config to allow executing Minecraft command from Discord
* Future
- [ ] MySQL token store
- [ ] Group-based prefix
- [ ] Handle custom Sponge channels (e.g. MCClan and staff chat of Nucleus)
- [ ] A command to check Bot connection status
- [ ] New config to route Minecraft server log to Discord
| {
"content_hash": "63ca17a557f7bb25a3b3bc8bd45bcdb5",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 257,
"avg_line_length": 54.205479452054796,
"alnum_prop": 0.7265605256507455,
"repo_name": "nguyenquyhy/Sponge-Discord",
"id": "f75f43fadd8c767f56db0197036806826cb89e94",
"size": "7931",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "73724"
}
],
"symlink_target": ""
} |
package sorcer.core.dispatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sorcer.core.context.model.ent.ProcModel;
import sorcer.core.exertion.Mograms;
import sorcer.core.provider.Provider;
import sorcer.service.*;
import sorcer.service.modeling.Model;
import java.rmi.RemoteException;
import java.util.List;
import java.util.Set;
import static sorcer.service.Exec.*;
public class CatalogSequentialDispatcher extends CatalogExertDispatcher {
private final Logger logger = LoggerFactory.getLogger(CatalogSequentialDispatcher.class);
@SuppressWarnings("rawtypes")
public CatalogSequentialDispatcher(Exertion job,
Set<Context> sharedContext,
boolean isSpawned,
Provider provider,
ProvisionManager provisionManager) {
super(job, sharedContext, isSpawned, provider, provisionManager);
}
protected void doExec(Arg... args) throws MogramException, SignatureException {
String pn;
if (inputXrts == null) {
xrt.setStatus(FAILED);
state = FAILED;
try {
pn = provider.getProviderName();
if (pn == null)
pn = provider.getClass().getName();
ExertionException fe = new ExertionException(pn + " received invalid job: "
+ xrt.getName(), xrt);
xrt.reportException(fe);
dispatchers.remove(xrt.getId());
throw fe;
} catch (RemoteException e) {
logger.warn("Error during local call", e);
}
}
xrt.startExecTime();
Context previous = null;
for (Mogram mogram: inputXrts) {
if (xrt.isBlock()) {
try {
if (mogram.getScope() != null)
mogram.getScope().append(xrt.getContext());
else {
mogram.setScope(xrt.getContext());
}
} catch (Exception ce) {
throw new MogramException(ce);
}
}
try {
if (mogram instanceof Exertion) {
ServiceExertion se = (ServiceExertion) mogram;
// support for continuous pre and post execution of task
// signatures
if (previous != null && se.isTask() && ((Task) se).isContinous())
se.setContext(previous);
dispatchExertion(se, args);
previous = se.getContext();
} else if (mogram instanceof ProcModel) {
((ProcModel)mogram).updateEntries(xrt.getContext());
xrt.getDataContext().append((Context) ((Model) mogram).getResponse());
}
} catch (Exception e) {
e.printStackTrace();
throw new ExertionException(e);
}
}
if (masterXrt != null) {
masterXrt = (ServiceExertion) execExertion(masterXrt, args); // executeMasterExertion();
if (masterXrt.getStatus() <= FAILED) {
state = FAILED;
xrt.setStatus(FAILED);
} else {
state = DONE;
xrt.setStatus(DONE);
}
} else
state = DONE;
dispatchers.remove(xrt.getId());
xrt.stopExecTime();
xrt.setStatus(DONE);
}
protected void dispatchExertion(ServiceExertion se, Arg... args) throws SignatureException, ExertionException {
se = (ServiceExertion) execExertion(se, args);
if (se.getStatus() <= FAILED) {
xrt.setStatus(FAILED);
state = FAILED;
try {
String pn = provider.getProviderName();
if (pn == null)
pn = provider.getClass().getName();
ExertionException fe = new ExertionException(pn
+ " received failed task: " + se.getName(), se);
xrt.reportException(fe);
dispatchers.remove(xrt.getId());
throw fe;
} catch (RemoteException e) {
logger.warn("Exception during local call");
}
} else if (se.getStatus() == SUSPENDED
|| xrt.getControlContext().isReview(se)) {
xrt.setStatus(SUSPENDED);
ExertionException ex = new ExertionException(
"exertion suspended", se);
se.reportException(ex);
dispatchers.remove(xrt.getId());
throw ex;
}
}
protected List<Mogram> getInputExertions() throws ContextException {
return Mograms.getInputExertions(((Job) xrt));
}
}
| {
"content_hash": "48a0b311a53eb34308cca27a86995ebe",
"timestamp": "",
"source": "github",
"line_count": 134,
"max_line_length": 115,
"avg_line_length": 36.656716417910445,
"alnum_prop": 0.5228013029315961,
"repo_name": "mwsobol/SORCER",
"id": "aa781906e7c164dbc8fbd33af726855d29a6b6c8",
"size": "5563",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/sorcer-platform/src/main/java/sorcer/core/dispatch/CatalogSequentialDispatcher.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "6625"
},
{
"name": "CSS",
"bytes": "2145"
},
{
"name": "Groovy",
"bytes": "109160"
},
{
"name": "HTML",
"bytes": "35236"
},
{
"name": "Java",
"bytes": "4503087"
},
{
"name": "NSIS",
"bytes": "138"
},
{
"name": "Shell",
"bytes": "42234"
}
],
"symlink_target": ""
} |
namespace SelfLoad.DataAccess.ERCLevel
{
public partial class D11_City_ReChildDto
{
}
}
| {
"content_hash": "491c67fdfde44dc8fb5079ecdd4f7467",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 44,
"avg_line_length": 17.666666666666668,
"alnum_prop": 0.660377358490566,
"repo_name": "CslaGenFork/CslaGenFork",
"id": "fcc04bc5eb6c1a83f1af9f8ec81dfe5aeafd6fd4",
"size": "106",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "trunk/Samples/DeepLoad/DAL-DTO/SelfLoad.DataAccess/ERCLevel/D11_City_ReChildDto.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "4816094"
},
{
"name": "Assembly",
"bytes": "73066"
},
{
"name": "C#",
"bytes": "12314305"
},
{
"name": "C++",
"bytes": "313681"
},
{
"name": "HTML",
"bytes": "30950"
},
{
"name": "PHP",
"bytes": "35716"
},
{
"name": "PLpgSQL",
"bytes": "2164471"
},
{
"name": "Pascal",
"bytes": "1244"
},
{
"name": "PowerShell",
"bytes": "1687"
},
{
"name": "SourcePawn",
"bytes": "500196"
},
{
"name": "Visual Basic",
"bytes": "3027224"
}
],
"symlink_target": ""
} |
@CHARSET "UTF-8";
a {
color: lime;
}
.w952 {
width: 952px;
margin: 0 auto;
border: 1px dotted blue;
}
p {
width: 600px
}
.go-topbtn {
background: url("/user/images/vipsite/backtop.gif")
no-repeat transparent;
bottom: 20px;
_top: expression(documentElement.scrollTop + documentElement.clientHeight-76);
cursor: pointer;
height: 56px;
position: fixed;
_position: absolute;
width: 16px;
} | {
"content_hash": "49d0493b06d971ec67c0215008e0e415",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 79,
"avg_line_length": 14.962962962962964,
"alnum_prop": 0.693069306930693,
"repo_name": "baowp/platform",
"id": "6c56110de314ed8f27898e927387d6798aeb6cf9",
"size": "404",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bundle/src/main/webapp/sample/html/jq/test.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ActionScript",
"bytes": "313319"
},
{
"name": "CSS",
"bytes": "1567456"
},
{
"name": "Groovy",
"bytes": "16703"
},
{
"name": "Java",
"bytes": "2369547"
},
{
"name": "JavaScript",
"bytes": "5755060"
},
{
"name": "PHP",
"bytes": "65173"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "926db344cad1fcaa8e87b247f7c57735",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "db8ffc52af253176da83b4e67bccfbac81b2a03b",
"size": "196",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Arecales/Arecaceae/Geonoma/Geonoma macrostachys/Geonoma macrostachys macrostachys/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
class AddFeatureFilterTypeToUserPreferences < ActiveRecord::Migration[6.0]
DOWNTIME = false
def change
add_column :user_preferences, :feature_filter_type, :bigint
end
end
| {
"content_hash": "8a4e6e57e68164121f205b93a83801ce",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 74,
"avg_line_length": 26,
"alnum_prop": 0.7692307692307693,
"repo_name": "mmkassem/gitlabhq",
"id": "c05b624c43825b6f0d341911d350c6e82a6f8829",
"size": "213",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "db/migrate/20200209131152_add_feature_filter_type_to_user_preferences.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "113683"
},
{
"name": "CoffeeScript",
"bytes": "139197"
},
{
"name": "Cucumber",
"bytes": "119759"
},
{
"name": "HTML",
"bytes": "447030"
},
{
"name": "JavaScript",
"bytes": "29805"
},
{
"name": "Ruby",
"bytes": "2417833"
},
{
"name": "Shell",
"bytes": "14336"
}
],
"symlink_target": ""
} |
@extends('layout')
@section('title', 'New post')
@section('content')
<h1>Create new post</h1>
<br>
@if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
@if (session()->has('flash_notification.message'))
<div class="alert alert-{{ session('flash_notification.level') }}">
<button type="button" class="close" data-dismiss="alert" aria-hidded="true">×</button>
{!! session('flash_notification.message') !!}
</div>
@endif
<form action="/posts" method="POST">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Title:</label>
<input type='text' name='title' id='title' class='form-control' value="{{ old('title') }}">
</div>
<div class="form-group">
<label for="content">Content:</label>
<textarea type='text' name='content' id='content' class='form-control has_editor' rows=10>{{ old('content') }}</textarea>
</div>
<hr>
<div class="form-group">
<button type='submit' name='submit' id='submit' class='btn btn-primary' value='Submit'>Create post</button>
</div>
</form>
@include('partials.editor')
@stop
| {
"content_hash": "88179919f604efc244f398632b5781ef",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 125,
"avg_line_length": 29.94871794871795,
"alnum_prop": 0.6361301369863014,
"repo_name": "saleone/obscuris",
"id": "08809f1c05c0f429bbb1087d6a4e5494164fd4ec",
"size": "1168",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "resources/views/posts/create.blade.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "553"
},
{
"name": "CSS",
"bytes": "4653"
},
{
"name": "HTML",
"bytes": "14643"
},
{
"name": "JavaScript",
"bytes": "747"
},
{
"name": "PHP",
"bytes": "76334"
}
],
"symlink_target": ""
} |
@implementation P2MSWindowView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor clearColor];
}
return self;
}
- (void)setTextImage:(UIImage *)image{
_textImage=nil;
_textImage = image;
[self setNeedsDisplay];
}
@end
@implementation P2MSMagnifyView
- (id)init {
return [super initWithFrame:CGRectMake(0.0f, 0.0f, 145.0f, 59.0f)];
}
- (void)drawRect:(CGRect)rect {
[[UIImage imageNamed:@"magnifier"] drawInRect:rect];
if (self.textImage) {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextClipToMask(context, rect, [UIImage imageNamed:@"magnifier-mask"].CGImage);
[self.textImage drawInRect:rect];
CGContextRestoreGState(context);
}
}
@end
@implementation P2MSLoupeView
- (id)init {
return [super initWithFrame:CGRectMake(0.0f, 0.0f, 127.0f, 127.0f)];
}
- (void)drawRect:(CGRect)rect {
[[UIImage imageNamed:@"loupe"] drawInRect:rect];
if (self.textImage) {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextClipToMask(context, rect, [UIImage imageNamed:@"loupe-mask"].CGImage);
[self.textImage drawInRect:rect];
CGContextRestoreGState(context);
}
}
@end | {
"content_hash": "03b0e2c15fc47b52d0e11744e4fc0219",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 91,
"avg_line_length": 22.442622950819672,
"alnum_prop": 0.6705624543462382,
"repo_name": "ptwoms/P2MSTextView",
"id": "4da0d59ab80d372a0783b8d60afeb17bb15b42e0",
"size": "1557",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "classes/P2MSWindowView.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "2288"
},
{
"name": "Objective-C",
"bytes": "219733"
}
],
"symlink_target": ""
} |
Migrate Orientdb schema.
Uses a `schema_versions` class to keep track of migrations.
## Installation
Add this line to your application's Gemfile:
gem 'orientdb-schema-migrator'
And then execute:
$ bundle
Or install it yourself as:
$ gem install orientdb-schema-migrator
## Usage
### Create Migration
`rake odb:generate_migration migration_name=CreateFoos`
### Migrate
`rake odb:migrate`
### Rollback
Rollback (one migration at a time).
`rake odb:rollback`
## Testing
1. Install OrientDb and run it locally.
2. Create a database named `schema_test` with an admin user named `test`, password `test` (or provide your own credentials via environment variables).
You can test that this is correctly setup with `rake odb:test_connection`.
3. `ODB_TEST=true bundle exec rake odb:add_schema_class`
4. `bundle exec rake spec`
## Contributing
1. Fork it ( https://github.com/Headlinerfm/orientdb-schema-migrator/fork )
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 a new Pull Request
| {
"content_hash": "728b74c860d1eed0d9a8837c89e42601",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 150,
"avg_line_length": 23.53061224489796,
"alnum_prop": 0.7389418907198613,
"repo_name": "ashramsey/orientdb-schema-migrator",
"id": "92b80225ca2bde76fd694fc6c0d4f4f2d5c3200e",
"size": "1179",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "41012"
}
],
"symlink_target": ""
} |
/* The DNA strand is missing the pairing element. Take each character, get its pair, and return the results as a 2d array.
Base pairs are a pair of AT and CG. Match the missing element to the provided character.
Return the provided character as the first element in each array.
For example, for the input GCG, return [["G", "C"], ["C","G"],["G", "C"]]
The character and its pair are paired up in an array, and all the arrays are grouped into one encapsulating array. */
function pairElement(str) {
let chars;
let arrayToFill = [];
for(i = 0; i < str.length; i++) {
chars = str[i].split();
switch(chars[0]) {
case "G":
chars.push("C");
arrayToFill.push(chars);
break;
case "C":
chars.push("G");
arrayToFill.push(chars);
break;
case "A":
chars.push("T");
arrayToFill.push(chars);
break;
case "T":
chars.push("A");
arrayToFill.push(chars);
break;
}
}
str = arrayToFill;
return str;
}
pairElement("GCG");
| {
"content_hash": "e1f847c9a40f37b99c1591a50b33b513",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 122,
"avg_line_length": 21.16,
"alnum_prop": 0.5945179584120983,
"repo_name": "davidteoran/freecodecamp-projects",
"id": "70f5ace72b0cb2583dd70c668979e3789edd3e15",
"size": "1058",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "intermediate-algorithm-scripting/DNA_pairing.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10661"
},
{
"name": "HTML",
"bytes": "27709"
},
{
"name": "JavaScript",
"bytes": "59585"
}
],
"symlink_target": ""
} |
namespace tod
{
wxColour TodEditorInspector::s_backgroundColor1 = wxColour(39, 40, 34);
wxColour TodEditorInspector::s_backgroundColor2 = wxColour(60, 60, 60);
wxColour TodEditorInspector::s_textColor1 = wxColour(207, 207, 193);
wxColour TodEditorInspector::s_textColor2 = wxColour(92, 93, 80);
wxFont TodEditorInspector::s_font1 = wxFont(9, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_LIGHT, false, "Consolas");
}
| {
"content_hash": "2e29ee7da49ae7143b1d297fd1f40fa9",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 126,
"avg_line_length": 33,
"alnum_prop": 0.7738927738927739,
"repo_name": "vateran/todengine",
"id": "62a64786a829de05aa6597554feace8828c8276d",
"size": "496",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "code/todeditor/todeditorinspector.cc",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2823"
},
{
"name": "C++",
"bytes": "444514"
},
{
"name": "Objective-C",
"bytes": "1564"
}
],
"symlink_target": ""
} |
{% extends "base.html" %}
{% block title %}Client{% endblock %}
{% block head %}
<link href="http://static0.twilio.com/packages/quickstart/client.css"
type="text/css" rel="stylesheet" />
{% if not configuration_error %}
<script type="text/javascript"
src="http://static.twilio.com/libs/twiliojs/1.0/twilio.min.js"></script>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<script type="text/javascript">
Twilio.Device.setup("{{ params['token'] }}");
Twilio.Device.ready(function (device) {
$("#log").text("Ready");
});
Twilio.Device.error(function (error) {
$("#log").text("Error: " + error.message);
});
Twilio.Device.connect(function (conn) {
$("#log").text("Successfully established call");
});
Twilio.Device.disconnect(function (conn) {
$("#log").text("Call ended");
});
Twilio.Device.incoming(function (conn) {
$("#log").text("Incoming connection from " + conn.parameters.From);
// accept the incoming connection and start two-way audio
conn.accept();
});
function call() {
// get the phone number to connect the call to
Twilio.Device.connect();
}
function hangup() {
Twilio.Device.disconnectAll();
}
</script>
{% endif %}
{% endblock %}
{% block header %}Nice!{% endblock %}
{% block message %}Try using Twilio Client on your new Twilio app{% endblock %}
{% block content %}
<div id="client-controls">
<button class="call" onclick="call();">
Call
</button>
<button class="hangup" onclick="hangup();">
Hangup
</button>
<div id="log">
{% if configuration_error %}
{{ configuration_error }}
{% else %}
Loading pigeons...
{% endif %}
</div>
</div>
{% endblock %}
| {
"content_hash": "18ebb5aaacd655358418d208489657ca",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 79,
"avg_line_length": 24.34246575342466,
"alnum_prop": 0.622397298818233,
"repo_name": "kwhinnery/jumpstart",
"id": "5a31608be18534d16e81dd48006b6c5113f352ff",
"size": "1777",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "twilio-python/templates/client.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "104"
},
{
"name": "C#",
"bytes": "5774"
},
{
"name": "CSS",
"bytes": "12291"
},
{
"name": "Erlang",
"bytes": "1056"
},
{
"name": "Java",
"bytes": "3437"
},
{
"name": "JavaScript",
"bytes": "11416"
},
{
"name": "PHP",
"bytes": "60322"
},
{
"name": "Perl",
"bytes": "19"
},
{
"name": "Python",
"bytes": "37136"
},
{
"name": "Ruby",
"bytes": "2059"
},
{
"name": "Shell",
"bytes": "317"
}
],
"symlink_target": ""
} |
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import java.io.Serializable;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import javax.annotation.Nullable;
/**
* Implementation of {@code Table} whose row keys and column keys are ordered
* by their natural ordering or by supplied comparators. When constructing a
* {@code TreeBasedTable}, you may provide comparators for the row keys and
* the column keys, or you may use natural ordering for both.
*
* <p>The {@link #rowKeySet} method returns a {@link SortedSet} and the {@link
* #rowMap} method returns a {@link SortedMap}, instead of the {@link Set} and
* {@link Map} specified by the {@link Table} interface.
*
* <p>The views returned by {@link #column}, {@link #columnKeySet()}, and {@link
* #columnMap()} have iterators that don't support {@code remove()}. Otherwise,
* all optional operations are supported. Null row keys, columns keys, and
* values are not supported.
*
* <p>Lookups by row key are often faster than lookups by column key, because
* the data is stored in a {@code Map<R, Map<C, V>>}. A method call like {@code
* column(columnKey).get(rowKey)} still runs quickly, since the row key is
* provided. However, {@code column(columnKey).size()} takes longer, since an
* iteration across all row keys occurs.
*
* <p>Because a {@code TreeBasedTable} has unique sorted values for a given
* row, both {@code row(rowKey)} and {@code rowMap().get(rowKey)} are {@link
* SortedMap} instances, instead of the {@link Map} specified in the {@link
* Table} interface.
*
* <p>Note that this implementation is not synchronized. If multiple threads
* access this table concurrently and one of the threads modifies the table, it
* must be synchronized externally.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/NewCollectionTypesExplained#table">
* {@code Table}</a>.
*
* @author Jared Levy
* @author Louis Wasserman
* @since 7.0
*/
@GwtCompatible(serializable = true)
@Beta
public class TreeBasedTable<R, C, V> extends StandardRowSortedTable<R, C, V> {
private final Comparator<? super C> columnComparator;
private static class Factory<C, V>
implements Supplier<TreeMap<C, V>>, Serializable {
final Comparator<? super C> comparator;
Factory(Comparator<? super C> comparator) {
this.comparator = comparator;
}
@Override
public TreeMap<C, V> get() {
return new TreeMap<C, V>(comparator);
}
private static final long serialVersionUID = 0;
}
/**
* Creates an empty {@code TreeBasedTable} that uses the natural orderings
* of both row and column keys.
*
* <p>The method signature specifies {@code R extends Comparable} with a raw
* {@link Comparable}, instead of {@code R extends Comparable<? super R>},
* and the same for {@code C}. That's necessary to support classes defined
* without generics.
*/
public static <R extends Comparable, C extends Comparable, V>
TreeBasedTable<R, C, V> create() {
return new TreeBasedTable<R, C, V>(Ordering.natural(),
Ordering.natural());
}
/**
* Creates an empty {@code TreeBasedTable} that is ordered by the specified
* comparators.
*
* @param rowComparator the comparator that orders the row keys
* @param columnComparator the comparator that orders the column keys
*/
public static <R, C, V> TreeBasedTable<R, C, V> create(
Comparator<? super R> rowComparator,
Comparator<? super C> columnComparator) {
checkNotNull(rowComparator);
checkNotNull(columnComparator);
return new TreeBasedTable<R, C, V>(rowComparator, columnComparator);
}
/**
* Creates a {@code TreeBasedTable} with the same mappings and sort order
* as the specified {@code TreeBasedTable}.
*/
public static <R, C, V> TreeBasedTable<R, C, V> create(
TreeBasedTable<R, C, ? extends V> table) {
TreeBasedTable<R, C, V> result
= new TreeBasedTable<R, C, V>(
table.rowComparator(), table.columnComparator());
result.putAll(table);
return result;
}
TreeBasedTable(Comparator<? super R> rowComparator,
Comparator<? super C> columnComparator) {
super(new TreeMap<R, Map<C, V>>(rowComparator),
new Factory<C, V>(columnComparator));
this.columnComparator = columnComparator;
}
// TODO(jlevy): Move to StandardRowSortedTable?
/**
* Returns the comparator that orders the rows. With natural ordering,
* {@link Ordering#natural()} is returned.
*/
public Comparator<? super R> rowComparator() {
return rowKeySet().comparator();
}
/**
* Returns the comparator that orders the columns. With natural ordering,
* {@link Ordering#natural()} is returned.
*/
public Comparator<? super C> columnComparator() {
return columnComparator;
}
// TODO(user): make column return a SortedMap
/**
* {@inheritDoc}
*
* <p>Because a {@code TreeBasedTable} has unique sorted values for a given
* row, this method returns a {@link SortedMap}, instead of the {@link Map}
* specified in the {@link Table} interface.
* @since 10.0
* (<a href="https://github.com/google/guava/wiki/Compatibility"
* >mostly source-compatible</a> since 7.0)
*/
@Override
public SortedMap<C, V> row(R rowKey) {
return new TreeRow(rowKey);
}
private class TreeRow extends Row implements SortedMap<C, V> {
@Nullable final C lowerBound;
@Nullable final C upperBound;
TreeRow(R rowKey) {
this(rowKey, null, null);
}
TreeRow(R rowKey, @Nullable C lowerBound, @Nullable C upperBound) {
super(rowKey);
this.lowerBound = lowerBound;
this.upperBound = upperBound;
checkArgument(lowerBound == null || upperBound == null
|| compare(lowerBound, upperBound) <= 0);
}
@Override public SortedSet<C> keySet() {
return new Maps.SortedKeySet<C, V>(this);
}
@Override public Comparator<? super C> comparator() {
return columnComparator();
}
int compare(Object a, Object b) {
// pretend we can compare anything
@SuppressWarnings({"rawtypes", "unchecked"})
Comparator<Object> cmp = (Comparator) comparator();
return cmp.compare(a, b);
}
boolean rangeContains(@Nullable Object o) {
return o != null && (lowerBound == null || compare(lowerBound, o) <= 0)
&& (upperBound == null || compare(upperBound, o) > 0);
}
@Override public SortedMap<C, V> subMap(C fromKey, C toKey) {
checkArgument(rangeContains(checkNotNull(fromKey))
&& rangeContains(checkNotNull(toKey)));
return new TreeRow(rowKey, fromKey, toKey);
}
@Override public SortedMap<C, V> headMap(C toKey) {
checkArgument(rangeContains(checkNotNull(toKey)));
return new TreeRow(rowKey, lowerBound, toKey);
}
@Override public SortedMap<C, V> tailMap(C fromKey) {
checkArgument(rangeContains(checkNotNull(fromKey)));
return new TreeRow(rowKey, fromKey, upperBound);
}
@Override public C firstKey() {
SortedMap<C, V> backing = backingRowMap();
if (backing == null) {
throw new NoSuchElementException();
}
return backingRowMap().firstKey();
}
@Override public C lastKey() {
SortedMap<C, V> backing = backingRowMap();
if (backing == null) {
throw new NoSuchElementException();
}
return backingRowMap().lastKey();
}
transient SortedMap<C, V> wholeRow;
/*
* If the row was previously empty, we check if there's a new row here every
* time we're queried.
*/
SortedMap<C, V> wholeRow() {
if (wholeRow == null
|| (wholeRow.isEmpty() && backingMap.containsKey(rowKey))) {
wholeRow = (SortedMap<C, V>) backingMap.get(rowKey);
}
return wholeRow;
}
@Override
SortedMap<C, V> backingRowMap() {
return (SortedMap<C, V>) super.backingRowMap();
}
@Override
SortedMap<C, V> computeBackingRowMap() {
SortedMap<C, V> map = wholeRow();
if (map != null) {
if (lowerBound != null) {
map = map.tailMap(lowerBound);
}
if (upperBound != null) {
map = map.headMap(upperBound);
}
return map;
}
return null;
}
@Override
void maintainEmptyInvariant() {
if (wholeRow() != null && wholeRow.isEmpty()) {
backingMap.remove(rowKey);
wholeRow = null;
backingRowMap = null;
}
}
@Override public boolean containsKey(Object key) {
return rangeContains(key) && super.containsKey(key);
}
@Override public V put(C key, V value) {
checkArgument(rangeContains(checkNotNull(key)));
return super.put(key, value);
}
}
// rowKeySet() and rowMap() are defined here so they appear in the Javadoc.
@Override public SortedSet<R> rowKeySet() {
return super.rowKeySet();
}
@Override public SortedMap<R, Map<C, V>> rowMap() {
return super.rowMap();
}
/**
* Overridden column iterator to return columns values in globally sorted
* order.
*/
@Override
Iterator<C> createColumnKeyIterator() {
final Comparator<? super C> comparator = columnComparator();
final Iterator<C> merged =
Iterators.mergeSorted(Iterables.transform(backingMap.values(),
new Function<Map<C, V>, Iterator<C>>() {
@Override
public Iterator<C> apply(Map<C, V> input) {
return input.keySet().iterator();
}
}), comparator);
return new AbstractIterator<C>() {
C lastValue;
@Override
protected C computeNext() {
while (merged.hasNext()) {
C next = merged.next();
boolean duplicate =
lastValue != null && comparator.compare(next, lastValue) == 0;
// Keep looping till we find a non-duplicate value.
if (!duplicate) {
lastValue = next;
return lastValue;
}
}
lastValue = null; // clear reference to unused data
return endOfData();
}
};
}
private static final long serialVersionUID = 0;
}
| {
"content_hash": "72ce007fee5d6441cd647a18c4131306",
"timestamp": "",
"source": "github",
"line_count": 338,
"max_line_length": 80,
"avg_line_length": 31.600591715976332,
"alnum_prop": 0.6515307555472334,
"repo_name": "cklsoft/guava",
"id": "b6c5e34bf5a9790b05123cd0fba03e7acb6bdde2",
"size": "11281",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "guava/src/com/google/common/collect/TreeBasedTable.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "11478"
},
{
"name": "Java",
"bytes": "13985291"
},
{
"name": "Shell",
"bytes": "1128"
}
],
"symlink_target": ""
} |
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
<id>overlay</id>
<formats>
<format>zip</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<dependencySets>
<!-- apiman-manager -->
<dependencySet>
<outputDirectory>standalone/deployments</outputDirectory>
<includes>
<include>*:apiman-manager-ui-war-wildfly8:war</include>
</includes>
<outputFileNameMapping>apimanui.war</outputFileNameMapping>
<useProjectArtifact>false</useProjectArtifact>
<useProjectAttachments>false</useProjectAttachments>
<useTransitiveDependencies>false</useTransitiveDependencies>
<useTransitiveFiltering>false</useTransitiveFiltering>
<directoryMode>0755</directoryMode>
<fileMode>0755</fileMode>
</dependencySet>
<!-- apiman -->
<dependencySet>
<outputDirectory>standalone/deployments</outputDirectory>
<includes>
<include>*:apiman-manager-api-war-wildfly8:war</include>
</includes>
<outputFileNameMapping>apiman.war</outputFileNameMapping>
<useProjectArtifact>false</useProjectArtifact>
<useProjectAttachments>false</useProjectAttachments>
<useTransitiveDependencies>false</useTransitiveDependencies>
<useTransitiveFiltering>false</useTransitiveFiltering>
<directoryMode>0755</directoryMode>
<fileMode>0755</fileMode>
</dependencySet>
<!-- apiman-gateway-api -->
<dependencySet>
<outputDirectory>standalone/deployments</outputDirectory>
<includes>
<include>*:apiman-gateway-platforms-war-wildfly8-api:war</include>
</includes>
<outputFileNameMapping>apiman-gateway-api.war</outputFileNameMapping>
<useProjectArtifact>false</useProjectArtifact>
<useProjectAttachments>false</useProjectAttachments>
<useTransitiveDependencies>false</useTransitiveDependencies>
<useTransitiveFiltering>false</useTransitiveFiltering>
<directoryMode>0755</directoryMode>
<fileMode>0755</fileMode>
</dependencySet>
<!-- apiman-gateway -->
<dependencySet>
<outputDirectory>standalone/deployments</outputDirectory>
<includes>
<include>*:apiman-gateway-platforms-war-wildfly8-gateway:war</include>
</includes>
<outputFileNameMapping>apiman-gateway.war</outputFileNameMapping>
<useProjectArtifact>false</useProjectArtifact>
<useProjectAttachments>false</useProjectAttachments>
<useTransitiveDependencies>false</useTransitiveDependencies>
<useTransitiveFiltering>false</useTransitiveFiltering>
<directoryMode>0755</directoryMode>
<fileMode>0755</fileMode>
</dependencySet>
<!-- apiman-es -->
<dependencySet>
<outputDirectory>standalone/deployments</outputDirectory>
<includes>
<include>*:apiman-distro-es:war</include>
</includes>
<outputFileNameMapping>apiman-es.war</outputFileNameMapping>
<useProjectArtifact>false</useProjectArtifact>
<useProjectAttachments>false</useProjectAttachments>
<useTransitiveDependencies>false</useTransitiveDependencies>
<useTransitiveFiltering>false</useTransitiveFiltering>
<directoryMode>0755</directoryMode>
<fileMode>0755</fileMode>
</dependencySet>
<!-- Sample data -->
<dependencySet>
<outputDirectory>apiman</outputDirectory>
<includes>
<include>io.apiman:apiman-distro-data:jar</include>
</includes>
<useProjectArtifact>false</useProjectArtifact>
<useProjectAttachments>false</useProjectAttachments>
<useTransitiveDependencies>false</useTransitiveDependencies>
<useTransitiveFiltering>false</useTransitiveFiltering>
<directoryMode>0755</directoryMode>
<fileMode>0755</fileMode>
<unpack>true</unpack>
<unpackOptions>
<excludes>
<exclude>**/META-INF/**</exclude>
<exclude>**/sample-data/**</exclude>
</excludes>
</unpackOptions>
</dependencySet>
<dependencySet>
<outputDirectory>standalone/data</outputDirectory>
<includes>
<include>io.apiman:apiman-distro-data:jar</include>
</includes>
<useProjectArtifact>false</useProjectArtifact>
<useProjectAttachments>false</useProjectAttachments>
<useTransitiveDependencies>false</useTransitiveDependencies>
<useTransitiveFiltering>false</useTransitiveFiltering>
<directoryMode>0755</directoryMode>
<fileMode>0755</fileMode>
<unpack>true</unpack>
<unpackOptions>
<includes>
<include>**/bootstrap/**</include>
</includes>
</unpackOptions>
</dependencySet>
</dependencySets>
<fileSets>
<fileSet>
<directory>src/main/resources/overlay</directory>
<outputDirectory></outputDirectory>
<filtered>false</filtered>
<directoryMode>0755</directoryMode>
<fileMode>0755</fileMode>
</fileSet>
<fileSet>
<directory>target/keycloak/standalone</directory>
<outputDirectory>standalone</outputDirectory>
<filtered>false</filtered>
<directoryMode>0755</directoryMode>
<fileMode>0755</fileMode>
</fileSet>
<fileSet>
<directory>target/keycloak/modules</directory>
<outputDirectory>modules</outputDirectory>
<filtered>false</filtered>
<directoryMode>0755</directoryMode>
<fileMode>0755</fileMode>
<excludes>
<exclude>**/aesh/**</exclude>
</excludes>
</fileSet>
<fileSet>
<directory>target/keycloak/themes</directory>
<outputDirectory>themes</outputDirectory>
<filtered>false</filtered>
<directoryMode>0755</directoryMode>
<fileMode>0755</fileMode>
</fileSet>
</fileSets>
</assembly>
| {
"content_hash": "8f9c314f4976eafca1398ea728a851c5",
"timestamp": "",
"source": "github",
"line_count": 151,
"max_line_length": 140,
"avg_line_length": 39.56953642384106,
"alnum_prop": 0.7010878661087866,
"repo_name": "jcechace/apiman",
"id": "031eaf21e3207177a1f90f4ef35e1387534966d5",
"size": "5975",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "distro/wildfly10/src/main/assembly/overlay.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "58563"
},
{
"name": "HTML",
"bytes": "358504"
},
{
"name": "Java",
"bytes": "3731061"
},
{
"name": "JavaScript",
"bytes": "20095"
},
{
"name": "Shell",
"bytes": "1900"
},
{
"name": "TypeScript",
"bytes": "362947"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
namespace Game
{
public class MainViewModel : INotifyPropertyChanged
{
#region scores
private int _bestscore;
public int BestScore
{
get { return _bestscore; }
set
{
if (_bestscore != value)
{
_bestscore = value; this.RaisePropertyChanged("BestScore");
}
}
}
private int _score;
public int Score
{
get
{
return _score;
}
set
{
if (_score != value)
{
this._score = value;
this.RaisePropertyChanged("Score");
}
}
}
#endregion scores
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
// take a copy to prevent thread issues
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| {
"content_hash": "173c3fc4cc78f062408eb6ca0d0e53ce",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 79,
"avg_line_length": 25,
"alnum_prop": 0.49642857142857144,
"repo_name": "carlhuting/2048",
"id": "c327d887a1f02e8c4ef057aabb84f2cbf603f75d",
"size": "1402",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Game/MainViewModel.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "59818"
}
],
"symlink_target": ""
} |
namespace chromecast {
namespace media {
namespace {
constexpr auto kMaxRateChangeInterval = base::Minutes(5);
} // namespace
RateAdjuster::RateAdjuster(const Config& config,
RateChangeCallback change_clock_rate,
double current_clock_rate)
: config_(config),
change_clock_rate_(std::move(change_clock_rate)),
linear_error_(config_.linear_regression_window.InMicroseconds()),
current_clock_rate_(current_clock_rate) {
DCHECK(change_clock_rate_);
}
RateAdjuster::~RateAdjuster() = default;
void RateAdjuster::Reserve(int count) {
linear_error_.Reserve(count);
}
void RateAdjuster::Reset() {
linear_error_.Reset();
initialized_ = false;
clock_rate_start_timestamp_ = 0;
initial_timestamp_ = 0;
clock_rate_error_base_ = 0.0;
}
void RateAdjuster::AddError(int64_t error, int64_t timestamp) {
if (!initialized_) {
clock_rate_start_timestamp_ = timestamp;
clock_rate_error_base_ = 0.0;
initial_timestamp_ = timestamp;
initialized_ = true;
}
int64_t x = timestamp - initial_timestamp_;
// Error is positive if actions are happening too late.
// We perform |current_clock_rate_| seconds of actions per second of actual
// time. We want to run a linear regression on how the error is changing over
// time, if we ignore the effects of any previous clock rate changes. To do
// this, we correct the error value to what it would have been if we had never
// adjusted the clock rate.
// In the last N seconds, if the clock rate was 1.0 we would have performed
// (1.0 - clock_rate) * N more seconds of actions, so the current action would
// have occurred that much sooner (reducing its error by that amount). We
// also need to take into account the previous "expected error" (due to clock
// rate changes) at the point when we last changed the clock rate. The
// expected error now is the previous expected error, plus the change due to
// the clock rate of (1.0 - clock_rate) * N seconds.
int64_t time_at_current_clock_rate = timestamp - clock_rate_start_timestamp_;
double correction = clock_rate_error_base_ +
(1.0 - current_clock_rate_) * time_at_current_clock_rate;
int64_t corrected_error = error - correction;
linear_error_.AddSample(x, corrected_error, 1.0);
if (time_at_current_clock_rate <
config_.rate_change_interval.InMicroseconds()) {
// Don't change clock rate too frequently.
return;
}
int64_t offset;
double slope;
double e;
if (!linear_error_.EstimateY(x, &offset, &e) ||
!linear_error_.EstimateSlope(&slope, &e)) {
return;
}
// Get the smoothed error (linear regression estimate) at the current time,
// translated back into actual error.
int64_t smoothed_error = offset + correction;
// If slope is positive, a clock rate of 1.0 is too slow (actions are
// occurring progressively later than desired). We wanted to do slope*N
// seconds actions during N seconds than would have been done at rate 1.0.
// Therefore the actual clock rate should be (1.0 + slope).
// However, we also want to correct for any existing offset. We correct so
// that the error should reduce to 0 by the next rate change interval;
// however the rate change is capped to prevent very fast slewing.
double offset_correction = static_cast<double>(smoothed_error) /
config_.rate_change_interval.InMicroseconds();
if (std::abs(smoothed_error) < config_.max_ignored_current_error) {
// Offset is small enough that we can ignore it, but still correct a little
// bit to avoid bouncing in and out of the ignored region.
offset_correction = offset_correction / 4;
}
offset_correction =
base::clamp(offset_correction, -config_.max_current_error_correction,
config_.max_current_error_correction);
double new_rate = (1.0 + slope) + offset_correction;
// Only change the clock rate if the difference between the desired rate and
// the current rate is larger than the minimum change.
if (std::fabs(new_rate - current_clock_rate_) > config_.min_rate_change ||
time_at_current_clock_rate > kMaxRateChangeInterval.InMicroseconds()) {
current_clock_rate_ =
change_clock_rate_.Run(new_rate, slope, smoothed_error);
clock_rate_start_timestamp_ = timestamp;
clock_rate_error_base_ = correction;
}
}
} // namespace media
} // namespace chromecast
| {
"content_hash": "04e95f434704881819d1877842e9586f",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 80,
"avg_line_length": 40.58181818181818,
"alnum_prop": 0.6881720430107527,
"repo_name": "ric2b/Vivaldi-browser",
"id": "f1cc282b8cbe66f51781ffc8505d20c7bab958fc",
"size": "4777",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "chromium/chromecast/media/audio/rate_adjuster.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package com.evolveum.midpoint.util;
/**
* @author semancik
*
*/
@FunctionalInterface
public interface Foreachable<T> {
/**
* Will call processor for every element in the instance.
* This is NOT recursive. E.g. in case of collection of collections
* the processor will NOT be called for elements of the inner collections.
* If you need recursion please have a look at Visitor.
*/
void foreach(Processor<T> processor);
}
| {
"content_hash": "af207a11828d74083adcc3002976aaf1",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 75,
"avg_line_length": 23.05263157894737,
"alnum_prop": 0.723744292237443,
"repo_name": "arnost-starosta/midpoint",
"id": "199e6559ed766c8018995c1de5ba2ec2fc01b288",
"size": "1034",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "infra/util/src/main/java/com/evolveum/midpoint/util/Foreachable.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "360626"
},
{
"name": "CSS",
"bytes": "246079"
},
{
"name": "HTML",
"bytes": "1906400"
},
{
"name": "Java",
"bytes": "33331059"
},
{
"name": "JavaScript",
"bytes": "18450"
},
{
"name": "PLSQL",
"bytes": "212132"
},
{
"name": "PLpgSQL",
"bytes": "9834"
},
{
"name": "Perl",
"bytes": "13072"
},
{
"name": "Shell",
"bytes": "52"
}
],
"symlink_target": ""
} |
$(function() {
function getCookie(name)
{
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
$.ajaxSetup({
crossDomain: false, // obviates need for sameOrigin test
beforeSend: function(xhr, settings) {
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
function request_photos(aid, next, callback) {
$.ajax({
type: "POST",
url: "photos",
dataType: "json",
data: {"album": aid, "next": next}
}).done(function(data){
if (data.status == 0)
callback(data.result);
});
}
var PHOTO_PER_ROW = 4
// var albumListNode = $("#album_list");
var albumPageNode = $("#album_page");
/* var AlbumList = function(listener) {
this.albums = [];
this.listener = listener;
this.list_node = albumListNode.find('ul');
this.add(0, '(ALL)');
this.add_divider();
}
AlbumList.prototype = {
view: function(idx) {
if (0 > idx) return;
if (idx >= this.albums.length) return;
this.listener.onAlbumChanging(this.albums[idx]);
},
add: function(album_id, name) {
var that = this;
var node = $("<li>");
var link = $("<a>");
var idx = that.albums.length;
link.attr("role", "menuitem").attr("tabindex","-1").attr("href","#");
link.append(name);
node.append(link);
link.on("click", function(e) {
that.listener.albumView(idx);
return true;
});
that.albums.push({id: album_id, name: name});
this.list_node.append(node);
},
add_divider: function() {
var divider = $("<li>").attr("class", "divider");
this.list_node.append(divider);
},
update: function(albums) {
var len = albums.length;
for (var i=0; i<len; i++) {
this.add(albums[i].id, albums[i].name);
}
}
};
*/
var Album = function(page, album_id) {
this.page = page;
this.album = album_id;
this.photos = new Array();
this.albumRows = [];
this.currentPhoto = 0;
this.size = 0;
this.leftSize = -1;
this.node = $("<div>");
albumPageNode.append(this.node);
};
Album.prototype = {
complete: function() {
return this.leftSize == 0;
},
request: function(callback) {
var that = this;
request_photos(this.album,
this.currentPhoto,
function(data) {
if (that.currentPhoto != 0 && that.currentPhoto <= data.next)
return;
var length = data.size;
for (var i=0; i<length; i++) {
that.add(data.photos[i])
}
that.currentPhoto = data.next;
that.size += length;
that.leftSize = data.left_size;
callback();
});
},
add: function(photo) {
var that = this;
var length = that.photos.length;
if (length % PHOTO_PER_ROW > 0) {
var row = that.albumRows.pop();
} else {
// insert a row.
var stand = $("<div>").attr("class", "row");
var details = $("<div>").attr("class", "photo_details")
.append($("<img>"));
var levelNode = $("<div>")
.append(stand)
.append(details);
that.node.append(levelNode);
var row = {stand: stand,
details: details
}
}
var node = $("<div>").attr("class", "col-md-3")
.append($("<a>").attr("class", "thumbnail")
.append($("<img>").attr("src", photo.t_url))
);
row.stand.append(node);
that.albumRows.push(row);
var p = {
photo: photo,
node: node,
row: row
}
that.photos.push(p);
node.click(function(){
that.page.onClickPhoto(p);
});
},
clean: function() {
this.node.remove();
}
};
var AlbumPage = function() {
};
AlbumPage.prototype = {
initialize: function() {
var that = this;
that.albumList = new AlbumList(that);
that.albumList.add(0, '(ALL)');
that.albumList.add_divider();
that.currentAlbumIdx = -1;
that.currentAlbum = null;
that.currentPhoto = null;
that.albumList.request(function(albums) {
that.albumList.update(albums);
that.albumView(0);
});
},
albumView: function(idx) {
if (this.currentAlbumIdx != idx) {
this.albumList.view(idx)
this.currentAlbumIdx = idx;
}
},
onAlbumChanging: function(album) {
},
onClickPhoto: function(photo) {
},
onScroll: function() {
}
};
var page = new AlbumPage();
page.onAlbumChanging = function(album) {
var that = this;
if (that.currentAlbumIdx != -1)
that.currentAlbum.clean();
var alb = new Album(that, album.id);
alb.request(function() {
});
console.log(this.albumList);
that.currentAlbum = alb;
}
page.onClickPhoto = function(photo) {
if (this.currentPhoto == photo) {
photo.row.details.slideUp();
this.currentPhoto = null;
} else {
var detailNode = photo.row.details;
detailNode.find("img").attr("src", photo.photo.url);
if (this.currentPhoto == null || this.currentPhoto.row != photo.row) {
if (this.currentPhoto != null)
this.currentPhoto.row.details.slideUp("fast");
photo.row.details.slideDown(function() {
$('html,body').animate({scrollTop: photo.row.details.position().top-140 }, "fast");
});
}
this.currentPhoto = photo;
}
}
page.onScroll = function(e) {
if (this.currentAlbum.complete()) return;
var contentHeight = albumPageNode.height();
var contentTop = albumPageNode.position().top;
var pageHeight = $(window).height();
var scrollTop = $(window).scrollTop();
console.log(contentHeight - pageHeight + contentTop - scrollTop);
if (contentHeight - pageHeight + contentTop - scrollTop < 220) {
this.currentAlbum.request(function() {});
}
}
page.initialize();
$(window).scroll(function(e) {
page.onScroll()
});
});
| {
"content_hash": "84dd9f7fa143f2a61cdcc03f7c5fb22e",
"timestamp": "",
"source": "github",
"line_count": 279,
"max_line_length": 103,
"avg_line_length": 30.27956989247312,
"alnum_prop": 0.4341856060606061,
"repo_name": "HeXA-UNIST/dinger",
"id": "07f9daf44b63c6d565c2a9d967876656b67260ed",
"size": "8448",
"binary": false,
"copies": "1",
"ref": "refs/heads/devel",
"path": "website/static/js/album.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
from domain.decorators import login_and_domain_required
from rapidsms.webui.utils import render_to_response, paginated
from sms_notifications.models import SmsNotification, NotificationChoice
from sms_notifications.forms import SmsNotificationForm
@login_and_domain_required
def index(request):
template_name = 'index.html'
notifications = SmsNotification.objects.all().order_by("-authorised_personnel")
return render_to_response(request,
template_name,
{
"notifications": paginated(request, notifications, prefix="smsnotice"),
}
)
@login_and_domain_required
def add_notifications(request):
template_name = "sms-notifications.html"
if request.method == 'POST': # If the form has been submitted...
form = SmsNotificationForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# saving the form data is not cleaned
form.save()
return message(request,
"SMS Notification Added",
link="/smsnotification")
else:
form = SmsNotificationForm() # An unbound form
return render_to_response(request,
template_name,
{
'form': form,
}
)
@login_and_domain_required
def edit_notifications(request, pk):
template_name = "sms-notifications.html"
notification = get_object_or_404(SmsNotification, pk=pk)
if request.method == 'POST': # If the form has been submitted...
form = SmsNotificationForm(request.POST, instance = notification) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# saving the form data is not cleaned
form.save()
return message(request,
"SMS Notification Updated",
link="/smsnotification")
else:
form = SmsNotificationForm(instance=notification)
return render_to_response(request,
template_name,
{
'form': form,
'notification': notification,
}
)
@login_and_domain_required
def delete_notifications(req, pk):
notification = get_object_or_404(SmsNotification, pk=pk)
notification.delete()
transaction.commit()
id = int(pk)
return message(req,
"SMS Notification %d deleted" % (id),
link="/smsnotification")
| {
"content_hash": "6869aeb071f1777579dc08ffaadef8a9",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 105,
"avg_line_length": 38.666666666666664,
"alnum_prop": 0.5513649425287356,
"repo_name": "fredwilliam/PMO",
"id": "3dddacbca7321d65eb8f3a41bac1fee259baacc1",
"size": "2784",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "apps/sms_notifications/views.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "553345"
},
{
"name": "PHP",
"bytes": "2787"
},
{
"name": "Python",
"bytes": "3626515"
},
{
"name": "Shell",
"bytes": "487"
}
],
"symlink_target": ""
} |
package org.gradle.api.internal.artifacts.ivyservice.resolveengine.projectresult;
import org.gradle.api.artifacts.component.ProjectComponentIdentifier;
import java.util.Set;
public interface ResolvedProjectConfigurationResult {
ProjectComponentIdentifier getId();
Set<String> getTargetConfigurations();
}
| {
"content_hash": "c8c84dacf2b9ec2fda6528bb1c16468b",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 81,
"avg_line_length": 24.53846153846154,
"alnum_prop": 0.8244514106583072,
"repo_name": "Artificial-Engineering/lycheeJS",
"id": "cc1d8f3daafa99790cd8cb4644555f15dc438f1f",
"size": "934",
"binary": false,
"copies": "2",
"ref": "refs/heads/development",
"path": "lycheejs/bin/runtime/html-webview/android-toolchain/gradle/src/dependency-management/org/gradle/api/internal/artifacts/ivyservice/resolveengine/projectresult/ResolvedProjectConfigurationResult.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AppleScript",
"bytes": "258"
},
{
"name": "CSS",
"bytes": "21259"
},
{
"name": "HTML",
"bytes": "56420"
},
{
"name": "JavaScript",
"bytes": "1206074"
},
{
"name": "Shell",
"bytes": "38111"
},
{
"name": "Smarty",
"bytes": "5714"
}
],
"symlink_target": ""
} |
// The user can choose whether or not to include TinyXML support in the DOM. Supporting TinyXML will
// require linking against it. By default TinyXML support isn't included.
#if defined(DOM_INCLUDE_TINYXML)
#if defined(DOM_DYNAMIC) && defined(_MSC_VER)
#pragma comment(lib, "tinyxml.lib")
#endif
#if defined(_MSC_VER)
#pragma warning(disable: 4100) // warning C4100: 'element' : unreferenced formal parameter
#endif
#include <string>
#include <tinyxml.h>
#include <dae.h>
#include <dom.h>
#include <dae/daeMetaElement.h>
#include <dae/daeErrorHandler.h>
#include <dae/daeMetaElementAttribute.h>
#include <dae/daeTinyXMLPlugin.h>
#include <dae/daeDocument.h>
using namespace std;
namespace {
daeInt getCurrentLineNumber(TiXmlElement* element) {
return -1;
}
}
daeTinyXMLPlugin::daeTinyXMLPlugin()
{
m_doc = NULL;
supportedProtocols.push_back("*");
}
daeTinyXMLPlugin::~daeTinyXMLPlugin()
{
}
daeInt daeTinyXMLPlugin::setOption( daeString option, daeString value )
{
return DAE_ERR_INVALID_CALL;
}
daeString daeTinyXMLPlugin::getOption( daeString option )
{
return NULL;
}
daeElementRef daeTinyXMLPlugin::readFromFile(const daeURI& uri) {
string file = cdom::uriToNativePath(uri.str());
if (file.empty())
return NULL;
TiXmlDocument doc;
doc.LoadFile(file.c_str());
if (!doc.RootElement()) {
daeErrorHandler::get()->handleError((std::string("Failed to open ") + uri.str() +
" in daeTinyXMLPlugin::readFromFile\n").c_str());
return NULL;
}
return readElement(doc.RootElement(), NULL);
}
daeElementRef daeTinyXMLPlugin::readFromMemory(daeString buffer, const daeURI& baseUri) {
TiXmlDocument doc;
doc.Parse(buffer);
if (!doc.RootElement()) {
daeErrorHandler::get()->handleError("Failed to open XML document from memory buffer in "
"daeTinyXMLPlugin::readFromMemory\n");
return NULL;
}
return readElement(doc.RootElement(), NULL);
}
daeElementRef daeTinyXMLPlugin::readElement(TiXmlElement* tinyXmlElement, daeElement* parentElement) {
std::vector<attrPair> attributes;
for (TiXmlAttribute* attrib = tinyXmlElement->FirstAttribute(); attrib != NULL; attrib = attrib->Next())
attributes.push_back(attrPair(attrib->Name(), attrib->Value()));
daeElementRef element = beginReadElement(parentElement, tinyXmlElement->Value(),
attributes, getCurrentLineNumber(tinyXmlElement));
if (!element) {
// We couldn't create the element. beginReadElement already printed an error message.
return NULL;
}
if (tinyXmlElement->GetText() != NULL)
readElementText(element, tinyXmlElement->GetText(), getCurrentLineNumber(tinyXmlElement));
// Recurse children
for (TiXmlElement* child = tinyXmlElement->FirstChildElement(); child != NULL; child = child->NextSiblingElement())
element->placeElement(readElement(child, element));
return element;
}
daeInt daeTinyXMLPlugin::write(const daeURI& name, daeDocument *document, daeBool replace)
{
// Make sure database and document are both set
if (!database)
return DAE_ERR_INVALID_CALL;
if(!document)
return DAE_ERR_COLLECTION_DOES_NOT_EXIST;
string fileName = cdom::uriToNativePath(name.str());
if (fileName.empty())
{
daeErrorHandler::get()->handleError( "can't get path in write\n" );
return DAE_ERR_BACKEND_IO;
}
// If replace=false, don't replace existing files
if(!replace)
{
// Using "stat" would be better, but it's not available on all platforms
FILE *tempfd = fopen(fileName.c_str(), "r");
if(tempfd != NULL)
{
// File exists, return error
fclose(tempfd);
return DAE_ERR_BACKEND_FILE_EXISTS;
}
fclose(tempfd);
}
m_doc = new TiXmlDocument(name.getURI());
if (m_doc)
{
m_doc->SetTabSize(4);
TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );
m_doc->LinkEndChild( decl );
writeElement(document->getDomRoot());
// TODO check if writing to zae
// if( 0 ) {
// // Declare a printer
// TiXmlPrinter printer;
//
// // attach it to the document you want to convert in to a std::string
// m_doc->Accept(&printer);
//
// // Create a std::string and copy your document data in to the string
// std::string str = printer.CStr();
//
// // compress str and size to fileName
//
// }
m_doc->SaveFile(fileName.c_str());
delete m_doc;
m_doc = NULL;
}
return DAE_OK;
}
void daeTinyXMLPlugin::writeElement( daeElement* element )
{
daeMetaElement* _meta = element->getMeta();
if (!_meta->getIsTransparent() )
{
TiXmlElement* tiElm = new TiXmlElement( element->getElementName() );
if (m_elements.empty() == true) {
m_doc->LinkEndChild(tiElm);
} else {
TiXmlElement* first = m_elements.front();
first->LinkEndChild(tiElm);
}
m_elements.push_front(tiElm);
daeMetaAttributeRefArray& attrs = _meta->getMetaAttributes();
int acnt = (int)attrs.getCount();
for(int i=0; i<acnt; i++)
{
writeAttribute( attrs[i], element );
}
}
writeValue(element);
daeElementRefArray children;
element->getChildren( children );
for ( size_t x = 0; x < children.getCount(); x++ )
{
writeElement( children.get(x) );
}
if (!_meta->getIsTransparent() )
{
m_elements.pop_front();
}
}
void daeTinyXMLPlugin::writeValue( daeElement* element )
{
if (daeMetaAttribute* attr = element->getMeta()->getValueAttribute()) {
std::ostringstream buffer;
attr->memoryToString(element, buffer);
std::string s = buffer.str();
if (!s.empty())
m_elements.front()->LinkEndChild( new TiXmlText(buffer.str().c_str()) );
}
}
void daeTinyXMLPlugin::writeAttribute( daeMetaAttribute* attr, daeElement* element )
{
ostringstream buffer;
attr->memoryToString(element, buffer);
string str = buffer.str();
// Don't write the attribute if
// - The attribute isn't required AND
// - The attribute has no default value and the current value is ""
// - The attribute has a default value and the current value matches the default
if (!attr->getIsRequired()) {
if(!attr->getDefaultValue() && str.empty())
return;
if(attr->getDefaultValue() && attr->compareToDefault(element) == 0)
return;
}
m_elements.front()->SetAttribute(attr->getName(), str.c_str());
}
#endif // DOM_INCLUDE_TINYXML
| {
"content_hash": "ef926730d6ee075f55e6bad84d1b9401",
"timestamp": "",
"source": "github",
"line_count": 231,
"max_line_length": 119,
"avg_line_length": 29.757575757575758,
"alnum_prop": 0.6254000581902822,
"repo_name": "jdsika/TUM_HOly",
"id": "31654012b19c2008319a023d63bffb3fbb929599",
"size": "7088",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "openrave/3rdparty/collada-2.4.0/src/dae/daeTinyXMLPlugin.cpp",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "361"
},
{
"name": "C",
"bytes": "111973"
},
{
"name": "C#",
"bytes": "24641"
},
{
"name": "C++",
"bytes": "11966748"
},
{
"name": "CMake",
"bytes": "212392"
},
{
"name": "CSS",
"bytes": "2102"
},
{
"name": "HTML",
"bytes": "16213"
},
{
"name": "Makefile",
"bytes": "41"
},
{
"name": "Matlab",
"bytes": "198171"
},
{
"name": "Modelica",
"bytes": "621"
},
{
"name": "Objective-C",
"bytes": "51576"
},
{
"name": "Python",
"bytes": "10053508"
},
{
"name": "Shell",
"bytes": "11963"
},
{
"name": "XSLT",
"bytes": "471726"
}
],
"symlink_target": ""
} |
package jodd.http;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.util.Map;
class Liferay {
private static void sendGet1() {
HttpResponse response = HttpRequest
.get("http://192.168.1.111:8080/api/jsonws/user/get-user-by-id")
.query("userId", "10194")
.basicAuthentication("test", "test")
.send();
System.out.println(response);
}
private static void sendGet15() {
HttpResponse response = HttpRequest
.get("http://192.168.1.111:8080/api/jsonws/user/get-user-by-id?userId=10194")
.basicAuthentication("test", "test")
.send();
System.out.println(response);
}
private static void sendGet2() {
HttpRequest request = new HttpRequest();
request
.method("GET")
.protocol("http")
.host("192.168.1.111")
.port(8080)
.path("/api/jsonws/user/get-user-by-id");
Map<String, Object> httpParams = request.query();
httpParams.put("userId", "10194");
request.basicAuthentication("test", "test");
Socket socket = request.open().getSocket();
try {
socket.setSoTimeout(1000);
} catch (SocketException e) {
}
HttpResponse response = request.send();
System.out.println(response);
}
private static void sendPost1() {
HttpResponse response = HttpRequest
.post("http://192.168.1.111:8080/api/jsonws/user/get-user-by-id")
.form("userId", "10194")
.basicAuthentication("test", "test")
.send();
System.out.println(response);
}
private static void sendPost2() {
HttpRequest httpRequest = HttpRequest
.post("http://192.168.1.111:8080/api/jsonws/dlapp/add-file-entry")
.form(
"repositoryId", "10178",
"folderId", "11219",
"sourceFileName", "a.zip",
"mimeType", "application/zip",
"title", "test",
"description", "Upload test",
"changeLog", "testing...",
"file", new File("d:\\a.jpg.zip")
)
.basicAuthentication("test", "test");
System.out.println(httpRequest);
HttpResponse httpResponse = httpRequest.send();
System.out.println(httpResponse);
}
private static void sendInvoker() {
HttpResponse response = HttpRequest
.get("http://192.168.1.111:8080/api/jsonws/invoke")
.body("{'$user[userId, screenName] = /user/get-user-by-id' : {'userId':'10194'}}")
.basicAuthentication("test", "test")
.send();
System.out.println(response);
}
public static void main(String[] args) throws IOException {
// getJodd();
// getLiferayGZip();
// getGoogles();
// postGoogle();
// sendGet1();
// sendGet15();
// sendGet2();
// sendPost1();
// sendPost2();
// sendInvoker();
}
private static void getJodd() {
HttpRequest httpRequest = HttpRequest.get("http://jodd.org");
HttpResponse response = httpRequest.send();
System.out.println(response);
}
private static void getLiferayGZip() {
HttpResponse response = HttpRequest
.get("http://www.liferay.com")
.acceptEncoding("gzip")
.send();
System.out.println(response.unzip());
}
private static void getGoogles() {
HttpRequest httpRequest = HttpRequest.get("https://jodd.org");
HttpResponse response = httpRequest.send();
System.out.println(response);
}
private static void postGoogle() {
HttpRequest httpRequest = HttpRequest.post("http://www.google.com");
HttpResponse response = httpRequest.send();
System.out.println(response);
}
} | {
"content_hash": "fc9820bcfd632843b7c3b9aad80c0958",
"timestamp": "",
"source": "github",
"line_count": 142,
"max_line_length": 86,
"avg_line_length": 23.880281690140844,
"alnum_prop": 0.6638159834856975,
"repo_name": "Artemish/jodd",
"id": "de472dbef7104a458842be29984ded06c2043edf",
"size": "3391",
"binary": false,
"copies": "2",
"ref": "refs/heads/hb-compat-tests",
"path": "etc/java/HttpTester.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C#",
"bytes": "150"
},
{
"name": "CSS",
"bytes": "18126"
},
{
"name": "Groovy",
"bytes": "23303"
},
{
"name": "Java",
"bytes": "4708503"
},
{
"name": "JavaScript",
"bytes": "20970"
},
{
"name": "Python",
"bytes": "28403"
},
{
"name": "Shell",
"bytes": "11467"
}
],
"symlink_target": ""
} |
#ifndef GPICK_TOOLS_PALETTE_FROM_IMAGE_H_
#define GPICK_TOOLS_PALETTE_FROM_IMAGE_H_
#include <gtk/gtk.h>
struct GlobalState;
void tools_palette_from_image_show(GtkWindow* parent, GlobalState* gs);
#endif /* GPICK_TOOLS_PALETTE_FROM_IMAGE_H_ */
| {
"content_hash": "e747be5620163ad8f4e01f7227cb150b",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 71,
"avg_line_length": 30.75,
"alnum_prop": 0.7560975609756098,
"repo_name": "thezbyg/gpick",
"id": "0cc89998687c23f5ef2fb83950807ca79bcf18ce",
"size": "1796",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/tools/PaletteFromImage.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "222515"
},
{
"name": "C++",
"bytes": "1533917"
},
{
"name": "CMake",
"bytes": "17483"
},
{
"name": "Lua",
"bytes": "12636"
},
{
"name": "Makefile",
"bytes": "1076"
},
{
"name": "Python",
"bytes": "30597"
},
{
"name": "Ragel",
"bytes": "13212"
},
{
"name": "Roff",
"bytes": "1459"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__wchar_t_console_system_32.c
Label Definition File: CWE78_OS_Command_Injection.one_string.label.xml
Template File: sources-sink-32.tmpl.c
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: console Read input from the console
* GoodSource: Fixed string
* Sink: system
* BadSink : Execute command in data using system()
* Flow Variant: 32 Data flow using two pointers to the same value within the same function
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define FULL_COMMAND L"%WINDIR%\\system32\\cmd.exe /c dir "
#else
#include <unistd.h>
#define FULL_COMMAND L"/bin/sh ls -la "
#endif
#ifdef _WIN32
#define SYSTEM _wsystem
#else /* NOT _WIN32 */
#define SYSTEM system
#endif
#ifndef OMITBAD
void CWE78_OS_Command_Injection__wchar_t_console_system_32_bad()
{
wchar_t * data;
wchar_t * *dataPtr1 = &data;
wchar_t * *dataPtr2 = &data;
wchar_t data_buf[100] = FULL_COMMAND;
data = data_buf;
{
wchar_t * data = *dataPtr1;
{
/* Read input from the console */
size_t dataLen = wcslen(data);
/* if there is room in data, read into it from the console */
if (100-dataLen > 1)
{
/* POTENTIAL FLAW: Read data from the console */
if (fgetws(data+dataLen, (int)(100-dataLen), stdin) != NULL)
{
/* The next few lines remove the carriage return from the string that is
* inserted by fgetws() */
dataLen = wcslen(data);
if (dataLen > 0 && data[dataLen-1] == L'\n')
{
data[dataLen-1] = L'\0';
}
}
else
{
printLine("fgetws() failed");
/* Restore NUL terminator if fgetws fails */
data[dataLen] = L'\0';
}
}
}
*dataPtr1 = data;
}
{
wchar_t * data = *dataPtr2;
/* POTENTIAL FLAW: Execute command in data possibly leading to command injection */
if (SYSTEM(data) <= 0)
{
printLine("command execution failed!");
exit(1);
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B()
{
wchar_t * data;
wchar_t * *dataPtr1 = &data;
wchar_t * *dataPtr2 = &data;
wchar_t data_buf[100] = FULL_COMMAND;
data = data_buf;
{
wchar_t * data = *dataPtr1;
/* FIX: Append a fixed string to data (not user / external input) */
wcscat(data, L"*.*");
*dataPtr1 = data;
}
{
wchar_t * data = *dataPtr2;
/* POTENTIAL FLAW: Execute command in data possibly leading to command injection */
if (SYSTEM(data) <= 0)
{
printLine("command execution failed!");
exit(1);
}
}
}
void CWE78_OS_Command_Injection__wchar_t_console_system_32_good()
{
goodG2B();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE78_OS_Command_Injection__wchar_t_console_system_32_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE78_OS_Command_Injection__wchar_t_console_system_32_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| {
"content_hash": "ace652759844df73e9a589fd10e43398",
"timestamp": "",
"source": "github",
"line_count": 143,
"max_line_length": 92,
"avg_line_length": 28.65034965034965,
"alnum_prop": 0.5511349768123017,
"repo_name": "maurer/tiamat",
"id": "49d03cc0b6a44bfb1934ac94bc3409bdafe08144",
"size": "4097",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/Juliet/testcases/CWE78_OS_Command_Injection/s06/CWE78_OS_Command_Injection__wchar_t_console_system_32.c",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
@extends('layouts.default')
@if ($lang == 'sv')
@section('title', $post->title )
@else
@section('title', $post->title_en )
@endif
@section('description', trans('messages.easytocreatetournaments'))
@section('keywords', trans('defaultkeywords'))
@section('content')
<article id="welcome" class="tiny">
@if ($lang == 'sv')
<h2>{{ $post->title }}</h2>
@else
<h2>{{ $post->title_en }}</h2>
@endif
</article>
<article id="content">
<section class="content">
<a href="/blog/">{{ trans('messages.back') }}</a>
<div class="post">
@if ($lang == 'sv')
{!! $post->content !!}
@else
{!! $post->content_en !!}
@endif
<div class="post-footer">{{ trans('messages.createdof') }} {{ $post->user->name }} {{ Laravelrus\LocalizedCarbon\LocalizedCarbon::createFromTimeStamp(strtotime($post->created_at))->diffForHumans() }}</div>
</div>
</section>
</article>
@stop | {
"content_hash": "a579d60b4faea72e1d7c4ebc687f02c5",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 225,
"avg_line_length": 34.71875,
"alnum_prop": 0.49234923492349236,
"repo_name": "polybitgames/tournify",
"id": "9d90037e7793929bfb037b16f392a1de24bdfa5a",
"size": "1111",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "resources/views/blog/view.blade.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "611"
},
{
"name": "CSS",
"bytes": "388022"
},
{
"name": "HTML",
"bytes": "59303"
},
{
"name": "JavaScript",
"bytes": "387043"
},
{
"name": "PHP",
"bytes": "161896"
}
],
"symlink_target": ""
} |
<!-- *****************************************************************************************************************
TITLE
***************************************************************************************************************** -->
<div id="title" class="default-primary-color">
<div class="container">
<div class="row">
<h3>Login / Register.</h3>
</div><!-- /row -->
</div> <!-- /container -->
</div>
<div class="container mtb">
<div class="row">
<div class="col-lg-offset-2 col-lg-4">
<h4>Login</h4>
<div class="hline"></div>
<p>Welcome back!</p>
<form role="form" ng-submit="login()" >
<div class="form-group">
<label for="InputEmail1">Email address</label>
<input type="email" class="form-control" ng-model="email" id="email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" ng-model="password" id="password">
</div>
<button type="submit" class="btn btn-theme">Log In</button>
</form>
</div><! --/col-lg-8 -->
<div class="col-lg-4">
<h4>Register</h4>
<div class="hline"></div>
<p>Sign up today to enjoy lots of benefits!</p>
<form role="form">
<div class="form-group">
<label for="name">Your Name</label>
<input type="text" class="form-control" id="name">
</div>
<div class="form-group">
<label for="InputEmail1">Email address</label>
<input type="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password">
</div>
<div class="form-group">
<label for="password2">Password again</label>
<input type="password" class="form-control" id="password2">
</div>
<button type="submit" class="btn btn-theme">Register</button>
</form>
</div>
</div><! --/row -->
</div><! --/container -->
| {
"content_hash": "99835b2b12316f3a13c95d1e6895d266",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 118,
"avg_line_length": 37,
"alnum_prop": 0.4817449027975344,
"repo_name": "cjx3711/nvc-mpv",
"id": "7f30a6ab9be48f5bbf331f175dfaad1ded68f052",
"size": "2109",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "templates/login.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "73795"
},
{
"name": "HTML",
"bytes": "45820"
},
{
"name": "JavaScript",
"bytes": "101152"
}
],
"symlink_target": ""
} |
<?php
namespace Freedom\ObjectiveBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class DefaultControllerTest extends WebTestCase
{
public function testIndex()
{
$client = static::createClient();
$crawler = $client->request('GET', '/hello/Fabien');
$this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0);
}
}
| {
"content_hash": "da1243c48e08f27fb0f7d852c79b752f",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 90,
"avg_line_length": 23.88235294117647,
"alnum_prop": 0.6798029556650246,
"repo_name": "MaximePlancke/Freedom",
"id": "0d64a53f7b24c5f7ae226deb1449be35ca508f51",
"size": "406",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Freedom/ObjectiveBundle/Tests/Controller/DefaultControllerTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10880"
},
{
"name": "JavaScript",
"bytes": "37817"
},
{
"name": "PHP",
"bytes": "232329"
}
],
"symlink_target": ""
} |
<?php
/** Megleno-Romanian (Latin script) (Vlăheşte)
*
* See MessagesQqq.php for message documentation incl. usage of parameters
* To improve a translation please visit http://translatewiki.net
*
* @ingroup Language
* @file
*
* @author Andrijko Z.
* @author Кумулај Маркус
* @author Макѕе
* @author Приетен тев
*/
$fallback = 'ro';
| {
"content_hash": "7a7b64be1ef5cfbbdb8438f2f9189b59",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 74,
"avg_line_length": 20.352941176470587,
"alnum_prop": 0.6936416184971098,
"repo_name": "ArcherCraftStore/ArcherVMPeridot",
"id": "37e01a8006a43473e671884adf47e84626ab4ec7",
"size": "376",
"binary": false,
"copies": "20",
"ref": "refs/heads/master",
"path": "apps/mediawiki/htdocs/languages/messages/MessagesRuq_latn.php",
"mode": "33261",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2020 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.
-->
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="a11y_no_permission" msgid="6954835069208568445">"Деректерді пайдалануға рұқсат жоқ."</string>
<string name="a11y_no_data" msgid="1150196161728975556">"Дерек жоқ."</string>
<string name="a11y_template_range" msgid="43093005594777633">"<xliff:g id="MAX">%2$f</xliff:g>/<xliff:g id="VALUE">%1$f</xliff:g>"</string>
</resources>
| {
"content_hash": "c81b67fac2fcc616a43b275c56abe422",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 143,
"avg_line_length": 48.869565217391305,
"alnum_prop": 0.7322064056939501,
"repo_name": "androidx/androidx",
"id": "fe433ec3f4d0abe278f79f4647b5bfb9ecbe751b",
"size": "1162",
"binary": false,
"copies": "3",
"ref": "refs/heads/androidx-main",
"path": "wear/watchface/watchface-data/src/main/res/values-kk/accessibility_strings.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AIDL",
"bytes": "263978"
},
{
"name": "ANTLR",
"bytes": "19860"
},
{
"name": "C",
"bytes": "4764"
},
{
"name": "C++",
"bytes": "9020585"
},
{
"name": "CMake",
"bytes": "11999"
},
{
"name": "HTML",
"bytes": "21175"
},
{
"name": "Java",
"bytes": "59499889"
},
{
"name": "JavaScript",
"bytes": "1343"
},
{
"name": "Kotlin",
"bytes": "66123157"
},
{
"name": "Python",
"bytes": "292398"
},
{
"name": "Shell",
"bytes": "167367"
},
{
"name": "Swift",
"bytes": "3153"
},
{
"name": "TypeScript",
"bytes": "7599"
}
],
"symlink_target": ""
} |
BOOST_FIXTURE_TEST_SUITE(mvfstandalone_tests, BasicTestingSetup)
// tests of the wallet backup filename construction
BOOST_AUTO_TEST_CASE(wallet_backup_path_expansion)
{
std::string platform(BOOST_PLATFORM);
boost::filesystem::path datadir = GetDataDir();
std::string dds = datadir.string();
static const boost::filesystem::path abspath(GetDataDir());
static const boost::filesystem::path relpath("rel");
static const boost::filesystem::path fullpath = datadir / "w@.dat";
static const boost::filesystem::path userpath("/home/user/.bitcoin");
// sanity checks
BOOST_CHECK(abspath.is_absolute());
BOOST_CHECK(!abspath.is_relative());
BOOST_CHECK(relpath.is_relative());
BOOST_CHECK(!relpath.is_absolute());
BOOST_CHECK(!relpath.has_root_directory());
BOOST_CHECK(fullpath.has_filename());
BOOST_CHECK(userpath.has_filename());
BOOST_CHECK(userpath.has_extension());
BOOST_CHECK_EQUAL(userpath.filename(), ".bitcoin");
BOOST_CHECK_EQUAL(userpath.extension(), ".bitcoin");
BOOST_CHECK_EQUAL(userpath.extension(), userpath.filename());
#ifdef ENABLE_WALLET
// if first arg is empty, then datadir is prefixed
BOOST_CHECK_EQUAL(MVFexpandWalletAutoBackupPath("", "w.dat", 0, false),
datadir / "w.dat.auto.0.bak");
// if first arg is relative, then datadir is still prefixed
BOOST_CHECK_EQUAL(MVFexpandWalletAutoBackupPath("dir", "w.dat", 1, false),
datadir / "dir" / "w.dat.auto.1.bak");
// if first arg is absolute, then datadir is not prefixed
BOOST_CHECK_EQUAL(MVFexpandWalletAutoBackupPath(abspath.string(), "w.dat", 2, false),
abspath / "w.dat.auto.2.bak");
// if path contains @ it is replaced by height
BOOST_CHECK_EQUAL(MVFexpandWalletAutoBackupPath("@@@", "w@.dat", 7, false),
datadir / "777" / "w7.dat.auto.7.bak");
// if first contains filename, then appending of filename is skipped
BOOST_CHECK_EQUAL(MVFexpandWalletAutoBackupPath(fullpath.string(), "w.dat", 6, false),
datadir / "w6.dat");
#endif
}
BOOST_AUTO_TEST_CASE(btcfork_conf_maps)
{
btcforkMapArgs.clear();
btcforkMapArgs["strtest1"] = "string...";
// strtest2 undefined on purpose
btcforkMapArgs["inttest1"] = "12345";
btcforkMapArgs["inttest2"] = "81985529216486895";
// inttest3 undefined on purpose
btcforkMapArgs["booltest1"] = "";
// booltest2 undefined on purpose
btcforkMapArgs["booltest3"] = "0";
btcforkMapArgs["booltest4"] = "1";
BOOST_CHECK_EQUAL(MVFGetArg("strtest1", "default"), "string...");
BOOST_CHECK_EQUAL(MVFGetArg("strtest2", "default"), "default");
BOOST_CHECK_EQUAL(MVFGetArg("inttest1", -1), 12345);
BOOST_CHECK_EQUAL(MVFGetArg("inttest2", -1), 81985529216486895LL);
BOOST_CHECK_EQUAL(MVFGetArg("inttest3", -1), -1);
BOOST_CHECK_EQUAL(MVFGetBoolArg("booltest1", false), true);
BOOST_CHECK_EQUAL(MVFGetBoolArg("booltest2", false), false);
BOOST_CHECK_EQUAL(MVFGetBoolArg("booltest3", false), false);
BOOST_CHECK_EQUAL(MVFGetBoolArg("booltest4", false), true);
}
// test MVFGetConfigFile(), the MVF config (btcfork.conf) filename construction
BOOST_AUTO_TEST_CASE(mvfgetconfigfile)
{
boost::filesystem::path cfgBaseFile(BTCFORK_CONF_FILENAME);
BOOST_CHECK(!cfgBaseFile.is_complete());
BOOST_CHECK_EQUAL(MVFGetConfigFile(), (GetDataDir() / BTCFORK_CONF_FILENAME));
}
// test MVFReadConfigFile() which reads a config file into arg maps
BOOST_AUTO_TEST_CASE(mvfreadconfigfile)
{
boost::filesystem::path pathBTCforkConfigFile = GetTempPath() / boost::filesystem::unique_path("btcfork.conf.%%%%.txt");
//fprintf(stderr,"btcfork_conf_file: set config file %s\n", pathBTCforkConfigFile.string().c_str());
BOOST_CHECK(!boost::filesystem::exists(pathBTCforkConfigFile));
try
{
std::ofstream btcforkfile(pathBTCforkConfigFile.string().c_str(), std::ios::out);
btcforkfile << "forkheight=" << HARDFORK_HEIGHT_REGTEST << "\n";
btcforkfile << "forkid=" << HARDFORK_SIGHASH_ID << "\n";
btcforkfile << "autobackupblock=" << (HARDFORK_HEIGHT_REGTEST - 1) << "\n";
btcforkfile.close();
} catch (const std::exception& e) {
BOOST_ERROR("Cound not write config file " << pathBTCforkConfigFile << " : " << e.what());
}
BOOST_CHECK(boost::filesystem::exists(pathBTCforkConfigFile));
// clear args map and read file
btcforkMapArgs.clear();
try
{
MVFReadConfigFile(pathBTCforkConfigFile, btcforkMapArgs, btcforkMapMultiArgs);
} catch (const std::exception& e) {
BOOST_ERROR("Cound not read config file " << pathBTCforkConfigFile << " : " << e.what());
}
// check map after reading
BOOST_CHECK_EQUAL(atoi(btcforkMapArgs["-forkheight"]), (int)HARDFORK_HEIGHT_REGTEST);
BOOST_CHECK_EQUAL(atoi(btcforkMapArgs["-forkid"]), (int)HARDFORK_SIGHASH_ID);
BOOST_CHECK_EQUAL(atoi(btcforkMapArgs["-autobackupblock"]), (int)(HARDFORK_HEIGHT_REGTEST - 1));
// added so that we can update this test when adding new entries
BOOST_CHECK_EQUAL(btcforkMapArgs.size(), 3);
// cleanup
boost::filesystem::remove(pathBTCforkConfigFile);
BOOST_CHECK(!boost::filesystem::exists(pathBTCforkConfigFile));
}
BOOST_AUTO_TEST_SUITE_END()
| {
"content_hash": "644ed353ce4a5cd079f0c2952f6ecda9",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 124,
"avg_line_length": 42.864,
"alnum_prop": 0.6754385964912281,
"repo_name": "BTCfork/hardfork_prototype_1_mvf-bu",
"id": "6cdabeac539d0291f218f43564a722d852a89a14",
"size": "5860",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/test/mvfstandalone_tests.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "28456"
},
{
"name": "C",
"bytes": "682360"
},
{
"name": "C++",
"bytes": "5102661"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "HTML",
"bytes": "50622"
},
{
"name": "Java",
"bytes": "30290"
},
{
"name": "M4",
"bytes": "189719"
},
{
"name": "Makefile",
"bytes": "111286"
},
{
"name": "Objective-C",
"bytes": "5785"
},
{
"name": "Objective-C++",
"bytes": "7360"
},
{
"name": "Protocol Buffer",
"bytes": "2308"
},
{
"name": "Python",
"bytes": "962519"
},
{
"name": "QMake",
"bytes": "2020"
},
{
"name": "Roff",
"bytes": "3821"
},
{
"name": "Shell",
"bytes": "44285"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Poker
{
public class FormNotaInfo
{
public string TipoMesa { get; set; }
public IntPtr MainWindowHandle { get; set; }
public string MainWindowTitle { get; set; }
}
}
| {
"content_hash": "9119a5402459c5efc61970612d4ea2ef",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 52,
"avg_line_length": 21.066666666666666,
"alnum_prop": 0.6329113924050633,
"repo_name": "danielfonsecacastro/SNG-MTT-Nano-Tracker",
"id": "a54e1dcdf4614f750baaa14d0d8c7bc78eb14c33",
"size": "318",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SNG-MTT-Nano-Tracker/FormNotaInfo.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "194193"
}
],
"symlink_target": ""
} |
import {HttpClient} from '@angular/common/http';
import {Injectable} from '@angular/core';
@Injectable()
export class AppService {
constructor(private http: HttpClient) {
}
testRoute() {
return this.http.get('/api/ping');
}
}
| {
"content_hash": "2df2ac89f07a7aa34890c1f787dcd7b7",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 48,
"avg_line_length": 18.53846153846154,
"alnum_prop": 0.6804979253112033,
"repo_name": "mrsan22/Angular-Flask-Docker-Skeleton",
"id": "15041b163475a8b9e7e0fe3aeb9eae364935008f",
"size": "241",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/src/app/app.service.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "80"
},
{
"name": "Dockerfile",
"bytes": "981"
},
{
"name": "HTML",
"bytes": "535"
},
{
"name": "JavaScript",
"bytes": "1729"
},
{
"name": "Python",
"bytes": "13829"
},
{
"name": "Shell",
"bytes": "620"
},
{
"name": "TypeScript",
"bytes": "6976"
}
],
"symlink_target": ""
} |
/**
* \file SDL_cpuinfo.h
*
* CPU feature detection for SDL.
*/
#ifndef _SDL_cpuinfo_h
#define _SDL_cpuinfo_h
#include "SDL_stdinc.h"
/* Need to do this here because intrin.h has C++ code in it */
/* Visual Studio 2005 has a bug where intrin.h conflicts with winnt.h */
#if defined(_MSC_VER) && (_MSC_VER >= 1500) && (defined(_M_IX86) || defined(_M_X64))
#include <intrin.h>
#ifndef _WIN64
#define __MMX__
#define __3dNOW__
#endif
#ifndef __SSE__
#define __SSE__
#endif
#ifndef __SSE2__
#define __SSE2__
#endif
#elif defined(__MINGW64_VERSION_MAJOR)
#include <intrin.h>
#else
#ifdef __ALTIVEC__
#if HAVE_ALTIVEC_H && !defined(__APPLE_ALTIVEC__)
#include <altivec.h>
#undef pixel
#endif
#endif
#ifdef __MMX__
#include <mmintrin.h>
#endif
#ifdef __3dNOW__
#include <mm3dnow.h>
#endif
#ifdef __SSE__
#include <xmmintrin.h>
#endif
#ifdef __SSE2__
#include <emmintrin.h>
#endif
#endif
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/* This is a guess for the cacheline size used for padding.
* Most x86 processors have a 64 byte cache line.
* The 64-bit PowerPC processors have a 128 byte cache line.
* We'll use the larger value to be generally safe.
*/
#define SDL_CACHELINE_SIZE 128
/**
* This function returns the number of CPU cores available.
*/
extern DECLSPEC int SDLCALL SDL_GetCPUCount(void);
/**
* This function returns the L1 cache line size of the CPU
*
* This is useful for determining multi-threaded structure padding
* or SIMD prefetch sizes.
*/
extern DECLSPEC int SDLCALL SDL_GetCPUCacheLineSize(void);
/**
* This function returns true if the CPU has the RDTSC instruction.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasRDTSC(void);
/**
* This function returns true if the CPU has AltiVec features.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasAltiVec(void);
/**
* This function returns true if the CPU has MMX features.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasMMX(void);
/**
* This function returns true if the CPU has 3DNow! features.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_Has3DNow(void);
/**
* This function returns true if the CPU has SSE features.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasSSE(void);
/**
* This function returns true if the CPU has SSE2 features.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasSSE2(void);
/**
* This function returns true if the CPU has SSE3 features.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasSSE3(void);
/**
* This function returns true if the CPU has SSE4.1 features.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasSSE41(void);
/**
* This function returns true if the CPU has SSE4.2 features.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasSSE42(void);
/**
* This function returns true if the CPU has AVX features.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasAVX(void);
/**
* This function returns true if the CPU has AVX2 features.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasAVX2(void);
/**
* This function returns the amount of RAM configured in the system, in MB.
*/
extern DECLSPEC int SDLCALL SDL_GetSystemRAM(void);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* _SDL_cpuinfo_h */
/* vi: set ts=4 sw=4 expandtab: */
| {
"content_hash": "e06355932ac94ae3f268b1b30dea7125",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 84,
"avg_line_length": 22.243243243243242,
"alnum_prop": 0.701397326852977,
"repo_name": "robotjunkyard/learn3d",
"id": "d85fb0c03464a05ae122f5ba4c9b2dcbed6bf2f3",
"size": "4230",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cpp-learn3d/dep/SDL2-2.0.5/include/SDL2/SDL_cpuinfo.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1519393"
},
{
"name": "C++",
"bytes": "103484"
},
{
"name": "Common Lisp",
"bytes": "35437"
},
{
"name": "Makefile",
"bytes": "744"
},
{
"name": "Objective-C",
"bytes": "8847"
}
],
"symlink_target": ""
} |
package org.apache.shiro.realm.ldap;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.AllowAllCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.ldap.UnsupportedAuthenticationMechanismException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.naming.AuthenticationNotSupportedException;
import javax.naming.NamingException;
import javax.naming.ldap.LdapContext;
/**
* An LDAP {@link org.apache.shiro.realm.Realm Realm} implementation utilizing Sun's/Oracle's
* <a href="http://download-llnw.oracle.com/javase/tutorial/jndi/ldap/jndi.html">JNDI API as an LDAP API</a>. This is
* Shiro's default implementation for supporting LDAP, as using the JNDI API has been a common approach for Java LDAP
* support for many years.
* <p/>
* This realm implementation and its backing {@link JndiLdapContextFactory} should cover 99% of all Shiro-related LDAP
* authentication and authorization needs. However, if it does not suit your needs, you might want to look into
* creating your own realm using an alternative, perhaps more robust, LDAP communication API, such as the
* <a href="http://directory.apache.org/api/">Apache LDAP API</a>.
* <h2>Authentication</h2>
* During an authentication attempt, if the submitted {@code AuthenticationToken}'s
* {@link org.apache.shiro.authc.AuthenticationToken#getPrincipal() principal} is a simple username, but the
* LDAP directory expects a complete User Distinguished Name (User DN) to establish a connection, the
* {@link #setUserDnTemplate(String) userDnTemplate} property must be configured. If not configured,
* the property will pass the simple username directly as the User DN, which is often incorrect in most LDAP
* environments (maybe Microsoft ActiveDirectory being the exception).
* <h2>Authorization</h2>
* By default, authorization is effectively disabled due to the default
* {@link #doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)} implementation returning {@code null}.
* If you wish to perform authorization based on an LDAP schema, you must subclass this one
* and override that method to reflect your organization's data model.
* <h2>Configuration</h2>
* This class primarily provides the {@link #setUserDnTemplate(String) userDnTemplate} property to allow you to specify
* the your LDAP server's User DN format. Most other configuration is performed via the nested
* {@link LdapContextFactory contextFactory} property.
* <p/>
* For example, defining this realm in Shiro .ini:
* <pre>
* [main]
* ldapRealm = org.apache.shiro.realm.ldap.DefaultLdapRealm
* ldapRealm.userDnTemplate = uid={0},ou=users,dc=mycompany,dc=com
* ldapRealm.contextFactory.url = ldap://ldapHost:389
* ldapRealm.contextFactory.authenticationMechanism = DIGEST-MD5
* ldapRealm.contextFactory.environment[some.obscure.jndi.key] = some value
* ...
* </pre>
* The default {@link #setContextFactory contextFactory} instance is a {@link JndiLdapContextFactory}. See that
* class's JavaDoc for more information on configuring the LDAP connection as well as specifying JNDI environment
* properties as necessary.
*
* @see JndiLdapContextFactory
*
* @since 1.3
*/
public class DefaultLdapRealm extends AuthorizingRealm {
private static final Logger log = LoggerFactory.getLogger(DefaultLdapRealm.class);
//The zero index currently means nothing, but could be utilized in the future for other substitution techniques.
private static final String USERDN_SUBSTITUTION_TOKEN = "{0}";
private String userDnPrefix;
private String userDnSuffix;
/*--------------------------------------------
| I N S T A N C E V A R I A B L E S |
============================================*/
/**
* The LdapContextFactory instance used to acquire {@link javax.naming.ldap.LdapContext LdapContext}'s at runtime
* to acquire connections to the LDAP directory to perform authentication attempts and authorizatino queries.
*/
private LdapContextFactory contextFactory;
/*--------------------------------------------
| C O N S T R U C T O R S |
============================================*/
/**
* Default no-argument constructor that defaults the internal {@link LdapContextFactory} instance to a
* {@link JndiLdapContextFactory}.
*/
public DefaultLdapRealm() {
//Credentials Matching is not necessary - the LDAP directory will do it automatically:
setCredentialsMatcher(new AllowAllCredentialsMatcher());
//Any Object principal and Object credentials may be passed to the LDAP provider, so accept any token:
setAuthenticationTokenClass(AuthenticationToken.class);
this.contextFactory = new JndiLdapContextFactory();
}
/*--------------------------------------------
| A C C E S S O R S / M O D I F I E R S |
============================================*/
/**
* Returns the User DN prefix to use when building a runtime User DN value or {@code null} if no
* {@link #getUserDnTemplate() userDnTemplate} has been configured. If configured, this value is the text that
* occurs before the {@link #USERDN_SUBSTITUTION_TOKEN} in the {@link #getUserDnTemplate() userDnTemplate} value.
*
* @return the the User DN prefix to use when building a runtime User DN value or {@code null} if no
* {@link #getUserDnTemplate() userDnTemplate} has been configured.
*/
protected String getUserDnPrefix() {
return userDnPrefix;
}
/**
* Returns the User DN suffix to use when building a runtime User DN value. or {@code null} if no
* {@link #getUserDnTemplate() userDnTemplate} has been configured. If configured, this value is the text that
* occurs after the {@link #USERDN_SUBSTITUTION_TOKEN} in the {@link #getUserDnTemplate() userDnTemplate} value.
*
* @return the User DN suffix to use when building a runtime User DN value or {@code null} if no
* {@link #getUserDnTemplate() userDnTemplate} has been configured.
*/
protected String getUserDnSuffix() {
return userDnSuffix;
}
/*--------------------------------------------
| M E T H O D S |
============================================*/
/**
* Sets the User Distinguished Name (DN) template to use when creating User DNs at runtime. A User DN is an LDAP
* fully-qualified unique user identifier which is required to establish a connection with the LDAP
* directory to authenticate users and query for authorization information.
* <h2>Usage</h2>
* User DN formats are unique to the LDAP directory's schema, and each environment differs - you will need to
* specify the format corresponding to your directory. You do this by specifying the full User DN as normal, but
* but you use a <b>{@code {0}}</b> placeholder token in the string representing the location where the
* user's submitted principal (usually a username or uid) will be substituted at runtime.
* <p/>
* For example, if your directory
* uses an LDAP {@code uid} attribute to represent usernames, the User DN for the {@code jsmith} user may look like
* this:
* <p/>
* <pre>uid=jsmith,ou=users,dc=mycompany,dc=com</pre>
* <p/>
* in which case you would set this property with the following template value:
* <p/>
* <pre>uid=<b>{0}</b>,ou=users,dc=mycompany,dc=com</pre>
* <p/>
* If no template is configured, the raw {@code AuthenticationToken}
* {@link AuthenticationToken#getPrincipal() principal} will be used as the LDAP principal. This is likely
* incorrect as most LDAP directories expect a fully-qualified User DN as opposed to the raw uid or username. So,
* ensure you set this property to match your environment!
*
* @param template the User Distinguished Name template to use for runtime substitution
* @throws IllegalArgumentException if the template is null, empty, or does not contain the
* {@code {0}} substitution token.
* @see LdapContextFactory#getLdapContext(Object,Object)
*/
public void setUserDnTemplate(String template) throws IllegalArgumentException {
if (!StringUtils.hasText(template)) {
String msg = "User DN template cannot be null or empty.";
throw new IllegalArgumentException(msg);
}
int index = template.indexOf(USERDN_SUBSTITUTION_TOKEN);
if (index < 0) {
String msg = "User DN template must contain the '" +
USERDN_SUBSTITUTION_TOKEN + "' replacement token to understand where to " +
"insert the runtime authentication principal.";
throw new IllegalArgumentException(msg);
}
String prefix = template.substring(0, index);
String suffix = template.substring(prefix.length() + USERDN_SUBSTITUTION_TOKEN.length());
if (log.isDebugEnabled()) {
log.debug("Determined user DN prefix [{}] and suffix [{}]", prefix, suffix);
}
this.userDnPrefix = prefix;
this.userDnSuffix = suffix;
}
/**
* Returns the User Distinguished Name (DN) template to use when creating User DNs at runtime - see the
* {@link #setUserDnTemplate(String) setUserDnTemplate} JavaDoc for a full explanation.
*
* @return the User Distinguished Name (DN) template to use when creating User DNs at runtime.
*/
public String getUserDnTemplate() {
return getUserDn(USERDN_SUBSTITUTION_TOKEN);
}
/**
* Returns the LDAP User Distinguished Name (DN) to use when acquiring an
* {@link javax.naming.ldap.LdapContext LdapContext} from the {@link LdapContextFactory}.
* <p/>
* If the the {@link #getUserDnTemplate() userDnTemplate} property has been set, this implementation will construct
* the User DN by substituting the specified {@code principal} into the configured template. If the
* {@link #getUserDnTemplate() userDnTemplate} has not been set, the method argument will be returned directly
* (indicating that the submitted authentication token principal <em>is</em> the User DN).
*
* @param principal the principal to substitute into the configured {@link #getUserDnTemplate() userDnTemplate}.
* @return the constructed User DN to use at runtime when acquiring an {@link javax.naming.ldap.LdapContext}.
* @throws IllegalArgumentException if the method argument is null or empty
* @throws IllegalStateException if the {@link #getUserDnTemplate userDnTemplate} has not been set.
* @see LdapContextFactory#getLdapContext(Object, Object)
*/
protected String getUserDn(String principal) throws IllegalArgumentException, IllegalStateException {
if (!StringUtils.hasText(principal)) {
throw new IllegalArgumentException("User principal cannot be null or empty for User DN construction.");
}
String prefix = getUserDnPrefix();
String suffix = getUserDnSuffix();
if (prefix == null && suffix == null) {
log.debug("userDnTemplate property has not been configured, indicating the submitted " +
"AuthenticationToken's principal is the same as the User DN. Returning the method argument " +
"as is.");
return principal;
}
int prefixLength = prefix != null ? prefix.length() : 0;
int suffixLength = suffix != null ? suffix.length() : 0;
StringBuilder sb = new StringBuilder(prefixLength + principal.length() + suffixLength);
if (prefixLength > 0) {
sb.append(prefix);
}
sb.append(principal);
if (suffixLength > 0) {
sb.append(suffix);
}
return sb.toString();
}
/**
* Sets the LdapContextFactory instance used to acquire connections to the LDAP directory during authentication
* attempts and authorization queries. Unless specified otherwise, the default is a {@link JndiLdapContextFactory}
* instance.
*
* @param contextFactory the LdapContextFactory instance used to acquire connections to the LDAP directory during
* authentication attempts and authorization queries
*/
@SuppressWarnings({"UnusedDeclaration"})
public void setContextFactory(LdapContextFactory contextFactory) {
this.contextFactory = contextFactory;
}
/**
* Returns the LdapContextFactory instance used to acquire connections to the LDAP directory during authentication
* attempts and authorization queries. Unless specified otherwise, the default is a {@link JndiLdapContextFactory}
* instance.
*
* @return the LdapContextFactory instance used to acquire connections to the LDAP directory during
* authentication attempts and authorization queries
*/
public LdapContextFactory getContextFactory() {
return this.contextFactory;
}
/*--------------------------------------------
| M E T H O D S |
============================================*/
/**
* Delegates to {@link #queryForAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken, LdapContextFactory)},
* wrapping any {@link NamingException}s in a Shiro {@link AuthenticationException} to satisfy the parent method
* signature.
*
* @param token the authentication token containing the user's principal and credentials.
* @return the {@link AuthenticationInfo} acquired after a successful authentication attempt
* @throws AuthenticationException if the authentication attempt fails or if a
* {@link NamingException} occurs.
*/
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
AuthenticationInfo info;
try {
info = queryForAuthenticationInfo(token, getContextFactory());
} catch (AuthenticationNotSupportedException e) {
String msg = "Unsupported configured authentication mechanism";
throw new UnsupportedAuthenticationMechanismException(msg, e);
} catch (javax.naming.AuthenticationException e) {
throw new AuthenticationException("LDAP authentication failed.", e);
} catch (NamingException e) {
String msg = "LDAP naming error while attempting to authenticate user.";
throw new AuthenticationException(msg, e);
}
return info;
}
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
AuthorizationInfo info;
try {
info = queryForAuthorizationInfo(principals, getContextFactory());
} catch (NamingException e) {
String msg = "LDAP naming error while attempting to retrieve authorization for user [" + principals + "].";
throw new AuthorizationException(msg, e);
}
return info;
}
/**
* Returns the principal to use when creating the LDAP connection for an authentication attempt.
* <p/>
* This implementation uses a heuristic: it checks to see if the specified token's
* {@link AuthenticationToken#getPrincipal() principal} is a {@code String}, and if so,
* {@link #getUserDn(String) converts it} from what is
* assumed to be a raw uid or username {@code String} into a User DN {@code String}. Almost all LDAP directories
* expect the authentication connection to present a User DN and not an unqualified username or uid.
* <p/>
* If the token's {@code principal} is not a String, it is assumed to already be in the format supported by the
* underlying {@link LdapContextFactory} implementation and the raw principal is returned directly.
*
* @param token the {@link AuthenticationToken} submitted during the authentication process
* @return the User DN or raw principal to use to acquire the LdapContext.
* @see LdapContextFactory#getLdapContext(Object, Object)
*/
protected Object getLdapPrincipal(AuthenticationToken token) {
Object principal = token.getPrincipal();
if (principal instanceof String) {
String sPrincipal = (String) principal;
return getUserDn(sPrincipal);
}
return principal;
}
/**
* This implementation opens an LDAP connection using the token's
* {@link #getLdapPrincipal(org.apache.shiro.authc.AuthenticationToken) discovered principal} and provided
* {@link AuthenticationToken#getCredentials() credentials}. If the connection opens successfully, the
* authentication attempt is immediately considered successful and a new
* {@link AuthenticationInfo} instance is
* {@link #createAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken, Object, Object, javax.naming.ldap.LdapContext) created}
* and returned. If the connection cannot be opened, either because LDAP authentication failed or some other
* JNDI problem, an {@link NamingException} will be thrown.
*
* @param token the submitted authentication token that triggered the authentication attempt.
* @param ldapContextFactory factory used to retrieve LDAP connections.
* @return an {@link AuthenticationInfo} instance representing the authenticated user's information.
* @throws NamingException if any LDAP errors occur.
*/
protected AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken token,
LdapContextFactory ldapContextFactory)
throws NamingException {
Object principal = token.getPrincipal();
Object credentials = token.getCredentials();
log.debug("Authenticating user '{}' through LDAP", principal);
principal = getLdapPrincipal(token);
LdapContext ctx = null;
try {
ctx = ldapContextFactory.getLdapContext(principal, credentials);
//context was opened successfully, which means their credentials were valid. Return the AuthenticationInfo:
return createAuthenticationInfo(token, principal, credentials, ctx);
} finally {
LdapUtils.closeContext(ctx);
}
}
/**
* Returns the {@link AuthenticationInfo} resulting from a Subject's successful LDAP authentication attempt.
* <p/>
* This implementation ignores the {@code ldapPrincipal}, {@code ldapCredentials}, and the opened
* {@code ldapContext} arguments and merely returns an {@code AuthenticationInfo} instance mirroring the
* submitted token's principal and credentials. This is acceptable because this method is only ever invoked after
* a successful authentication attempt, which means the provided principal and credentials were correct, and can
* be used directly to populate the (now verified) {@code AuthenticationInfo}.
* <p/>
* Subclasses however are free to override this method for more advanced construction logic.
*
* @param token the submitted {@code AuthenticationToken} that resulted in a successful authentication
* @param ldapPrincipal the LDAP principal used when creating the LDAP connection. Unlike the token's
* {@link AuthenticationToken#getPrincipal() principal}, this value is usually a constructed
* User DN and not a simple username or uid. The exact value is depending on the
* configured
* <a href="http://download-llnw.oracle.com/javase/tutorial/jndi/ldap/auth_mechs.html">
* LDAP authentication mechanism</a> in use.
* @param ldapCredentials the LDAP credentials used when creating the LDAP connection.
* @param ldapContext the LdapContext created that resulted in a successful authentication. It can be used
* further by subclasses for more complex operations. It does not need to be closed -
* it will be closed automatically after this method returns.
* @return the {@link AuthenticationInfo} resulting from a Subject's successful LDAP authentication attempt.
* @throws NamingException if there was any problem using the {@code LdapContext}
*/
@SuppressWarnings({"UnusedDeclaration"})
protected AuthenticationInfo createAuthenticationInfo(AuthenticationToken token, Object ldapPrincipal,
Object ldapCredentials, LdapContext ldapContext)
throws NamingException {
return new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), getName());
}
/**
* Method that should be implemented by subclasses to build an
* {@link AuthorizationInfo} object by querying the LDAP context for the
* specified principal.</p>
*
* @param principals the principals of the Subject whose AuthenticationInfo should be queried from the LDAP server.
* @param ldapContextFactory factory used to retrieve LDAP connections.
* @return an {@link AuthorizationInfo} instance containing information retrieved from the LDAP server.
* @throws NamingException if any LDAP errors occur during the search.
*/
protected AuthorizationInfo queryForAuthorizationInfo(PrincipalCollection principals,
LdapContextFactory ldapContextFactory) throws NamingException {
return null;
}
}
| {
"content_hash": "7e7b14b255ad55f59928d8056e26be21",
"timestamp": "",
"source": "github",
"line_count": 413,
"max_line_length": 139,
"avg_line_length": 53.78692493946731,
"alnum_prop": 0.6793013414963537,
"repo_name": "xuegongzi/rabbitframework",
"id": "f14219a9383545ddf886ae5bcd794aa55bdf0303",
"size": "23023",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rabbitframework-security-pom/rabbitframework-security/src/main/java/org/apache/shiro/realm/ldap/DefaultLdapRealm.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "212"
},
{
"name": "FreeMarker",
"bytes": "2474"
},
{
"name": "Java",
"bytes": "3279211"
},
{
"name": "Shell",
"bytes": "376"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe ItemSet do
it { should have_many(:item_types) }
before(:each) do
@item_sets = [mock_model(ItemSet), mock_model(ItemSet)]
@item_types = [mock_model(ItemType, :item_set => @item_sets[0]),
mock_model(ItemType, :item_set => @item_sets[0]),
mock_model(ItemType, :item_set => @item_sets[1]),
mock_model(ItemType, :item_set => @item_sets[1])]
@items = [mock_model(Item, :item_type => @item_types[0]),
mock_model(Item, :item_type => @item_types[0]),
mock_model(Item, :item_type => @item_types[1]),
mock_model(Item, :item_type => @item_types[2]),
mock_model(Item, :item_type => @item_types[2]),
mock_model(Item, :item_type => @item_types[3])]
@user = mock_model(User, :id => 1)
end
it "creates a hash with item types and items for a user" do
items = [@items[0], @items[1], @items[2]]
item_set = ItemSet.new(:id => 1, :item_types => [@item_types[0], @item_types[1]])
Item.should_receive(:find).with(:all, :conditions => ['user_id = ? AND item_types.item_set_id = ?', @user.id, item_set.id], :include => :item_type).and_return(items)
item_set.items_for(@user).should == {@item_types[0] => [@items[0], @items[1]], @item_types[1] => [@items[2]]}
end
it "creates a hash with item sets for a user" do
Item.should_receive(:find).with(:all, :conditions => {:user_id => @user.id}, :include => {:item_type => :item_set}).and_return(@items)
ItemSet.sets_for(@user).should == {@item_sets[0] => {@item_types[0] => [@items[0], @items[1]], @item_types[1] => [@items[2]]},
@item_sets[1] => {@item_types[2] => [@items[3], @items[4]], @item_types[3] => [@items[5]]}}
end
describe "calculating if the user has a full set" do
it "return false if at least one of items are missing" do
item_set = ItemSet.new
user = mock_model(User, :id => 1)
item_types = [stub_model(ItemType, :items => []), stub_model(ItemType, :items => []), stub_model(ItemType, :items => [])]
item_set.item_types = item_types
item_types[0].items.should_receive(:find).with(:first, :conditions => {:user_id => user.id, :used => true}).and_return(mock_model(Item))
item_types[1].items.should_receive(:find).with(:first, :conditions => {:user_id => user.id, :used => true}).and_return(mock_model(Item))
item_types[2].items.should_receive(:find).with(:first, :conditions => {:user_id => user.id, :used => true}).and_return(nil)
item_set.has_full_set(user).should be_false
end
it "return true if all items are present" do
item_set = ItemSet.new
user = mock_model(User, :id => 1)
item_types = [stub_model(ItemType, :items => []), stub_model(ItemType, :items => []), stub_model(ItemType, :items => [])]
item_set.item_types = item_types
item_types[0].items.should_receive(:find).with(:first, :conditions => {:user_id => user.id, :used => true}).and_return(mock_model(Item))
item_types[1].items.should_receive(:find).with(:first, :conditions => {:user_id => user.id, :used => true}).and_return(mock_model(Item))
item_types[2].items.should_receive(:find).with(:first, :conditions => {:user_id => user.id, :used => true}).and_return(mock_model(Item))
item_set.has_full_set(user).should be_true
end
end
it "knows how to apply a bonus" do
item_set = ItemSet.new
item_set.bonus_type = "some_kind_of_bonus"
user = mock_model(User, :some_kind_of_bonus => 2)
user.should_receive(:some_kind_of_bonus=).with(3)
user.should_receive(:save)
item_set.apply_bonus(user)
end
end
| {
"content_hash": "7d693160ba8132d8aef56159d7211cf1",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 169,
"avg_line_length": 54.43939393939394,
"alnum_prop": 0.6148065683273031,
"repo_name": "schouery/gametheorygame",
"id": "79d57bd3018a06bc0e1a0c7cbf9f381b0d390514",
"size": "3593",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/models/item_set_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "310100"
},
{
"name": "Ruby",
"bytes": "272846"
}
],
"symlink_target": ""
} |
<?php
/**
* This file is part of the Symfony2-coding-standard (phpcs standard)
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer-Symfony2
* @author wicliff wolda <dev@bloody-wicked.com>
* @license http://spdx.org/licenses/MIT MIT License
* @version GIT: master
* @link https://github.com/escapestudios/Symfony2-coding-standard
*/
/**
* Proyecto404CodingStandard_Sniffs_Objects_ObjectInstantiationSniff.
*
* Throws a warning if an object isn't instantiated using parenthesis.
*
* @category PHP
* @package PHP_CodeSniffer-Symfony2
* @author wicliff wolda <dev@bloody-wicked.com>
* @license http://spdx.org/licenses/MIT MIT License
* @link https://github.com/escapestudios/Symfony2-coding-standard
*/
class Proyecto404_Sniffs_Objects_ObjectInstantiationSniff implements PHP_CodeSniffer_Sniff
{
/**
* A list of tokenizers this sniff supports.
*
* @var array
*/
public $supportedTokenizers = array(
'PHP',
);
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(
T_NEW,
);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$allowed = array(
T_STRING,
T_NS_SEPARATOR,
);
$object = $stackPtr;
$line = $tokens[$object]['line'];
while ($object && $tokens[$object]['line'] === $line) {
$object = $phpcsFile->findNext($allowed, $object + 1);
if ($tokens[$object]['line'] === $line && !in_array($tokens[$object + 1]['code'], $allowed)) {
if ($tokens[$object + 1]['code'] !== T_OPEN_PARENTHESIS) {
$phpcsFile->addError(
'Use parentheses when instantiating classes',
$stackPtr,
'Invalid'
);
}
break;
}
}
}//end process()
}//end class
| {
"content_hash": "5f1da22054d2fbf2569b4f11475f0734",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 106,
"avg_line_length": 27.89010989010989,
"alnum_prop": 0.5401891252955082,
"repo_name": "proyecto404/coding-standard",
"id": "6e4be227946dbafe3a714c786461c500185588b5",
"size": "2538",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Proyecto404/Sniffs/Objects/ObjectInstantiationSniff.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "39030"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.