repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
NghiemTrung/livecli | src/livecli/plugins/garena.py | <gh_stars>1-10
import re
from livecli.plugin import Plugin
from livecli.plugin.api import http
from livecli.plugin.api import validate
from livecli.stream import HLSStream
__livecli_docs__ = {
"domains": [
"garena.live",
],
"geo_blocked": [],
"notes": "",
"live": True,
"vod": False,
"last_update": "2017-03-19",
}
_url_re = re.compile(r"https?\:\/\/garena\.live\/(?:(?P<channel_id>\d+)|(?P<alias>\w+))")
class Garena(Plugin):
API_INFO = "https://garena.live/api/channel_info_get"
API_STREAM = "https://garena.live/api/channel_stream_get"
_info_schema = validate.Schema(
{
"reply": validate.any({
"channel_id": int,
}, None),
"result": validate.text
}
)
_stream_schema = validate.Schema(
{
"reply": validate.any({
"streams": [
{
"url": validate.text,
"resolution": int,
"bitrate": int,
"format": int
}
]
}, None),
"result": validate.text
}
)
@classmethod
def can_handle_url(self, url):
return _url_re.match(url)
def _post_api(self, api, payload, schema):
res = http.post(api, json=payload)
data = http.json(res, schema=schema)
if data["result"] == "success":
post_data = data["reply"]
return post_data
def _get_streams(self):
match = _url_re.match(self.url)
if match.group("alias"):
payload = {"alias": match.group("alias")}
info_data = self._post_api(self.API_INFO, payload, self._info_schema)
channel_id = info_data["channel_id"]
elif match.group("channel_id"):
channel_id = int(match.group("channel_id"))
if channel_id:
payload = {"channel_id": channel_id}
stream_data = self._post_api(self.API_STREAM, payload, self._stream_schema)
for stream in stream_data["streams"]:
n = "{0}p".format(stream["resolution"])
if stream["format"] == 3:
s = HLSStream(self.session, stream["url"])
yield n, s
__plugin__ = Garena
|
chukanov/autometry | core/src/main/ru/autometry/obd/state/dump/ByteArraySerializer.java | <reponame>chukanov/autometry
package ru.autometry.obd.state.dump;
import ru.autometry.obd.state.OBDState;
import ru.autometry.obd.state.location.GSMLocation;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.Date;
/**
* Created by jeck on 08/09/16.
*/
public class ByteArraySerializer implements StateSerializer<byte[]> {
@Override
public byte[] serialize(OBDState state) throws Exception {
ByteArrayOutputStream baos = null;
DataOutputStream dos = null;
try {
baos = new ByteArrayOutputStream();
dos = new DataOutputStream(baos);
dos.writeByte(0);
dos.writeLong(state.getRevolutions());
dos.writeDouble(state.getDistance());
dos.writeDouble(state.getLiters());
dos.writeLong(state.getTime().getTime());
dos.writeLong(state.getStopTime());
dos.writeLong(state.getOnlineTime());
dos.writeByte(state.getErrors().length);
dos.writeInt(state.getSessionId());
if (state.getLocation()!=null) {
dos.writeShort(state.getLocation().getMcc());
dos.writeShort(state.getLocation().getMnc());
dos.writeInt(state.getLocation().getLac());
dos.writeInt(state.getLocation().getCid());
}
return baos.toByteArray();
} finally {
if (dos != null) dos.close();
if (baos != null) baos.close();
}
}
@Override
public OBDState load(byte[] bytes) throws Exception {
ByteArrayInputStream bais = null;
DataInputStream dis = null;
try {
bais = new ByteArrayInputStream(bytes);
dis = new DataInputStream(bais);
byte version = dis.readByte();
if (version != 0) throw new Exception("bad version: " + version);
OBDState state = new OBDState();
state.setRevolutions(dis.readLong());
state.setDistance(dis.readDouble());
state.setLiters(dis.readDouble());
state.setTime(new Date(dis.readLong()));
state.setStopTime(dis.readLong());
state.setOnlineTime(dis.readLong());
state.setErrors(new String[dis.readByte()]);
state.setSessionId(dis.readInt());
GSMLocation location = new GSMLocation();
state.setLocation(location);
try {
location.setMcc(dis.readShort());
location.setMnc(dis.readShort());
location.setLac(dis.readInt());
location.setCid(dis.readInt());
} catch (Exception e) {
state.setLocation(null);
}
return state;
} finally {
if (dis != null) dis.close();
if (bais != null) bais.close();
}
}
}
|
NullIsNot0/handsontable | test/unit/sortFunction/date.spec.js | import dateSort from 'handsontable/plugins/columnSorting/sortFunction/date';
it('dateSort comparing function shouldn\'t change order when comparing empty string, null and undefined', () => {
expect(dateSort(false, {})(['key1', null], ['key2', null])).toEqual(0);
expect(dateSort(false, {})(['key1', ''], ['key2', ''])).toEqual(0);
expect(dateSort(false, {})(['key1', undefined], ['key2', undefined])).toEqual(0);
expect(dateSort(false, {})(['key1', ''], ['key2', null])).toEqual(0);
expect(dateSort(false, {})(['key1', null], ['key2', ''])).toEqual(0);
expect(dateSort(false, {})(['key1', ''], ['key2', undefined])).toEqual(0);
expect(dateSort(false, {})(['key1', undefined], ['key2', ''])).toEqual(0);
expect(dateSort(false, {})(['key1', null], ['key2', undefined])).toEqual(0);
expect(dateSort(false, {})(['key1', undefined], ['key2', null])).toEqual(0);
});
|
thabok/A2LParser | src/main/java/net/alenzen/a2l/Coeffs.java | <gh_stars>0
package net.alenzen.a2l;
import java.io.IOException;
public class Coeffs implements IA2LWriteable {
private double a, b, c, d, e, f;
public double getA() {
return a;
}
public void setA(double a) {
this.a = a;
}
public double getB() {
return b;
}
public void setB(double b) {
this.b = b;
}
public double getC() {
return c;
}
public void setC(double c) {
this.c = c;
}
public double getD() {
return d;
}
public void setD(double d) {
this.d = d;
}
public double getE() {
return e;
}
public void setE(double e) {
this.e = e;
}
public double getF() {
return f;
}
public void setF(double f) {
this.f = f;
}
@Override
public void writeTo(A2LWriter writer) throws IOException {
writer.writelnSpaced("COEFFS", Double.toString(a), Double.toString(b), Double.toString(c), Double.toString(d),
Double.toString(e), Double.toString(f));
}
}
|
dnikishov/fuel-web | nailgun/nailgun/orchestrator/tasks_templates.py | <gh_stars>0
# -*- coding: utf-8 -*-
# Copyright 2014 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
from oslo_serialization import jsonutils
import requests
import six
from nailgun import consts
from nailgun.logger import logger
from nailgun.settings import settings
from nailgun.utils import debian
def make_upload_task(uids, data, path):
return {
'type': consts.ORCHESTRATOR_TASK_TYPES.upload_file,
'uids': uids,
'parameters': {
'path': path,
'data': data}}
def make_ubuntu_sources_task(uids, repo):
sources_content = 'deb {uri} {suite} {section}'.format(**repo)
sources_path = '/etc/apt/sources.list.d/{name}.list'.format(
name=repo['name'])
return make_upload_task(uids, sources_content, sources_path)
def make_ubuntu_preferences_task(uids, repo):
# NOTE(ikalnitsky): In order to implement the proper pinning,
# we have to download and parse the repo's "Release" file.
# Generally, that's not a good idea to make some HTTP request
# from Nailgun, but taking into account that this task
# will be executed in uWSGI's mule worker we can skip this
# rule, because proper pinning is more valuable thing right now.
template = '\n'.join([
'Package: *',
'Pin: release {conditions}',
'Pin-Priority: {priority}'])
preferences_content = []
try:
release = debian.get_release_file(repo, retries=3)
release = debian.parse_release_file(release)
pin = debian.get_apt_preferences_line(release)
except requests.exceptions.HTTPError as exc:
logger.error("Failed to fetch 'Release' file due to '%s'. "
"The apt preferences won't be applied for repo '%s'.",
six.text_type(exc), repo['name'])
return None
except Exception:
logger.exception("Failed to parse 'Release' file.")
return None
# NOTE(kozhukalov): When a package is available both in:
# 1) http://archive.ubuntu.com/ubuntu trusty universe
# 2) http://mirror.fuel-infra.org/mos-repos/ubuntu/7.0 mos7.0 main
# And if the content of the preferences file is (i.e. by section priority):
# Package: *
# Pin: release o=Mirantis, a=mos7.0, n=mos7.0, l=mos7.0, c=main
# Pin-Priority: 1050
# then the package available in MOS won't match the pin because for
# some reason apt still thinks this package is in universe section.
# As a result:
# # apt-cache policy ohai
# ohai:
# Installed: (none)
# Candidate: 6.14.0-2
# Version table:
# 6.14.0-2 0
# 500 http://10.20.0.1/mirror/ubuntu/ trusty/universe amd64 Packages
# 6.14.0-2~u14.04+mos1 0
# 500 http://10.20.0.2:8080/2015.1.0-7.0/ubuntu/x86_64/ mos7.0/main
# amd64 Packages
preferences_content.append(template.format(
conditions=pin,
priority=repo['priority']))
preferences_content = '\n\n'.join(preferences_content)
preferences_path = '/etc/apt/preferences.d/{0}.pref'.format(repo['name'])
return make_upload_task(uids, preferences_content, preferences_path)
def make_ubuntu_apt_disable_ipv6(uids):
config_content = 'Acquire::ForceIPv4 "true";\n'
config_path = '/etc/apt/apt.conf.d/05disable-ipv6'
return make_upload_task(uids, config_content, config_path)
def make_ubuntu_unauth_repos_task(uids):
# NOTE(kozhukalov): This task is to allow installing packages
# from unauthenticated repositories. Apt has special
# mechanism for this.
config_content = 'APT::Get::AllowUnauthenticated 1;\n'
config_path = '/etc/apt/apt.conf.d/02mirantis-allow-unsigned'
return make_upload_task(uids, config_content, config_path)
def make_centos_repo_task(uids, repo):
repo_content = [
'[{name}]',
'name=Plugin {name} repository',
'baseurl={uri}',
'gpgcheck=0',
]
if repo.get('priority'):
repo_content.append('priority={priority}')
repo_content = '\n'.join(repo_content).format(**repo)
repo_path = '/etc/yum.repos.d/{name}.repo'.format(name=repo['name'])
return make_upload_task(uids, repo_content, repo_path)
def make_sync_scripts_task(uids, src, dst):
return {
'type': consts.ORCHESTRATOR_TASK_TYPES.sync,
'uids': uids,
'parameters': {
'src': src,
'dst': dst}}
def make_shell_task(uids, task):
return {
'id': task.get('id'),
'type': consts.ORCHESTRATOR_TASK_TYPES.shell,
'uids': uids,
'parameters': {
'cmd': task['parameters']['cmd'],
'timeout': task['parameters']['timeout'],
'retries': task['parameters'].get(
'retries', settings.SHELL_TASK_RETRIES),
'interval': task['parameters'].get(
'interval', settings.SHELL_TASK_INTERVAL),
'cwd': task['parameters'].get('cwd', '/')}}
def make_yum_clean(uids):
task = {
'parameters': {
'cmd': 'yum clean all',
'timeout': 180}}
return make_shell_task(uids, task)
def make_apt_update_task(uids):
task = {
'parameters': {
'cmd': 'apt-get update',
'timeout': 1800}}
return make_shell_task(uids, task)
def make_puppet_task(uids, task):
return {
'id': task.get('id'),
'type': consts.ORCHESTRATOR_TASK_TYPES.puppet,
'uids': uids,
'parameters': {
'puppet_manifest': task['parameters']['puppet_manifest'],
'puppet_modules': task['parameters']['puppet_modules'],
'timeout': task['parameters']['timeout'],
'retries': task['parameters'].get('retries'),
'cwd': task['parameters'].get('cwd', '/')}}
def make_generic_task(uids, task):
task = {
'id': task.get('id'),
'type': task['type'],
'uids': uids,
'fail_on_error': task.get('fail_on_error', True),
'parameters': task['parameters']
}
task['parameters'].setdefault('cwd', '/')
return task
def make_reboot_task(uids, task):
return {
'id': task.get('id'),
'type': consts.ORCHESTRATOR_TASK_TYPES.reboot,
'uids': uids,
'parameters': {
'timeout': task['parameters']['timeout']}}
def make_provisioning_images_task(
uids, repos, provision_data, cid, packages):
conf = {
'repos': repos,
'image_data': provision_data['image_data'],
'codename': provision_data['codename'],
'output': settings.PROVISIONING_IMAGES_PATH,
}
if packages:
conf['packages'] = packages
# TODO(ikalnitsky):
# Upload settings before using and pass them as command line argument.
conf = jsonutils.dumps(conf)
return make_shell_task(uids, {
'parameters': {
'cmd': ("fa_build_image "
"--image_build_dir /var/lib/fuel/ibp "
"--log-file /var/log/fuel-agent-env-{0}.log "
"--data_driver nailgun_build_image "
"--input_data '{1}'").format(cid, conf),
'timeout': settings.PROVISIONING_IMAGES_BUILD_TIMEOUT,
'retries': 1}})
def generate_ironic_bootstrap_keys_task(uids, cid):
cmd = "/etc/puppet/modules/osnailyfacter/modular/astute/generate_keys.sh"
return make_shell_task(uids, {
'parameters': {
'cmd': (
"sh {cmd} "
"-i {cid} "
"-s 'ironic' "
"-p /var/lib/fuel/keys/ ").format(
cid=cid,
cmd=cmd),
'timeout': 180,
'retries': 1}})
def make_ironic_bootstrap_task(uids, cid):
extra_conf_files = "/usr/share/ironic-fa-bootstrap-configs/"
ssh_keys = "/var/lib/fuel/keys/{0}/ironic/ironic.pub".format(cid)
log_file = "/var/log/fuel-ironic-bootstrap-image-build.log"
ironic_bootstrap_pkgs = ' '.join(
"--package '{0}'".format(pkg) for pkg in consts.IRONIC_BOOTSTRAP_PKGS)
bootstrap_path = "/var/www/nailgun/bootstrap/ironic/{cid}/".format(
cid=cid)
return make_shell_task(uids, {
'parameters': {
'cmd': (
"test -e {bootstrap_path}vmlinuz || "
"(fuel-bootstrap build {ironic_bootstrap_pkgs} "
"--root-ssh-authorized-file {bootstrap_ssh_keys} "
"--output-dir {bootstrap_path} "
"--extra-dir {extra_conf_files} --no-compress "
'--no-default-extra-dirs --no-default-packages '
'--log-file {log_file})').format(
cid=cid,
extra_conf_files=extra_conf_files,
bootstrap_ssh_keys=ssh_keys,
ironic_bootstrap_pkgs=ironic_bootstrap_pkgs,
bootstrap_path=bootstrap_path,
log_file=log_file),
'timeout': settings.PROVISIONING_IMAGES_BUILD_TIMEOUT,
'retries': 1}})
def make_download_debian_installer_task(
uids, repos, installer_kernel, installer_initrd):
# NOTE(kozhukalov): This task is going to go away by 7.0
# because we going to get rid of classic way of provision.
# NOTE(ikalnitsky): We can't use urljoin here because it works
# pretty bad in cases when 'uri' doesn't have a trailing slash.
remote_kernel = os.path.join(
repos[0]['uri'], installer_kernel['remote_relative'])
remote_initrd = os.path.join(
repos[0]['uri'], installer_initrd['remote_relative'])
return make_shell_task(uids, {
'parameters': {
'cmd': ('LOCAL_KERNEL_FILE={local_kernel} '
'LOCAL_INITRD_FILE={local_initrd} '
'download-debian-installer '
'{remote_kernel} {remote_initrd}').format(
local_kernel=installer_kernel['local'],
local_initrd=installer_initrd['local'],
remote_kernel=remote_kernel,
remote_initrd=remote_initrd),
'timeout': 10 * 60,
'retries': 1}})
def make_noop_task(uids, task):
"""Creates NoOp task for astute.
:param
:param task: the task instance
"""
return {
'id': task.get('id'),
'type': consts.ORCHESTRATOR_TASK_TYPES.skipped,
'uids': uids,
'fail_on_error': False
}
|
EN-IH-WDPT-JUN21/tEapot-Microservices-CRM | LeadService/src/main/java/com/ironhack/leadservice/dto/LeadDto.java | <gh_stars>0
package com.ironhack.leadservice.dto;
import com.ironhack.leadservice.dao.Lead;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.validation.constraints.Email;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.util.Optional;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class LeadDto {
private Long id;
@Pattern(regexp = "^([a-zA-Z]{2,}\\s[a-zA-Z]{1,}'?-?[a-zA-Z]{2,}\\s?([a-zA-Z]{1,})?)")
private String name;
@Pattern(regexp = "(^$|[0-9]{10})")
private String phoneNumber;
@Email(regexp = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$")
private String email;
@NotBlank
private String companyName;
private SalesRepDto salesRep;
public LeadDto(String name, String phoneNumber, String email, String companyName, SalesRepDto salesRep) {
this.name = name;
this.phoneNumber = phoneNumber;
this.email = email;
this.companyName = companyName;
this.salesRep = salesRep;
}
public LeadDto(Optional<Lead> existingLead) {
this.name = existingLead.get().getName();
this.phoneNumber = existingLead.get().getPhoneNumber();
this.email = existingLead.get().getEmail();
this.companyName = existingLead.get().getCompanyName();
this.salesRep = new SalesRepDto(existingLead.get().getSalesRepId());
}
}
|
jiashiwen/redissyncer-portal | utils/GenRandIP.go | package utils
import (
"fmt"
"math/rand"
"time"
)
// 随机生成合法 IP,如: 172.16.31.10
func RandomIp() string {
// IP 范围二维数组
ranges := ipRange()
idx := newRand().Intn(10)
return numToIp(ranges[idx][0] + newRand().Intn(ranges[idx][1]-ranges[idx][0]))
}
// 随机生成(隐蔽后两位的)合法 IP,如: 222.16.*.*
func RandomOmicIp() string {
// IP 范围二维数组
ranges := ipRange()
idx := newRand().Intn(10)
return numToOmicIp(ranges[idx][0] + newRand().Intn(ranges[idx][1]-ranges[idx][0]))
}
func numToIp(num int) string {
arr := make([]int, 4)
arr[0] = (num >> 24) & 0xff
arr[1] = (num >> 16) & 0xff
arr[2] = (num >> 8) & 0xff
arr[3] = num & 0xff
return fmt.Sprintf("%d.%d.%d.%d", arr[0], arr[1], arr[2], arr[3])
}
func numToOmicIp(num int) string {
arr := make([]int, 2)
arr[0] = (num >> 24) & 0xff
arr[1] = (num >> 16) & 0xff
return fmt.Sprintf("%d.%d.*.*", arr[0], arr[1])
}
// IP 范围二维数组
func ipRange() [][]int {
return [][]int{{607649792, 608174079}, //172.16.58.3-172.16.17.32
{1038614528, 1039007743}, //172.16.31.10-61.237.255.255
{1783627776, 1784676351}, //192.168.3.11-106.95.255.255
{2035023872, 2035154943}, //172.16.17.32-121.77.255.255
{2078801920, 2079064063}, //172.16.31.10-123.235.255.255
{-1950089216, -1948778497}, //192.168.127.12-139.215.255.255
{-1425539072, -1425014785}, //172.16.17.32-171.15.255.255
{-1236271104, -1235419137}, //192.168.127.12-182.92.255.255
{-770113536, -768606209}, //172.16.17.32-210.47.255.255
{-569376768, -564133889}, //172.16.31.10-222.95.255.255
}
}
// 实例化随机数结构体,源为时间微秒
func newRand() *rand.Rand {
return rand.New(rand.NewSource(time.Now().UnixNano()))
}
|
macor003/desarrollosAndroid | ProyectosCajaRegistrador/CRUtils/src/main/java/com/becoblohm/cr/utils/CRUtils.java | <filename>ProyectosCajaRegistrador/CRUtils/src/main/java/com/becoblohm/cr/utils/CRUtils.java<gh_stars>0
/*******************************************************************************
* © 2012 Global Retail Information Ltd.
******************************************************************************/
package com.becoblohm.cr.utils;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.Normalizer;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.Vector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.becoblohm.cr.models.Article;
import com.becoblohm.cr.types.CRBigDecimal;
/**
*/
public class CRUtils {
/**
* Field logger.
*/
private static final Logger logger = LoggerFactory.getLogger(CRUtils.class);
/**
* Method buildPropertiesVector.
*
* @param properties
* String
* @return Vector
*/
public static Vector buildPropertiesVector(String properties) {
Vector result = new Vector();
StringTokenizer tk = new StringTokenizer(properties, ",");
while (tk.hasMoreTokens()) {
String tmp = tk.nextToken();
result.add(tmp.trim());
}
return result;
}
/**
* Method buildPropertiesHashVectorDecision.
*
* @param properties
* String
* @return HashMap
*/
public static HashMap buildPropertiesHashVectorDecision(String properties) {
StringTokenizer tk = new StringTokenizer(properties, ":");
HashMap result = new HashMap();
String key = null;
String value = null;
Vector decision = null;
while (tk.hasMoreTokens()) {
String tmp = tk.nextToken();
StringTokenizer keys = new StringTokenizer(tmp, "@");
key = null;
value = null;
decision = null;
if (keys.hasMoreTokens()) {
key = keys.nextToken();
}
if (keys.hasMoreTokens()) {
value = keys.nextToken();
decision = new Vector();
StringTokenizer des = new StringTokenizer(value, ",");
while (des.hasMoreTokens()) {
String val = des.nextToken();
decision.add(val);
}
}
if (key != null && decision != null) {
result.put(key.trim(), decision);
}
}
return result;
}
/**
* Method buildPropertiesHashDecision.
*
* @param properties
* String
* @return HashMap
*/
public static HashMap buildPropertiesHashDecision(String properties) {
StringTokenizer tk = new StringTokenizer(properties, ",");
HashMap result = new HashMap();
while (tk.hasMoreTokens()) {
String tmp = tk.nextToken();
StringTokenizer keys = new StringTokenizer(tmp, "@");
String key = null;
String value = null;
if (keys.hasMoreTokens()) {
key = keys.nextToken();
}
if (keys.hasMoreTokens()) {
value = keys.nextToken();
}
if (key != null && value != null) {
result.put(key.trim(), value.trim());
}
}
return result;
}
/**
* Method findResource.
*
* @param resource
* String
* @param defaultPath
* String
* @param clase
* Class
*
*
*
* @return URL * @throws MalformedURLException
*/
public static URL findResource(final String resource, String defaultPath, final Class clase) {
URL propURL = null;
propURL = Thread.currentThread().getContextClassLoader().getResource(resource);
if (propURL != null) {
logger.debug("Encontrado recurso: " + resource + " en ContextClassLoader del Thread");
}
if (propURL == null) {
String propsFile = System.getProperty("user.home") + File.separator + resource;
File file = new File(propsFile);
if (file.exists() && file.isFile()) {
try {
propURL = file.toURL();
} catch (MalformedURLException e) {
e.printStackTrace();
}
} else {
propURL = null;
}
if (propURL != null) {
logger.debug("Encontrado recurso en user.home: " + propsFile);
}
}
// Busco en la ruta por defecto
if (propURL == null && defaultPath != null) {
if (defaultPath.length() > 0 && defaultPath.charAt(defaultPath.length() - 1) != '/'
&& defaultPath.charAt(defaultPath.length() - 1) != '\\') {
defaultPath = defaultPath.concat(File.separator);
}
File propsFile = new File(defaultPath + resource);
if (propsFile.exists() && propsFile.isFile()) {
try {
propURL = propsFile.toURL();
} catch (MalformedURLException e) {
e.printStackTrace();
}
} else {
propURL = null;
}
if (propURL != null) {
logger.debug("Encontrado recurso en defaultPath: " + propsFile);
}
}
if (propURL == null) {
File propsFile = new File(resource);
if (propsFile.exists() && propsFile.isFile()) {
try {
propURL = propsFile.toURL();
} catch (MalformedURLException e) {
e.printStackTrace();
}
} else {
propURL = null;
}
if (propURL != null) {
logger.debug("Encontrado recurso en user.dir: " + propsFile);
}
}
// Busco como recurso del sistema en el classLoader de esta clase
if (clase != null) {
if (propURL == null) {
propURL = clase.getClassLoader().getResource(resource);
if (propURL != null) {
logger.debug("Encontrado recurso en ClassLoader de la Clase '" + clase.getPackage().getName() + "."
+ clase.getName() + "': " + propURL);
}
}
// Busco como recurso del sistema en el classpath
if (propURL == null) {
propURL = clase.getResource(resource);
if (propURL != null) {
logger.debug("Encontrado recurso en ClassPath de la Clase '" + clase.getPackage().getName() + "."
+ clase.getName() + "': " + propURL);
}
}
}
// Busco como recurso del sistema en el classLoader de esta clase
if (propURL == null) {
propURL = CRUtils.class.getClassLoader().getResource(resource);
if (propURL != null) {
logger.debug("Encontrado recurso en ClassLoader del EpaComun: " + propURL);
}
}
// Busco como recurso del sistema en el classpath
if (propURL == null) {
propURL = CRUtils.class.getResource(resource);
if (propURL != null) {
logger.debug("Encontrado recurso en Class del EpaComun: " + propURL);
}
}
// Busco como recurso del sistema en el classpath
if (propURL == null) {
propURL = ClassLoader.getSystemResource(resource);
if (propURL != null) {
logger.debug("Encontrado recurso en ClassLoader.getSystemResource: " + propURL);
}
}
if (propURL == null) {
logger.debug("NO SE ENCONTRO RECURSO: " + resource);
}
return propURL;
}
/**
* Method removeSpecialChars.
*
* @param text
* String
* @return String
*/
public static String removeSpecialChars(String text) {
return removeSpecialChars(text, "");
}
/**
* Compares if two dates belong to the same day
*
* @param date1
* Date
* @param date2
* Date
* @return boolean
*/
public static boolean isSameDay(Date date1, Date date2) {
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
boolean sameDay = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
&& cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);
return sameDay;
}
/**
* Method bigdecimalToCalendar.
*
* @param date
* String
* @return Calendar
*/
public static Calendar bigdecimalToCalendar(String date) {
Calendar calendar = Calendar.getInstance();
String dateStr = date;
String year = dateStr.substring(0, 4);
String month = dateStr.substring(4, 6);
String day = dateStr.substring(6, 8);
String hour = dateStr.substring(8, 10);
String minute = dateStr.substring(10, 12);
String second = dateStr.substring(12, 14);
String milli = dateStr.substring(15, dateStr.length());
calendar.set(Calendar.YEAR, Integer.parseInt(year));
calendar.set(Calendar.MONTH, Integer.parseInt(month) - 1);
calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day));
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour));
calendar.set(Calendar.MINUTE, Integer.parseInt(minute));
calendar.set(Calendar.SECOND, Integer.parseInt(second));
// calendar.set(Calendar.MILLISECOND, Integer.parseInt(milli));
// SimpleDateFormat sdf = new
// SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SS");
// String fecha = sdf.format(calendar.getTime());
// logger.debug(fecha);
return calendar;
}
/**
* Compares if two dates belong to the same month
*
* @param date1
* Date
* @param date2
* Date
* @return int
*/
public static int compareMonths(Date date1, Date date2) {
int response;
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
if (cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)) {
if (cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH)) {
response = 0;
} else if (cal1.get(Calendar.MONTH) > cal2.get(Calendar.MONTH)) {
response = 1;
} else {
response = -1;
}
} else if (cal1.get(Calendar.YEAR) > cal2.get(Calendar.YEAR)) {
response = 1;
} else {
response = -1;
}
return response;
}
/*
* public static String getEncoded(String texto, String algoritmo) { String
* output=""; try { byte[] textBytes = texto.getBytes(); MessageDigest md =
* MessageDigest.getInstance(algoritmo); md.update(textBytes); byte[] codigo =
* md.digest(); output = new String(codigo); } catch (NoSuchAlgorithmException
* ex) { logger.warn(ex.toString()); } logger.debug("encoded "+output); return
* output; }
*/
/**
* Field HEXADECIMAL.
*/
private static final char[] HEXADECIMAL = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f' };
/**
* Method encode.
*
* @param stringToHash
* String
* @return String
*/
public static String encode(String stringToHash) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytes = md.digest(stringToHash.getBytes());
StringBuilder sb = new StringBuilder(2 * bytes.length);
int low = 0;
int high = 0;
for (int i = 0; i < bytes.length; i++) {
low = (bytes[i] & 0x0f);
high = ((bytes[i] & 0xf0) >> 4);
sb.append(HEXADECIMAL[high]);
sb.append(HEXADECIMAL[low]);
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
// exception handling goes here
return null;
}
}
/**
* Method removeSpecialChars.
*
* @param text
* String
* @param regex
* String
* @return String
*/
public static String removeSpecialChars(String text, String regex) {
String alphaOnly = "[^a-zA-Z]+";
String alphaAndDigits = "[^a-zA-Z0-9]+";
String ascii = "[^\\p{ASCII}" + regex + "]";
String strippedString = new String();
strippedString = Normalizer.normalize(text, Normalizer.Form.NFD).replaceAll(ascii, "");
// logger.debug("Texto normalizado" + strippedString);
strippedString = strippedString.replaceAll(ascii, "");
// logger.debug("Texto con ascii remplazado" + strippedString);
return strippedString;
}
/**
* Method getDaysUntilToday.
*
* @param date
* Date
* @return long
*/
public static long getDaysUntilToday(Date date) {
logger.debug("Validando diferencia en dias desde: " + date);
final long MILLSECS_PER_DAY = 24 * 60 * 60 * 1000; // Milisegundos al
// día
long diferencia = (new Date().getTime() - date.getTime()) / MILLSECS_PER_DAY;
logger.debug("diferencia: " + diferencia);
return diferencia;
}
/**
* Method generateIpaId.
*
* @param store
* Long
* @param pos
* Long
* @return long
*/
public static long generateIpaId(Integer store, Integer pos) {
if (store == null)
store = 0;
if (pos == null)
pos = 0;
return Long
.valueOf("" + System.currentTimeMillis() + String.format("%02d", store) + String.format("%02d", pos));
}
/**
* Method generateIpaId.
*
* @return long
*/
public static long generateIpaId() {
return generateIpaId(null, null);
}
public static long generateIpaIdComparison(Integer store, Integer pos) {
return Long.valueOf("" + generateIpaId(store, pos) + String.format("%02d", 0));
}
/**
* Valida la cantidad que la cantidad a agregar de una articulo no sobrepase el
* maximo pertido por trasaccion
*
* @param article
* Article articulo al que se le va a aunmentar la cantidad en la
* venta
* @param quantity
* CRBigDecimal cantidad
* @return boolean true si la contidad de articulos es menor o igual que la
* cantidad configurada por transaccion y false en caso contrario
*/
public static boolean validateTransaccionItems(Article article, CRBigDecimal quantity) {
logger.debug("validando cantiad de articulos por transaccion ");
if (article.getBuyPeriod() != 0) {
logger.debug("periodo es distinto de cero");
if (article.getAmountMaxTransaction().compareTo(quantity) < 0) {
return false;
}
}
return true;
}
public static boolean dateIsBetween(Date datetoBeCompared, Date from, Date to) {
return from.compareTo(datetoBeCompared) * datetoBeCompared.compareTo(to) > 0;
}
}
|
893930581/DSofGO | ALG/leetcode/84largest_rectangle_in_histogram/main.go | <gh_stars>0
package main
func largestRectangleArea(heights []int) int {
n := len(heights)
maxS := 0
for i := 0; i < n; i++ {
if i != 0 && heights[i] < heights[i-1] {
continue
}
minY := heights[i]
for j := i; j < n; j++ {
x := j - i + 1
if minY > heights[j] {
minY = heights[j]
}
maxS = max(maxS, x*minY)
}
}
return maxS
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func main() {}
|
avilcheslopez/geopm | service/test/MockSDBus.hpp | /*
* Copyright (c) 2015 - 2022, Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef MOCKSDBUS_HPP_INCLUDE
#define MOCKSDBUS_HPP_INCLUDE
#include "gmock/gmock.h"
#include "SDBus.hpp"
class MockSDBus : public geopm::SDBus
{
public:
MOCK_METHOD(std::shared_ptr<geopm::SDBusMessage>, call_method,
(std::shared_ptr<geopm::SDBusMessage> message), (override));
MOCK_METHOD(std::shared_ptr<geopm::SDBusMessage>, call_method,
(const std::string &member), (override));
MOCK_METHOD(std::shared_ptr<geopm::SDBusMessage>, call_method,
(const std::string &member,
const std::string &arg0, int arg1, int arg2), (override));
MOCK_METHOD(std::shared_ptr<geopm::SDBusMessage>, call_method,
(const std::string &member,
const std::string &arg0, int arg1, int arg2, double arg3),
(override));
MOCK_METHOD(std::shared_ptr<geopm::SDBusMessage>, call_method,
(const std::string &member, int arg0),
(override));
MOCK_METHOD(std::shared_ptr<geopm::SDBusMessage>, make_call_message,
(const std::string &member), (override));
};
#endif
|
rfarhanian/cs-review | cs-ctci/src/main/java/com/mmnaseri/cs/ctci/ch02/p05/LinkAdder.java | package com.mmnaseri.cs.ctci.ch02.p05;
import com.mmnaseri.cs.ctci.ch02.SinglyLinkedNode;
/**
* @author <NAME> (<EMAIL>)
* @since 1.0 (11/25/16, 2:37 PM)
*/
public interface LinkAdder {
<N extends SinglyLinkedNode<Integer, N>> SinglyLinkedNode<Integer, ?> add(N first, N second);
}
|
Intelligent-Systems-Lab/ISL-BCFL | data/mnist.py | <gh_stars>0
import os
import sys
import struct
import argparse
import pandas as pd
import random
import math
import numpy as np
from tqdm import tqdm
parser = argparse.ArgumentParser()
parser.add_argument('--data', type=str, default=None)
parser.add_argument('--n', type=int, default=5)
parser.add_argument('--format', type=str, default='csv', help="[csv, pickle]")
parser.add_argument('-f')
def get_dict_idx():
d = {0:"label"}
count = 1
for i in range(1, 29):
for j in range(1, 29):
d[count] = "{}x{}".format(i, j)
count += 1
return d
args = parser.parse_args()
X = pd.read_csv(args.data + "/mnist_train.csv")
num_package = args.n
# X_test = pd.read_csv("/Users/tonyguo/Desktop/mnist/mnist-in-csv/mnist_test.csv")
X_df = pd.DataFrame(X)
Xf_all_list = []
train_data = X_df.values.tolist()
for i in range(10):
Xf_all_list.append([])
for i in tqdm(range(len(train_data))):
Xf_all_list[train_data[i][0]].append(train_data[i])
packages = []
for i in tqdm(range(num_package)):
list_of_containt = []
for k in range(10):
Xp = Xf_all_list[k]
u = math.floor(len(Xp) / num_package) * i
d = math.floor(len(Xp) / num_package) * (i + 1)
if i == (num_package - 1):
list_of_containt = list_of_containt + Xf_all_list[k][u:]
else:
list_of_containt = list_of_containt + Xf_all_list[k][u:d]
random.shuffle(list_of_containt)
packages.append(list_of_containt)
# for p in range(len(packages)):
# pk = pd.concat(packages[p])
# pk = pk.sample(frac=1).reset_index(drop=True)
# del pk["index"]
# if args.format == "pickle":
# save_path = args.data+"/mnist_train_{}.p".format(p)
# print("Create : mnist_train_{}.p".format(p))
# pk.to_pickle(save_path)
# else:
# save_path = args.data+"/mnist_train_{}.csv".format(p)
# print("Create : mnist_train_{}.csv".format(p))
# pk.to_csv(save_path,mode = 'w', index=False)
for p in range(len(packages)):
df = pd.DataFrame(data=packages[p])
df = df.rename(columns=get_dict_idx())
if args.format == "pickle":
save_path = args.data + "/mnist_train_{}.p".format(p)
print("Create : mnist_train_{}.p".format(p))
df.to_pickle(save_path)
else:
save_path = args.data + "/mnist_train_{}.csv".format(p)
print("Create : mnist_train_{}.csv".format(p))
df.to_csv(save_path, mode='w', index=False)
|
shiniwat/sdl_javascript_suite | lib/js/src/rpc/messages/DeleteWindow.js | <filename>lib/js/src/rpc/messages/DeleteWindow.js
/* eslint-disable camelcase */
/*
* Copyright (c) 2020, SmartDeviceLink Consortium, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of the SmartDeviceLink Consortium Inc. nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import { FunctionID } from '../enums/FunctionID.js';
import { RpcRequest } from '../RpcRequest.js';
/**
* Deletes previously created window of the SDL application.
*/
class DeleteWindow extends RpcRequest {
/**
* Initalizes an instance of DeleteWindow.
* @class
* @param {object} parameters - An object map of parameters.
* @since SmartDeviceLink 6.0.0
*/
constructor (parameters) {
super(parameters);
this.setFunctionId(FunctionID.DeleteWindow);
}
/**
* Set the WindowID
* @param {Number} id - A unique ID to identify the window. The value of '0' will always be the default main window on the main display and cannot be deleted. See PredefinedWindows enum. - The desired WindowID.
* @returns {DeleteWindow} - The class instance for method chaining.
*/
setWindowID (id) {
this.setParameter(DeleteWindow.KEY_WINDOW_ID, id);
return this;
}
/**
* Get the WindowID
* @returns {Number} - the KEY_WINDOW_ID value
*/
getWindowID () {
return this.getParameter(DeleteWindow.KEY_WINDOW_ID);
}
}
DeleteWindow.KEY_WINDOW_ID = 'windowID';
export { DeleteWindow }; |
DogIsMe/myvtk9.03 | ThirdParty/vtkm/vtkvtkm/vtk-m/vtkm/worklet/testing/UnitTestSplatKernels.cxx | <filename>ThirdParty/vtkm/vtkvtkm/vtk-m/vtkm/worklet/testing/UnitTestSplatKernels.cxx
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//============================================================================
#include <iostream>
#include <vector>
#include <vtkm/cont/testing/Testing.h>
#include <vtkm/worklet/splatkernels/Gaussian.h>
#include <vtkm/worklet/splatkernels/Spline3rdOrder.h>
using Vector = vtkm::Vec3f_64;
// Simpson integradion rule
double SimpsonIntegration(const std::vector<double>& y, const std::vector<double>& x)
{
std::size_t n = x.size() - 1;
const double aux = 2. * (x[n] - x[0]) / (3. * static_cast<double>(n));
double val = 0.5 * (y[0] * x[0] + y[n] * x[n]);
for (std::size_t i = 2; i < n; i += 2)
{
val += 2 * y[i - 1] + y[i];
}
val += 2 * y[n - 1];
return aux * val;
}
// Integrade a kernel in 3D
template <typename Kernel>
double IntegralOfKernel(const Kernel& ker)
{
const double supportlength = ker.maxDistance();
const int npoint = 15000;
std::vector<double> x;
std::vector<double> y;
for (int i = 0; i < npoint; i++)
{
const double r = static_cast<double>(i) * supportlength / static_cast<double>(npoint);
x.push_back(r);
y.push_back(ker.w(r) * r * r);
}
return 4.0 * M_PI * SimpsonIntegration(y, x);
}
// Same integration, but using the variable smoothing length interface
template <typename Kernel>
double IntegralOfKernel(const Kernel& ker, double h)
{
const double supportlength = ker.maxDistance();
const int npoint = 15000;
std::vector<double> x;
std::vector<double> y;
for (int i = 0; i < npoint; i++)
{
const double r = static_cast<double>(i) * supportlength / static_cast<double>(npoint);
x.push_back(r);
y.push_back(ker.w(h, r) * r * r);
}
return 4.0 * M_PI * SimpsonIntegration(y, x);
}
int TestSplatKernels()
{
const double eps = 1e-4;
double s;
double smoothinglength;
std::cout << "Testing Gaussian 3D fixed h kernel integration \n";
for (int i = 0; i < 100; ++i)
{
smoothinglength = 0.01 + i * (10.0 / 100.0);
s = IntegralOfKernel(vtkm::worklet::splatkernels::Gaussian<3>(smoothinglength));
VTKM_TEST_ASSERT(fabs(s - 1.0) < eps, "Gaussian 3D integration failure");
}
std::cout << "Testing Gaussian 3D variable h kernel integration \n";
for (int i = 0; i < 100; ++i)
{
smoothinglength = 0.01 + i * (10.0 / 100.0);
s =
IntegralOfKernel(vtkm::worklet::splatkernels::Gaussian<3>(smoothinglength), smoothinglength);
VTKM_TEST_ASSERT(fabs(s - 1.0) < eps, "Gaussian 3D integration failure");
}
// s = IntegralOfKernel(vtkm::worklet::splatkernels::Gaussian<2>(smoothinglength));
// VTKM_TEST_ASSERT ( fabs(s - 1.0) < eps, "Gaussian 2D integration failure");
std::cout << "Testing Spline3rdOrder 3D kernel integration \n";
for (int i = 0; i < 100; ++i)
{
smoothinglength = 0.01 + i * (10.0 / 100.0);
s = IntegralOfKernel(vtkm::worklet::splatkernels::Spline3rdOrder<3>(smoothinglength));
VTKM_TEST_ASSERT(fabs(s - 1.0) < eps, "Spline3rdOrder 3D integration failure");
}
// s = IntegralOfKernel(vtkm::worklet::splatkernels::Spline3rdOrder<2>(smoothinglength));
// VTKM_TEST_ASSERT ( fabs(s - 1.0) < eps, "Spline3rdOrder 2D integration failure");
/*
s = IntegralOfKernel(KernelBox(ndim, smoothinglength));
if ( fabs(s - 1.0) > eps) {
return EXIT_FAILURE;
}
s = IntegralOfKernel(KernelCusp(ndim, smoothinglength));
if ( fabs(s - 1.0) > eps) {
return EXIT_FAILURE;
}
s = IntegralOfKernel(KernelGaussian(ndim, smoothinglength));
if ( fabs(s - 1.0) > eps) {
return EXIT_FAILURE;
}
s = IntegralOfKernel(KernelQuadratic(ndim, smoothinglength));
if ( fabs(s - 1.0) > eps) {
return EXIT_FAILURE;
}
s = IntegralOfKernel(KernelSpline3rdOrder(ndim, smoothinglength));
if ( fabs(s - 1.0) > eps) {
return EXIT_FAILURE;
}
s = IntegralOfKernel(KernelSpline5thOrder(ndim, smoothinglength));
if ( fabs(s - 1.0) > eps) {
return EXIT_FAILURE;
}
s = IntegralOfKernel(KernelWendland(ndim, smoothinglength));
if ( fabs(s - 1.0) > eps) {
return EXIT_FAILURE;
}
*/
return EXIT_SUCCESS;
}
int UnitTestSplatKernels(int argc, char* argv[])
{
return vtkm::cont::testing::Testing::Run(TestSplatKernels, argc, argv);
}
|
dmj/jing-trang | mod/xsd-datatype/src/main/com/thaiopensource/datatype/xsd/FloatDatatype.java | package com.thaiopensource.datatype.xsd;
import org.relaxng.datatype.ValidationContext;
class FloatDatatype extends DoubleDatatype {
Object getValue(String str, ValidationContext vc) {
if (str.equals("INF"))
return Float.POSITIVE_INFINITY;
if (str.equals("-INF"))
return Float.NEGATIVE_INFINITY;
if (str.equals("NaN"))
return Float.NaN;
return new Float(str);
}
public boolean isLessThan(Object obj1, Object obj2) {
return (Float)obj1 < (Float)obj2;
}
public boolean sameValue(Object value1, Object value2) {
float f1 = (Float)value1;
float f2 = (Float)value2;
// NaN = NaN
return f1 == f2 || (f1 != f1 && f2 != f2);
}
}
|
karthikrameskum/motech | platform/server-config/src/test/java/org/motechproject/config/monitor/ConfigFileMonitorTest.java | <reponame>karthikrameskum/motech<gh_stars>1-10
package org.motechproject.config.monitor;
import org.apache.commons.vfs2.FileChangeEvent;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.VFS;
import org.apache.commons.vfs2.impl.DefaultFileMonitor;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.motechproject.config.core.MotechConfigurationException;
import org.motechproject.config.core.domain.BootstrapConfig;
import org.motechproject.config.core.domain.ConfigLocation;
import org.motechproject.config.core.domain.ConfigSource;
import org.motechproject.config.core.service.CoreConfigurationService;
import org.motechproject.config.service.ConfigurationService;
import org.motechproject.server.config.service.ConfigLoader;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static junit.framework.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyList;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ConfigFileMonitorTest {
@Mock
private ConfigurationService configurationService;
@Mock
private DefaultFileMonitor fileMonitor;
@Mock
private ConfigLoader configLoader;
@Mock
private CoreConfigurationService coreConfigurationService;
@Mock
private BootstrapConfig bootstrapConfig;
@InjectMocks
private ConfigFileMonitor configFileMonitor = new ConfigFileMonitor();
@Before
public void setUp() {
configFileMonitor.setFileMonitor(fileMonitor);
when(configurationService.loadBootstrapConfig()).thenReturn(bootstrapConfig);
}
@Test
public void shouldProcessExistingFilesAndStartFileMonitorWhileInitializing() throws IOException, URISyntaxException {
final Path tempDirectory = Files.createTempDirectory("motech-config-");
String configLocation = tempDirectory.toString();
when(coreConfigurationService.getConfigLocation()).thenReturn(new ConfigLocation(configLocation));
when(bootstrapConfig.getConfigSource()).thenReturn(ConfigSource.FILE);
configFileMonitor.init();
InOrder inOrder = inOrder(configLoader, configurationService, fileMonitor);
inOrder.verify(configLoader).findExistingConfigs();
inOrder.verify(configurationService).processExistingConfigs((List<File>) any());
final ArgumentCaptor<FileObject> fileObjArgCaptor = ArgumentCaptor.forClass(FileObject.class);
inOrder.verify(fileMonitor).addFile(fileObjArgCaptor.capture());
final FileObject monitoredLocation = fileObjArgCaptor.getValue();
assertEquals(configLocation, new File(monitoredLocation.getURL().toURI()).getAbsolutePath());
inOrder.verify(fileMonitor).start();
}
@Test
public void shouldSaveConfigWhenNewFileCreated() throws IOException {
final String fileName = "res:config/org.motechproject.motech-module1/somemodule.properties";
FileObject fileObject = VFS.getManager().resolveFile(fileName);
configFileMonitor.fileCreated(new FileChangeEvent(fileObject));
verify(configurationService).addOrUpdate(new File(fileObject.getName().getPath()));
}
@Test
public void shouldNotSaveConfigWhenNewFileCreatedIsNotSupported() throws IOException {
final String fileName = "res:config/motech-settings.conf";
FileObject fileObject = VFS.getManager().resolveFile(fileName);
configFileMonitor.fileCreated(new FileChangeEvent(fileObject));
verifyZeroInteractions(configurationService);
}
@Test
public void shouldSaveConfigWhenFileIsChanged() throws IOException {
final String fileName = "res:config/org.motechproject.motech-module1/somemodule.properties";
FileObject fileObject = VFS.getManager().resolveFile(fileName);
configFileMonitor.fileChanged(new FileChangeEvent(fileObject));
verify(configurationService).addOrUpdate(new File(fileObject.getName().getPath()));
}
@Test
public void shouldUpdateFileMonitoringLocation() throws FileSystemException {
final String fileName = "res:config/motech-settings.properties";
ConfigLocation configLocation = new ConfigLocation(fileName);
FileObject newLocation = VFS.getManager().resolveFile(fileName);
when(coreConfigurationService.getConfigLocation()).thenReturn(configLocation);
configFileMonitor.updateFileMonitor();
InOrder inOrder = inOrder(coreConfigurationService, fileMonitor);
inOrder.verify(fileMonitor).stop();
inOrder.verify(fileMonitor).removeFile(any(FileObject.class));
inOrder.verify(coreConfigurationService).getConfigLocation();
inOrder.verify(fileMonitor).addFile(newLocation);
inOrder.verify(fileMonitor).start();
}
@Test
public void shouldDeleteConfigWhenFileIsDeleted() throws FileSystemException {
final String fileName = "res:config/org.motechproject.motech-module1/somemodule.properties";
FileObject fileObject = VFS.getManager().resolveFile(fileName);
configFileMonitor.fileDeleted(new FileChangeEvent(fileObject));
verify(configurationService).deleteByBundle(new File(fileObject.getName().getPath()).getParentFile().getName());
}
@Test
public void shouldNotStartFileMonitorIfConfigLoaderThrowsException() throws IOException {
doThrow(new MotechConfigurationException("file could not be read")).when(configLoader).findExistingConfigs();
configFileMonitor.init();
verify(configurationService, never()).processExistingConfigs(anyList());
verify(fileMonitor, never()).run();
}
@Test
public void shouldNotStartWhenFileSourceIsUI() throws IOException {
when(configurationService.getConfigSource()).thenReturn(ConfigSource.UI);
configFileMonitor.init();
verify(configurationService, never()).processExistingConfigs(anyList());
verify(fileMonitor, never()).run();
}
}
|
agustafson/sbt-avrohugger | src/sbt-test/avrohugger/SpecificADTSerializationTests/build.sbt | <filename>src/sbt-test/avrohugger/SpecificADTSerializationTests/build.sbt<gh_stars>0
sourceGenerators in Compile += (avroScalaGenerateSpecific in Compile).taskValue
organization := "com.julianpeeters"
name := "datatype-specific-serializaton-tests"
version := "0.4-SNAPSHOT"
crossScalaVersions := Seq("2.10.6", "2.11.11", "2.12.4")
scalacOptions ++= Seq("-unchecked", "-deprecation", "-feature", "-Ywarn-value-discard")
avroScalaCustomTypes in Compile := {
avrohugger.format.SpecificRecord.defaultTypes.copy(
protocol = avrohugger.types.ScalaADT)
}
libraryDependencies += "org.apache.avro" % "avro" % "1.7.7"
libraryDependencies += "org.apache.avro" % "avro-ipc" % "1.7.7"
libraryDependencies += "org.specs2" %% "specs2-core" % "3.8.6" % "test" |
zealoussnow/chromium | third_party/blink/web_tests/http/tests/devtools/extensions/extensions-headers.js | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
(async function() {
TestRunner.addResult(`Tests WebInspector extension API\n`);
await TestRunner.loadTestModule('extensions_test_runner');
await TestRunner.loadHTML(`
<div style="white-space: pre" id="headers"></div>
<script>
function doXHR()
{
var xhr = new XMLHttpRequest();
xhr.open("GET", "../resources/echo-headers.php", false);
xhr.send(null);
return xhr.responseText;
}
</script>
`);
await ExtensionsTestRunner.runExtensionTests([
function extension_testAddHeaders(nextTest) {
webInspector.network.addRequestHeaders({
"x-webinspector-extension": "test",
"user-agent": "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)"
});
function cleanUpHeaders(headers) {
output(headers);
webInspector.network.addRequestHeaders({
"x-webinspector-extension": null,
"user-agent": null
});
}
webInspector.inspectedWindow.eval("doXHR()", callbackAndNextTest(cleanUpHeaders, nextTest));
}
]);
})();
|
WigWagCo/alljoyn | alljoyn/common/src/CertificateECC.cc | <filename>alljoyn/common/src/CertificateECC.cc
/**
* @file CertificateECC.cc
*
* Utilites for SPKI-style Certificates
*/
/******************************************************************************
* Copyright (c) 2014, AllSeen Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
******************************************************************************/
#include <qcc/platform.h>
#include <qcc/CertificateECC.h>
#include <qcc/String.h>
#include <qcc/StringUtil.h>
#include <qcc/Util.h>
#include <Status.h>
using namespace std;
using namespace qcc;
#define QCC_MODULE "CRYPTO"
namespace qcc {
#define CERT_TYPE0_SIGN_LEN Crypto_SHA256::DIGEST_SIZE
#define CERT_TYPE0_RAW_LEN sizeof(uint32_t) + sizeof(ECCPublicKey) + CERT_TYPE0_SIGN_LEN + sizeof(ECCSignature)
#define CERT_TYPE1_SIGN_LEN sizeof(uint32_t) + 2 * sizeof(ECCPublicKey) + sizeof(ValidPeriod) + sizeof (uint8_t) + Crypto_SHA256::DIGEST_SIZE
#define CERT_TYPE1_RAW_LEN CERT_TYPE1_SIGN_LEN + sizeof(ECCSignature)
#define CERT_TYPE2_SIGN_LEN sizeof(uint32_t) + 2 * sizeof(ECCPublicKey) + sizeof(ValidPeriod) + sizeof (uint8_t) + GUILD_ID_LEN + Crypto_SHA256::DIGEST_SIZE
#define CERT_TYPE2_RAW_LEN CERT_TYPE2_SIGN_LEN + sizeof(ECCSignature)
static qcc::String EncodeRawByte(const uint8_t* raw, size_t rawLen, const char* beginToken, const char* endToken)
{
qcc::String str;
qcc::String rawStr((const char*) raw, rawLen);
qcc::String base64;
QStatus status = Crypto_ASN1::EncodeBase64(rawStr, base64);
if (status != ER_OK) {
return "";
}
str += beginToken;
str += base64;
str += endToken;
return str;
}
static qcc::String EncodeCertRawByte(const uint8_t* raw, size_t rawLen)
{
return EncodeRawByte(raw, rawLen, "-----BEGIN CERTIFICATE-----",
"-----END CERTIFICATE-----");
}
static QStatus CountNumOfChunksFromEncoded(const String& encoded, const char* beginToken, const char* endToken, size_t* count)
{
size_t pos;
*count = 0;
qcc::String remainder = encoded;
while (true) {
pos = remainder.find(beginToken);
if (pos == qcc::String::npos) {
/* no more */
return ER_OK;
}
remainder = remainder.substr(pos + strlen(beginToken));
pos = remainder.find(endToken);
if (pos == qcc::String::npos) {
return ER_OK;
}
*count += 1;
remainder = remainder.substr(pos + strlen(endToken));
}
return ER_OK;
}
static QStatus RetrieveNumOfChunksFromPEM(const String& encoded, const char* beginToken, const char* endToken, qcc::String chunks[], size_t count)
{
size_t pos;
qcc::String remainder = encoded;
for (size_t idx = 0; idx < count; idx++) {
pos = remainder.find(beginToken);
if (pos == qcc::String::npos) {
/* no more */
return ER_OK;
}
remainder = remainder.substr(pos + strlen(beginToken));
pos = remainder.find(endToken);
if (pos == qcc::String::npos) {
return ER_OK;
}
chunks[idx] = beginToken;
chunks[idx] += remainder.substr(0, pos);
chunks[idx] += endToken;
remainder = remainder.substr(pos + strlen(endToken));
}
return ER_OK;
}
static QStatus RetrieveRawFromPEM(const String& pem, const char* beginToken, const char* endToken, String& rawStr)
{
qcc::String base64;
size_t pos;
pos = pem.find(beginToken);
if (pos == qcc::String::npos) {
return ER_INVALID_DATA;
}
qcc::String remainder = pem.substr(pos + strlen(beginToken));
pos = remainder.find(endToken);
if (pos == qcc::String::npos) {
base64 = remainder;
} else {
base64 = remainder.substr(0, pos);
}
return Crypto_ASN1::DecodeBase64(base64, rawStr);
}
static QStatus RetrieveRawCertFromPEM(const String& pem, String& rawStr)
{
return RetrieveRawFromPEM(pem,
"-----BEGIN CERTIFICATE-----",
"-----END CERTIFICATE-----", rawStr);
}
static QStatus DecodeKeyFromPEM(const String& pem, uint32_t* key, size_t len, const char* beginToken, const char* endToken)
{
String rawStr;
QStatus status = RetrieveRawFromPEM(pem, beginToken, endToken, rawStr);
if (status != ER_OK) {
return status;
}
if (len != rawStr.length()) {
return ER_INVALID_DATA;
}
memcpy(key, rawStr.data(), len);
return ER_OK;
}
QStatus CertECCUtil_EncodePrivateKey(const uint32_t* privateKey, size_t len, String& encoded)
{
encoded = EncodeRawByte((uint8_t*) privateKey, len,
"-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----");
return ER_OK;
}
QStatus CertECCUtil_DecodePrivateKey(const String& encoded, uint32_t* privateKey, size_t len)
{
return DecodeKeyFromPEM(encoded, privateKey, len,
"-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----");
}
QStatus CertECCUtil_EncodePublicKey(const uint32_t* publicKey, size_t len, String& encoded)
{
encoded = EncodeRawByte((uint8_t*) publicKey, len,
"-----BEGIN PUBLIC KEY-----", "-----END PUBLIC KEY-----");
return ER_OK;
}
QStatus CertECCUtil_DecodePublicKey(const String& encoded, uint32_t* publicKey, size_t len)
{
return DecodeKeyFromPEM(encoded, publicKey, len,
"-----BEGIN PUBLIC KEY-----", "-----END PUBLIC KEY-----");
}
QStatus CertECCUtil_GetCertCount(const String& encoded, size_t* count)
{
*count = 0;
return CountNumOfChunksFromEncoded(encoded,
"-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----", count);
}
QStatus CertECCUtil_GetVersionFromEncoded(const uint8_t* encoded, size_t len, uint32_t* certVersion)
{
if (len < sizeof(uint32_t)) {
return ER_INVALID_DATA;
}
uint32_t* p = (uint32_t*) encoded;
*certVersion = betoh32(*p);
return ER_OK;
}
QStatus CertECCUtil_GetVersionFromPEM(const String& pem, uint32_t* certVersion)
{
qcc::String rawStr;
QStatus status = RetrieveRawCertFromPEM(pem, rawStr);
if (status != ER_OK) {
return status;
}
uint8_t* raw = (uint8_t*) rawStr.data();
size_t rawLen = rawStr.length();
return CertECCUtil_GetVersionFromEncoded(raw, rawLen, certVersion);
}
QStatus CertECCUtil_GetCertChain(const String& pem, CertificateECC* certChain[], size_t count)
{
qcc::String* chunks = new qcc::String[count];
QStatus status = RetrieveNumOfChunksFromPEM(pem, "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----", chunks, count);
if (status != ER_OK) {
delete [] chunks;
return status;
}
for (size_t idx = 0; idx < count; idx++) {
uint32_t certVersion;
status = CertECCUtil_GetVersionFromPEM(chunks[idx], &certVersion);
if (status != ER_OK) {
break;
}
switch (certVersion) {
case 0:
certChain[idx] = new CertificateType0();
break;
case 1:
certChain[idx] = new CertificateType1();
break;
case 2:
certChain[idx] = new CertificateType2();
break;
default:
delete [] chunks;
return ER_INVALID_DATA;
}
status = certChain[idx]->LoadPEM(chunks[idx]);
if (status != ER_OK) {
break;
}
}
delete [] chunks;
return status;
}
CertificateType0::CertificateType0(const ECCPublicKey* issuer, const uint8_t* externalDigest) : CertificateECC(0)
{
SetVersion(0);
SetIssuer(issuer);
SetExternalDataDigest(externalDigest);
}
void CertificateType0::SetVersion(uint32_t val)
{
uint32_t* p = (uint32_t*) &encoded[OFFSET_VERSION];
*p = htobe32(val);
}
void CertificateType0::SetIssuer(const ECCPublicKey* issuer)
{
memcpy(&encoded[OFFSET_ISSUER], issuer, sizeof(ECCPublicKey));
}
void CertificateType0::SetExternalDataDigest(const uint8_t* externalDataDigest)
{
memcpy(&encoded[OFFSET_DIGEST], externalDataDigest, Crypto_SHA256::DIGEST_SIZE);
}
void CertificateType0::SetSig(const ECCSignature* sig)
{
memcpy(&encoded[OFFSET_SIG], sig, sizeof(ECCSignature));
}
QStatus CertificateType0::Sign(const ECCPrivateKey* dsaPrivateKey)
{
Crypto_ECC ecc;
ecc.SetDSAPrivateKey(dsaPrivateKey);
return ecc.DSASignDigest(GetExternalDataDigest(), Crypto_SHA256::DIGEST_SIZE, (ECCSignature*) &encoded[OFFSET_SIG]);
}
bool CertificateType0::VerifySignature()
{
Crypto_ECC ecc;
ecc.SetDSAPublicKey(GetIssuer());
return ecc.DSAVerifyDigest(GetExternalDataDigest(), Crypto_SHA256::DIGEST_SIZE, GetSig()) == ER_OK;
}
QStatus CertificateType0::LoadEncoded(const uint8_t* encodedBytes, size_t len)
{
if (len != GetEncodedLen()) {
return ER_INVALID_DATA;
}
uint32_t*pVersion = (uint32_t*) encodedBytes;
uint32_t version = betoh32(*pVersion);
if (version != GetVersion()) {
return ER_INVALID_DATA;
}
memcpy(&encoded, encodedBytes, len);
return ER_OK;
}
String CertificateType0::GetPEM()
{
return EncodeCertRawByte(GetEncoded(), GetEncodedLen());
}
QStatus CertificateType0::LoadPEM(const String& pem)
{
qcc::String rawStr;
QStatus status = RetrieveRawCertFromPEM(pem, rawStr);
if (status != ER_OK) {
return status;
}
uint8_t* raw = (uint8_t*) rawStr.data();
size_t rawLen = rawStr.length();
return LoadEncoded(raw, rawLen);
}
qcc::String CertificateType0::ToString()
{
qcc::String str("Certificate:\n");
str += "version: ";
str += U32ToString(GetVersion());
str += "\n";
str += "issuer: ";
str += BytesToHexString((const uint8_t*) GetIssuer(), sizeof(ECCPublicKey));
str += "\n";
str += "digest: ";
str += BytesToHexString((const uint8_t*) GetExternalDataDigest(), Crypto_SHA256::DIGEST_SIZE);
str += "\n";
str += "sig: ";
str += BytesToHexString((const uint8_t*) GetSig(), sizeof(ECCSignature));
str += "\n";
return str;
}
void CertificateType1::SetVersion(uint32_t val)
{
uint32_t* p = (uint32_t*) &encoded[OFFSET_VERSION];
*p = htobe32(val);
}
void CertificateType1::SetIssuer(const ECCPublicKey* issuer)
{
memcpy(&encoded[OFFSET_ISSUER], issuer, sizeof(ECCPublicKey));
}
void CertificateType1::SetSubject(const ECCPublicKey* subject)
{
memcpy(&encoded[OFFSET_SUBJECT], subject, sizeof(ECCPublicKey));
}
void CertificateType1::SetValidity(const ValidPeriod* validPeriod)
{
validity = *validPeriod;
/* setup encoded buffer */
uint64_t* p = (uint64_t*) &encoded[OFFSET_VALIDFROM];
*p = htobe64(validity.validFrom);
p = (uint64_t*) &encoded[OFFSET_VALIDTO];
*p = htobe64(validity.validTo);
}
CertificateType1::CertificateType1(const ECCPublicKey* issuer, const ECCPublicKey* subject) : CertificateECC(1)
{
SetVersion(1);
SetIssuer(issuer);
SetSubject(subject);
SetDelegate(false);
}
void CertificateType1::SetExternalDataDigest(const uint8_t* externalDataDigest)
{
memcpy(&encoded[OFFSET_DIGEST], externalDataDigest, Crypto_SHA256::DIGEST_SIZE);
}
void CertificateType1::SetSig(const ECCSignature* sig)
{
memcpy(&encoded[OFFSET_SIG], sig, sizeof(ECCSignature));
}
QStatus CertificateType1::Sign(const ECCPrivateKey* dsaPrivateKey)
{
Crypto_ECC ecc;
ecc.SetDSAPrivateKey(dsaPrivateKey);
uint8_t digest[Crypto_SHA256::DIGEST_SIZE];
Crypto_SHA256 hash;
hash.Init();
hash.Update(encoded, OFFSET_SIG);
hash.GetDigest(digest);
return ecc.DSASignDigest(digest, sizeof(digest), (ECCSignature*) &encoded[OFFSET_SIG]);
}
bool CertificateType1::VerifySignature()
{
Crypto_ECC ecc;
ecc.SetDSAPublicKey(GetIssuer());
uint8_t digest[Crypto_SHA256::DIGEST_SIZE];
Crypto_SHA256 hash;
hash.Init();
hash.Update(encoded, OFFSET_SIG);
hash.GetDigest(digest);
return ecc.DSAVerifyDigest(digest, sizeof(digest), GetSig()) == ER_OK;
}
QStatus CertificateType1::LoadEncoded(const uint8_t* encodedBytes, size_t len)
{
if (len != GetEncodedLen()) {
return ER_INVALID_DATA;
}
uint32_t* pVersion = (uint32_t*) encodedBytes;
uint32_t version = betoh32(*pVersion);
if (version != GetVersion()) {
return ER_INVALID_DATA;
}
memcpy(&encoded, encodedBytes, len);
/* setup the localized validitiy value from the encoded bytes */
uint64_t* p = (uint64_t*) &encoded[OFFSET_VALIDFROM];
validity.validFrom = betoh64(*p);
p = (uint64_t*) &encoded[OFFSET_VALIDTO];
validity.validTo = betoh64(*p);
return ER_OK;
}
String CertificateType1::GetPEM()
{
return EncodeCertRawByte(GetEncoded(), GetEncodedLen());
}
QStatus CertificateType1::LoadPEM(const String& pem)
{
qcc::String rawStr;
QStatus status = RetrieveRawCertFromPEM(pem, rawStr);
if (status != ER_OK) {
return status;
}
uint8_t* raw = (uint8_t*) rawStr.data();
size_t rawLen = rawStr.length();
return LoadEncoded(raw, rawLen);
}
qcc::String CertificateType1::ToString()
{
qcc::String str("Certificate:\n");
str += "version: ";
str += U32ToString(GetVersion());
str += "\n";
str += "issuer: ";
str += BytesToHexString((const uint8_t*) GetIssuer(), sizeof(ECCPublicKey));
str += "\n";
str += "subject: ";
str += BytesToHexString((const uint8_t*) GetSubject(), sizeof(ECCPublicKey));
str += "\n";
str += "validity: not-before ";
str += U64ToString(GetValidity()->validFrom);
str += " not-after ";
str += U64ToString(GetValidity()->validTo);
str += "\n";
if (IsDelegate()) {
str += "delegate: true\n";
} else {
str += "delegate: false\n";
}
str += "digest: ";
str += BytesToHexString((const uint8_t*) GetExternalDataDigest(), Crypto_SHA256::DIGEST_SIZE);
str += "\n";
str += "sig: ";
str += BytesToHexString((const uint8_t*) GetSig(), sizeof(ECCSignature));
str += "\n";
return str;
}
void CertificateType2::SetVersion(uint32_t val)
{
uint32_t* p = (uint32_t*) &encoded[OFFSET_VERSION];
*p = htobe32(val);
}
void CertificateType2::SetIssuer(const ECCPublicKey* issuer)
{
memcpy(&encoded[OFFSET_ISSUER], issuer, sizeof(ECCPublicKey));
}
void CertificateType2::SetSubject(const ECCPublicKey* subject)
{
memcpy(&encoded[OFFSET_SUBJECT], subject, sizeof(ECCPublicKey));
}
void CertificateType2::SetValidity(const ValidPeriod* validPeriod)
{
validity = *validPeriod;
/* setup encoded buffer */
uint64_t* p = (uint64_t*) &encoded[OFFSET_VALIDFROM];
*p = htobe64(validity.validFrom);
p = (uint64_t*) &encoded[OFFSET_VALIDTO];
*p = htobe64(validity.validTo);
}
CertificateType2::CertificateType2(const ECCPublicKey* issuer, const ECCPublicKey* subject) : CertificateECC(2)
{
SetVersion(2);
SetIssuer(issuer);
SetSubject(subject);
SetDelegate(false);
}
void CertificateType2::SetExternalDataDigest(const uint8_t* externalDataDigest)
{
memcpy(&encoded[OFFSET_DIGEST], externalDataDigest, Crypto_SHA256::DIGEST_SIZE);
}
void CertificateType2::SetSig(const ECCSignature* sig)
{
memcpy(&encoded[OFFSET_SIG], sig, sizeof(ECCSignature));
}
QStatus CertificateType2::Sign(const ECCPrivateKey* dsaPrivateKey)
{
Crypto_ECC ecc;
ecc.SetDSAPrivateKey(dsaPrivateKey);
uint8_t digest[Crypto_SHA256::DIGEST_SIZE];
Crypto_SHA256 hash;
hash.Init();
hash.Update(encoded, OFFSET_SIG);
hash.GetDigest(digest);
return ecc.DSASignDigest(digest, sizeof(digest), (ECCSignature*) &encoded[OFFSET_SIG]);
}
bool CertificateType2::VerifySignature()
{
Crypto_ECC ecc;
ecc.SetDSAPublicKey(GetIssuer());
uint8_t digest[Crypto_SHA256::DIGEST_SIZE];
Crypto_SHA256 hash;
hash.Init();
hash.Update(encoded, OFFSET_SIG);
hash.GetDigest(digest);
return ecc.DSAVerifyDigest(digest, sizeof(digest), GetSig()) == ER_OK;
}
QStatus CertificateType2::LoadEncoded(const uint8_t* encodedBytes, size_t len)
{
if (len != GetEncodedLen()) {
return ER_INVALID_DATA;
}
uint32_t* pVersion = (uint32_t*) encodedBytes;
uint32_t version = betoh32(*pVersion);
if (version != GetVersion()) {
return ER_INVALID_DATA;
}
memcpy(&encoded, encodedBytes, len);
/* setup the localized validitiy value from the encoded bytes */
uint64_t* p = (uint64_t*) &encoded[OFFSET_VALIDFROM];
validity.validFrom = betoh64(*p);
p = (uint64_t*) &encoded[OFFSET_VALIDTO];
validity.validTo = betoh64(*p);
return ER_OK;
}
String CertificateType2::GetPEM()
{
return EncodeCertRawByte(GetEncoded(), GetEncodedLen());
}
QStatus CertificateType2::LoadPEM(const String& pem)
{
qcc::String rawStr;
QStatus status = RetrieveRawCertFromPEM(pem, rawStr);
if (status != ER_OK) {
return status;
}
uint8_t* raw = (uint8_t*) rawStr.data();
size_t rawLen = rawStr.length();
return LoadEncoded(raw, rawLen);
}
void CertificateType2::SetGuild(const uint8_t* newGuild, size_t guildLen)
{
size_t len = GUILD_ID_LEN;
memset(&encoded[OFFSET_GUILD], 0, len);
if (len > guildLen) {
len = guildLen;
}
memcpy(&encoded[OFFSET_GUILD], newGuild, len);
}
String CertificateType2::ToString()
{
qcc::String str("Certificate:\n");
str += "version: ";
str += U32ToString(GetVersion());
str += "\n";
str += "issuer: ";
str += BytesToHexString((const uint8_t*) GetIssuer(), sizeof(ECCPublicKey));
str += "\n";
str += "subject: ";
str += BytesToHexString((const uint8_t*) GetSubject(), sizeof(ECCPublicKey));
str += "\n";
str += "validity: not-before ";
str += U64ToString(GetValidity()->validFrom);
str += " not-after ";
str += U64ToString(GetValidity()->validTo);
str += "\n";
if (IsDelegate()) {
str += "delegate: true\n";
} else {
str += "delegate: false\n";
}
str += "guild: ";
str += BytesToHexString((const uint8_t*) GetGuild(), GUILD_ID_LEN);
str += "\n";
str += "digest: ";
str += BytesToHexString((const uint8_t*) GetExternalDataDigest(), Crypto_SHA256::DIGEST_SIZE);
str += "\n";
str += "sig: ";
str += BytesToHexString((const uint8_t*) GetSig(), sizeof(ECCSignature));
str += "\n";
return str;
}
}
|
gilleshenrard/ITLG_POO | Awele/src/com/gilleshenrard/Awele/Models/Board.java | /****************************************************************************************************/
/* Class Board */
/* Encloses the game board manipulations */
/* The board contains a static array of slots, a players' remaining seeds count */
/* and a players' stored (saved) seeds count */
/* Author : <NAME> */
/* Last update : 11/05/2020 */
/****************************************************************************************************/
package com.gilleshenrard.Awele.Models;
import java.security.InvalidParameterException;
import java.util.ArrayList;
public class Board {
private Slot[][] m_slots;
private int[] m_storedSeeds;
/**
* Create new Board
*/
public Board(){
this.m_storedSeeds = new int[2];
java.util.Arrays.fill(m_storedSeeds, 0);
this.m_slots = new Slot[2][6];
for (int l = 0 ; l < 2 ; l++){
for (int c = 0 ; c < 6 ; c++){
this.m_slots[l][c] = new Slot(c, l);
}
}
}
/**
* Copy a Board from another Board
* @param board Board to copy
*/
public Board(Board board){
this();
this.copy(board);
}
/**
* Copy board values in the current board
* @param board Board from which copy the values
* @throws NullPointerException
*/
public void copy(Board board) throws NullPointerException {
if (board == null)
throw new NullPointerException("Board.copy() : NULL instance of Board");
//copy the stored seeds values
this.setStoredSeeds(1, board.getStoredSeeds(1));
this.setStoredSeeds(2, board.getStoredSeeds(2));
//copy each slot value
Point p = new Point(0, 0);
for (int l = 0 ; l < 2 ; l++){
for (int c = 0 ; c < 6 ; c++){
p.setCoordinates(c, l);
this.m_slots[l][c].setNbSeeds(board.getSlot(p).getNbSeeds());
}
}
}
/**
* Throw an exception if ID != 1 or ID != 2
* @param ID ID of the player
* @param msg Name of the method in which the validation occurs
* @throws InvalidParameterException
*/
public static void validateID(int ID, String msg) throws InvalidParameterException{
if (ID != 1 && ID != 2)
throw new InvalidParameterException(msg + ": invalid ID provided (value : " + ID + ")");
}
/**
* Throw an exception if not 0 <= x <= 5 of y != 1,2
* @param point Coordinates to validate
* @param msg Name of the method in which the validation occurs
* @throws InvalidParameterException
*/
public static void validateCoordinates(Point point, String msg) throws InvalidParameterException{
if(point.getX() < 0 || point.getX() > 5 || (point.getY() != 0 && point.getY() != 1))
throw new InvalidParameterException(msg + " : incorrect coordinates (values : " + point.getX() + "," + point.getY() + ")");
}
/**
* Add nb_seeds to the seeds reserve of Player 1 or Player 2
* @param ID ID of the player who receives the seeds
* @param nb_seeds Amount of seeds to store
* @throws InvalidParameterException
*/
public void setStoredSeeds(int ID, int nb_seeds) throws InvalidParameterException{
Board.validateID(ID, "Board.storeSeeds()");
if(nb_seeds < 0 || nb_seeds > 48)
throw new InvalidParameterException("Board.storeSeeds() : incorrect amount of seeds (value : " + nb_seeds + ")");
this.m_storedSeeds[ID - 1] = nb_seeds;
}
/**
* Return the amount of stored seeds for a Player
* @param ID ID of the player
* @return Amount of seeds stored
* @throws InvalidParameterException
*/
public int getStoredSeeds(int ID) throws InvalidParameterException {
Board.validateID(ID, "Board.getSeeds()");
return this.m_storedSeeds[ID - 1];
}
/**
* Get the slot located at point coordinates
* @param point Coordinates of the slot
* @return Slot requested
* @throws InvalidParameterException
*/
private Slot getSlot(Point point) throws InvalidParameterException{
Board.validateCoordinates(point, "Board.getSlot()");
return this.m_slots[point.getY()][point.getX()];
}
/**
* Set the amount of seeds contained in the slot located at X,Y
* @param point Coordinates of the slot
* @param nbSeeds Amount of seeds to set to the slot
* @throws InvalidParameterException
*/
public void setSlotSeeds(Point point, int nbSeeds) throws InvalidParameterException{
this.getSlot(point).setNbSeeds(nbSeeds);
}
/**
* Get the amount of seeds contained in the slot located at X,Y
* @param point Coordinates of the slot
* @return Amount of seeds
* @throws InvalidParameterException
*/
public int getSlotSeeds(Point point) throws InvalidParameterException{
return this.getSlot(point).getNbSeeds();
}
/**
* Empty a slot located at point
* @param point Coordinates of the slot to empty
* @throws InvalidParameterException
*/
public void emptySlotSeeds(Point point) throws InvalidParameterException{
this.getSlot(point).emptySeeds();
}
/**
* Get the next slot in which a seed can be scattered (does not skip the start seed)
* @param point Point of which find the next
* @return Next slot to point
* @throws NullPointerException
* @throws InvalidParameterException
*/
public Point getNext(Point point) throws NullPointerException, InvalidParameterException{
return this.getSubsequent(point, 1);
}
/**
* Get the Xth slot after a point in which a seed can be scattered (skip said point each turn)
* @param point Point of which find the next
* @param subsequent Which one of the subsequent seeds to get
* @return Next slot to point
* @throws NullPointerException
* @throws InvalidParameterException
*/
public Point getSubsequent(Point point, int subsequent) throws NullPointerException, InvalidParameterException{
validateCoordinates(point, "Board.getSubsequent()");
if (point == null)
throw new NullPointerException("Board.getSubsequent() : NULL instance of Point");
if (subsequent < 0)
throw new InvalidParameterException("Board.getSubsequent() : negative subsequent number");
//compute new x (start X + amount of seeds + amount of times the starting point is reached, then get the remainder of / 6)
int x = (point.getX() + subsequent + (subsequent/12)) % 6;
//compute new y (amount of back and forth the scattering would take + take start slot into account, then divide by 2)
int y = ((point.getX() + subsequent + (subsequent/12)) / 6) % 2;
//rectify the new Y if point is on opponent's side
if (point.getY() == 1)
y = 1 - y;
return new Point(x, y);
}
/**
* Get the previous slot coordinates (decrement x, and roll y when reached the beginning)
* @param point Point of which find the next
* @return Previous slot from point
* @throws NullPointerException
* @throws InvalidParameterException
*/
public Point getPrevious(Point point) throws NullPointerException, InvalidParameterException{
validateCoordinates(point, "Board.getSubsequent()");
if (point == null)
throw new NullPointerException("Board.getSubsequent() : NULL instance of Point");
int x = point.getX();
int y = point.getY();
//decrement X
x--;
//if beginning of row, roll X and decrement Y
if (x < 0){
x = 5;
y--;
}
//rectify Y
if (y < 0)
y = 1;
return new Point(x, y);
}
/**
* Get the distance on the board (slot count) between two points
* @param a Lowest point to check
* @param b Hignest point
* @return Distance (amount of slots) between the two points
*/
public int getDistance(Point a, Point b) {
if (a.getY() == b.getY()) {
if (b.getX() < a.getX())
return b.getX() + (5 - a.getX()) + 6;
else
return b.getX() - a.getX();
}
else
return b.getX() + (5 - a.getX());
}
/**
* Get how many seeds will be in a slot after scattering
* @param start Slot from which the scattering starts
* @param end Final slot in which the scattering ends
* @param p Slot for which to compute the final seed count
* @param nbseeds Amount of seeds in the start slot
* @return Total amount of seeds in the slot after scattering
*/
public int getFinalSeeds(Point start, Point end, Point p, int nbseeds){
//if p is the starting slot, amount of seeds should be 0
if (p.equals(start))
return 0;
//get how many times the scattering makes a whole board turn (translated from {0, x})
int addedSeeds = ((nbseeds) / 12);
//compare slot count between start, final and p to know if an additional seed is to be added
if (this.getDistance(start, p) <= this.getDistance(start, end))
addedSeeds++;
//return the final amount of seeds
return this.getSlotSeeds(p) + addedSeeds;
}
/**
* Reset the board to an inial value
*/
public void reset(){
this.setStoredSeeds(1, 0);
this.setStoredSeeds(2, 0);
Point p = new Point(0, 0);
for (int l = 0 ; l < 2 ; l++){
for (int c = 0 ; c < 6 ; c++){
p.setCoordinates(c, l);
this.setSlotSeeds(p, 4);
}
}
}
/**
* Get a buffer with all the non-empty slots
* @param ID ID of the player for which getting the slots
* @return Buffer
* @throws InvalidParameterException
*/
public ArrayList<Integer> getNonEmpty(int ID) throws InvalidParameterException{
Board.validateID(ID, "Board.getNonEmpty()");
ArrayList<Integer> array = new ArrayList<>();
for(Slot s : this.m_slots[ID-1]){
if (s.getNbSeeds() > 0)
array.add(s.getCoordinates().getX());
}
return array;
}
}
|
ShoheiTsuji-CRE/deploy_sample | vendor/bundle/ruby/2.6.0/gems/unicorn-6.0.0/test/benchmark/readinput.ru | # This app is intended to test large HTTP requests with or without
# a fully-buffering reverse proxy such as nginx. Without a fully-buffering
# reverse proxy, unicorn will be unresponsive when client count exceeds
# worker_processes.
DOC = <<DOC
To demonstrate how bad unicorn is at slowly uploading clients:
# in one terminal, start unicorn with one worker:
unicorn -E none -l 127.0.0.1:8080 test/benchmark/readinput.ru
# in a different terminal, upload 45M from multiple curl processes:
dd if=/dev/zero bs=45M count=1 | curl -T- -HExpect: --limit-rate 1M \
--trace-time -v http://127.0.0.1:8080/ &
dd if=/dev/zero bs=45M count=1 | curl -T- -HExpect: --limit-rate 1M \
--trace-time -v http://127.0.0.1:8080/ &
wait
# The last client won't see a response until the first one is done uploading
# You also won't be able to make GET requests to view this documentation
# while clients are uploading. You can also view the stderr debug output
# of unicorn (see logging code in #{__FILE__}).
DOC
run(lambda do |env|
input = env['rack.input']
buf = ''.b
# default logger contains timestamps, rely on that so users can
# see what the server is doing
l = env['rack.logger']
l.debug('BEGIN reading input ...') if l
:nop while input.read(16384, buf)
l.debug('DONE reading input ...') if l
buf.clear
[ 200, [ %W(Content-Length #{DOC.size}), %w(Content-Type text/plain) ],
[ DOC ] ]
end)
|
gchq/stroom-auth | stroom-auth-svc/src/main/java/stroom/auth/resources/user/v1/UserResource.java |
/*
*
* Copyright 2017 Crown Copyright
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package stroom.auth.resources.user.v1;
import com.codahale.metrics.annotation.Timed;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import event.logging.Event;
import event.logging.MultiObject;
import event.logging.ObjectOutcome;
import io.dropwizard.auth.Auth;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.tuple.Pair;
import org.jooq.Condition;
import org.jooq.DSLContext;
import org.jooq.JSONFormat;
import org.jooq.Record;
import org.jooq.Record13;
import org.jooq.Result;
import org.jooq.Table;
import org.jooq.TableField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import stroom.auth.clients.AuthorisationService;
import stroom.auth.clients.UserServiceClient;
import stroom.auth.daos.UserDao;
import stroom.auth.daos.UserMapper;
import stroom.auth.service.eventlogging.StroomEventLoggingService;
import stroom.auth.service.security.ServiceUser;
import stroom.auth.db.tables.records.UsersRecord;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import static stroom.auth.db.Tables.USERS;
@Singleton
@Path("/user/v1")
@Produces({"application/json"})
@Api(description = "Stroom User API", tags = {"User"})
public final class UserResource {
private static final Logger LOGGER = LoggerFactory.getLogger(UserResource.class);
private AuthorisationService authorisationService;
private UserServiceClient userServiceClient;
private UserDao userDao;
private StroomEventLoggingService stroomEventLoggingService;
@Inject
public UserResource(
@NotNull AuthorisationService authorisationService,
@NotNull UserServiceClient userServiceClient,
UserDao userDao,
final StroomEventLoggingService stroomEventLoggingService) {
super();
this.authorisationService = authorisationService;
this.userServiceClient = userServiceClient;
this.userDao = userDao;
this.stroomEventLoggingService = stroomEventLoggingService;
}
@ApiOperation(
value = "Get all users.",
response = String.class,
tags = {"User"})
@GET
@Path("/")
@Timed
@NotNull
public final Response getAll(
@Context @NotNull HttpServletRequest httpServletRequest,
@Auth @NotNull ServiceUser authenticatedServiceUser,
@Context @NotNull DSLContext database) {
Preconditions.checkNotNull(authenticatedServiceUser);
Preconditions.checkNotNull(database);
if (!authorisationService.canManageUsers(authenticatedServiceUser.getName(), authenticatedServiceUser.getJwt())) {
return Response.status(Response.Status.UNAUTHORIZED).entity(UserServiceClient.UNAUTHORISED_USER_MESSAGE).build();
}
TableField orderByEmailField = USERS.EMAIL;
String usersAsJson = database
.selectFrom(USERS)
.orderBy(orderByEmailField)
.fetch()
.formatJSON((new JSONFormat())
.header(false)
.recordFormat(JSONFormat.RecordFormat.OBJECT));
ObjectOutcome objectOutcome = new ObjectOutcome();
event.logging.Object object = new event.logging.Object();
object.setName("GetAllUsers");
objectOutcome.getObjects().add(object);
stroomEventLoggingService.view(
"GetAllUsers",
httpServletRequest,
authenticatedServiceUser.getName(),
objectOutcome,
"Read all users.");
return Response.status(Response.Status.OK).entity(usersAsJson).build();
}
@ApiOperation(
value = "Create a user.",
response = Integer.class,
tags = {"User"})
@POST
@Path("/")
@Timed
@NotNull
public final Response createUser(
@Context @NotNull HttpServletRequest httpServletRequest,
@Auth @NotNull ServiceUser authenticatedServiceUser,
@Context @NotNull DSLContext database,
@ApiParam("user") @NotNull User user) {
// Validate
Preconditions.checkNotNull(authenticatedServiceUser);
Preconditions.checkNotNull(database);
if (!authorisationService.canManageUsers(authenticatedServiceUser.getName(), authenticatedServiceUser.getJwt())) {
return Response.status(Response.Status.UNAUTHORIZED).entity(UserServiceClient.UNAUTHORISED_USER_MESSAGE).build();
}
Pair<Boolean, String> validationResults = User.isValidForCreate(user);
boolean isUserValid = validationResults.getLeft();
if (!isUserValid) {
return Response.status(Response.Status.BAD_REQUEST).entity(validationResults.getRight()).build();
}
if (doesUserAlreadyExist(database, user.getEmail())) {
return Response.status(Response.Status.CONFLICT).entity(UserValidationError.USER_ALREADY_EXISTS).build();
}
if (Strings.isNullOrEmpty(user.getState())) {
user.setState(User.UserState.ENABLED.getStateText());
}
int newUserId = userDao.create(user, authenticatedServiceUser.getName());
event.logging.User loggingUser = new event.logging.User();
loggingUser.setId(user.getEmail());
ObjectOutcome objectOutcome = new ObjectOutcome();
objectOutcome.getObjects().add(loggingUser);
stroomEventLoggingService.create(
"CreateUser",
httpServletRequest,
authenticatedServiceUser.getName(),
objectOutcome,
"Create a user");
return Response.status(Response.Status.OK).entity(newUserId).build();
}
@ApiOperation(
value = "Get the details of the currently logged-in user.",
response = String.class,
tags = {"User"})
@GET
@Path("/me")
@Timed
@NotNull
public final Response readCurrentUser(
@Context @NotNull HttpServletRequest httpServletRequest,
@Auth @NotNull ServiceUser authenticatedServiceUser,
@Context @NotNull DSLContext database) {
// Validate
Preconditions.checkNotNull(authenticatedServiceUser);
Preconditions.checkNotNull(database);
// We're not checking authorisation because the current user is allowed to get infomation about themselves.
// Get the user
Record foundUserRecord = database
.select(USERS.ID,
USERS.EMAIL,
USERS.FIRST_NAME,
USERS.LAST_NAME,
USERS.COMMENTS,
USERS.STATE,
USERS.LOGIN_FAILURES,
USERS.LOGIN_COUNT,
USERS.LAST_LOGIN,
USERS.UPDATED_ON,
USERS.UPDATED_BY_USER,
USERS.CREATED_ON,
USERS.CREATED_BY_USER,
USERS.NEVER_EXPIRES,
USERS.FORCE_PASSWORD_CHANGE)
.from(USERS)
.where(new Condition[]{USERS.EMAIL.eq(authenticatedServiceUser.getName())}).fetchOne();
Result foundUserResult = database
.newResult(USERS.ID,
USERS.EMAIL,
USERS.FIRST_NAME,
USERS.LAST_NAME,
USERS.COMMENTS,
USERS.STATE,
USERS.LOGIN_FAILURES,
USERS.LOGIN_COUNT,
USERS.LAST_LOGIN,
USERS.UPDATED_ON,
USERS.UPDATED_BY_USER,
USERS.CREATED_ON,
USERS.CREATED_BY_USER,
USERS.NEVER_EXPIRES,
USERS.FORCE_PASSWORD_CHANGE
);
foundUserResult.add(foundUserRecord);
String foundUserJson = foundUserResult.formatJSON((new JSONFormat()).header(false).recordFormat(JSONFormat.RecordFormat.OBJECT));
event.logging.User user = new event.logging.User();
user.setId(foundUserRecord.get(USERS.EMAIL));
ObjectOutcome objectOutcome = new ObjectOutcome();
objectOutcome.getObjects().add(user);
stroomEventLoggingService.view(
"ReadCurrentUser",
httpServletRequest,
authenticatedServiceUser.getName(),
objectOutcome,
"Read the current user.");
Response response = Response.status(Response.Status.OK).entity(foundUserJson).build();
return response;
}
@ApiOperation(
value = "Search for a user by email.",
response = String.class,
tags = {"User"})
@GET
@Path("search")
@Timed
@NotNull
public final Response searchUsers(
@Context @NotNull HttpServletRequest httpServletRequest,
@Auth @NotNull ServiceUser authenticatedServiceUser,
@Context @NotNull DSLContext database,
@QueryParam("email") String email) {
// Validate
Preconditions.checkNotNull(authenticatedServiceUser);
Preconditions.checkNotNull(database);
if (!authorisationService.canManageUsers(authenticatedServiceUser.getName(), (authenticatedServiceUser.getJwt()))) {
return Response
.status(Response.Status.UNAUTHORIZED)
.entity(UserServiceClient.UNAUTHORISED_USER_MESSAGE).build();
}
// Get the users
Result<Record13<Integer, String, String, String, String, String, Integer, Integer, Timestamp, Timestamp, String, Timestamp, String>> foundUserRecord = database
.select(USERS.ID,
USERS.EMAIL,
USERS.FIRST_NAME,
USERS.LAST_NAME,
USERS.COMMENTS,
USERS.STATE,
USERS.LOGIN_FAILURES,
USERS.LOGIN_COUNT,
USERS.LAST_LOGIN,
USERS.UPDATED_ON,
USERS.UPDATED_BY_USER,
USERS.CREATED_ON,
USERS.CREATED_BY_USER)
.from(USERS)
.where(new Condition[]{USERS.EMAIL.contains(email)})
.fetch();
Response response;
if (foundUserRecord == null) {
response = Response.status(Response.Status.NOT_FOUND).build();
return response;
} else {
String users = foundUserRecord.formatJSON((new JSONFormat())
.header(false)
.recordFormat(JSONFormat.RecordFormat.OBJECT));
event.logging.User user = new event.logging.User();
user.setId(email);
ObjectOutcome objectOutcome = new ObjectOutcome();
objectOutcome.getObjects().add(user);
stroomEventLoggingService.view(
"SearchUser",
httpServletRequest,
authenticatedServiceUser.getName(),
objectOutcome,
"Search for a user.");
response = Response.status(Response.Status.OK).entity(users).build();
return response;
}
}
@ApiOperation(
value = "Get a user by ID.",
response = String.class,
tags = {"User"})
@GET
@Path("{id}")
@Timed
@NotNull
public final Response getUser(
@Context @NotNull HttpServletRequest httpServletRequest,
@Auth @NotNull ServiceUser authenticatedServiceUser,
@Context @NotNull DSLContext database,
@PathParam("id") int userId) {
// Validate
Preconditions.checkNotNull(authenticatedServiceUser);
Preconditions.checkNotNull(database);
// Get the user
UsersRecord foundUserRecord = database
.selectFrom(USERS)
.where(new Condition[]{USERS.ID.eq(userId)})
.fetchOne();
Response response;
if (foundUserRecord == null) {
response = Response.status(Response.Status.NOT_FOUND).build();
return response;
} else {
// We only need to check auth permissions if the user is trying to access a different user.
String foundUserEmail = foundUserRecord.get(USERS.EMAIL);
boolean isUserAccessingThemselves = authenticatedServiceUser.getName().equals(foundUserEmail);
if (!isUserAccessingThemselves) {
if (!authorisationService.canManageUsers(authenticatedServiceUser.getName(), authenticatedServiceUser.getJwt())) {
return Response.status(Response.Status.UNAUTHORIZED).entity(UserServiceClient.UNAUTHORISED_USER_MESSAGE).build();
}
}
event.logging.User user = new event.logging.User();
user.setId(foundUserRecord.get(USERS.EMAIL));
ObjectOutcome objectOutcome = new ObjectOutcome();
objectOutcome.getObjects().add(user);
stroomEventLoggingService.view(
"GetUser",
httpServletRequest,
authenticatedServiceUser.getName(),
objectOutcome,
"Read a specific user.");
User foundUser = UserMapper.map(foundUserRecord);
response = Response.status(Response.Status.OK).entity(foundUser).build();
return response;
}
}
@ApiOperation(
value = "Update a user.",
response = String.class,
tags = {"User"})
@PUT
@Path("{id}")
@Timed
@NotNull
public final Response updateUser(
@Context @NotNull HttpServletRequest httpServletRequest,
@Auth @NotNull ServiceUser authenticatedServiceUser,
@Context @NotNull DSLContext database,
@ApiParam("user") @NotNull User user,
@PathParam("id") int userId) {
UsersRecord usersRecord = (UsersRecord) database
.selectFrom((Table) USERS)
.where(new Condition[]{USERS.ID.eq(userId)})
.fetchOne();
// We only need to check auth permissions if the user is trying to access a different user.
String foundUserEmail = usersRecord.get(USERS.EMAIL);
boolean isUserAccessingThemselves = authenticatedServiceUser.getName().equals(foundUserEmail);
if (!isUserAccessingThemselves) {
if (!authorisationService.canManageUsers(authenticatedServiceUser.getName(), authenticatedServiceUser.getJwt())) {
return Response.status(Response.Status.UNAUTHORIZED).entity(UserServiceClient.UNAUTHORISED_USER_MESSAGE).build();
}
}
if(!usersRecord.getState().equalsIgnoreCase(user.getState())) {
boolean isEnabled = user.getState().equals("enabled");
userServiceClient.setUserStatus(authenticatedServiceUser.getJwt(), user.getEmail(), isEnabled);
}
user.setUpdatedByUser(authenticatedServiceUser.getName());
user.setUpdatedOn(LocalDateTime.now().toString());
UsersRecord updatedUsersRecord = UserMapper.updateUserRecordWithUser(user, usersRecord);
database
.update((Table) USERS)
.set(updatedUsersRecord)
.where(new Condition[]{USERS.ID.eq(userId)}).execute();
event.logging.User eventUser = new event.logging.User();
eventUser.setId(Integer.valueOf(userId).toString());
MultiObject afterMultiObject = new MultiObject();
afterMultiObject.getObjects().add(eventUser);
Event.EventDetail.Update update = new Event.EventDetail.Update();
update.setAfter(afterMultiObject);
stroomEventLoggingService.update(
"UpdateUser",
httpServletRequest,
authenticatedServiceUser.getName(),
update,
"Toggle whether a token is enabled or not.");
Response response = Response.status(Response.Status.NO_CONTENT).build();
return response;
}
@ApiOperation(
value = "Delete a user by ID.",
response = String.class,
tags = {"User"})
@DELETE
@Path("{id}")
@Timed
@NotNull
public final Response deleteUser(
@Context @NotNull HttpServletRequest httpServletRequest,
@Auth @NotNull ServiceUser authenticatedServiceUser,
@Context @NotNull DSLContext database,
@PathParam("id") int userId) {
// Validate
Preconditions.checkNotNull(authenticatedServiceUser);
Preconditions.checkNotNull(database);
if (!authorisationService.canManageUsers(authenticatedServiceUser.getName(), authenticatedServiceUser.getJwt())) {
return Response.status(Response.Status.UNAUTHORIZED).entity(UserServiceClient.UNAUTHORISED_USER_MESSAGE).build();
}
database
.deleteFrom((Table) USERS)
.where(new Condition[]{USERS.ID.eq(userId)}).execute();
event.logging.User user = new event.logging.User();
user.setId(Integer.valueOf(userId).toString());
ObjectOutcome objectOutcome = new ObjectOutcome();
objectOutcome.getObjects().add(user);
stroomEventLoggingService.delete(
"DeleteUser",
httpServletRequest,
authenticatedServiceUser.getName(),
objectOutcome,
"Delete a user by ID");
Response response = Response.status(Response.Status.NO_CONTENT).build();
return response;
}
private static Boolean doesUserAlreadyExist(DSLContext database, String email) {
int countOfSameName = database
.selectCount()
.from(USERS)
.where(new Condition[]{USERS.EMAIL.eq(email)})
.fetchOne(0, Integer.TYPE);
return countOfSameName > 0;
}
}
|
kzahedi/YARS | src/yars/configuration/xsd/generator/YarsXSDGenerator.cpp | #include <yars/configuration/xsd/generator/YarsXSDGenerator.h>
#include <yars/configuration/xsd/generator/YarsXSDNames.h>
#include <yars/configuration/xsd/generator/XSDString.h>
#include <yars/configuration/data/Data.h>
#include <cstdlib>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/dom/DOM.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/OutOfMemoryException.hpp>
#if defined(XERCES_NEW_IOSTREAMS)
# include <iostream>
#else
# include <iostream.h>
#endif
using namespace std;
XERCES_CPP_NAMESPACE_USE
YarsXSDGenerator::YarsXSDGenerator()
{
try
{
XMLPlatformUtils::Initialize();
}
catch(const XMLException& toCatch)
{
char *pMsg = XMLString::transcode(toCatch.getMessage());
XERCES_STD_QUALIFIER cerr << "Error during Xerces-c Initialization.\n"
<< " Exception message:"
<< pMsg;
XMLString::release(&pMsg);
}
_impl = DOMImplementationRegistry::getDOMImplementation(NULL);
_out = ((DOMImplementationLS*)_impl)->createLSOutput();
_out->setEncoding(X("UTF-8"));
if (_impl != NULL)
{
try
{
_doc = _impl->createDocument(YARS_XSD_NS, YARS_XSD_SCHEMA, 0);
_doc->setXmlStandalone(true);
_root = _doc->getDocumentElement();
_root->setAttribute(YARS_XSD_ELEMENT_FORM_DEFAULT, YARS_XSD_QUALIFIED);
Data *data = Data::instance();
XsdSpecification *spec = data->xsd();
for(std::vector<XsdSequence*>::iterator s = spec->s_begin(); s != spec->s_end(); s++)
{
__addSequence(*s);
}
for(std::vector<XsdEnumeration*>::iterator e = spec->e_begin(); e != spec->e_end(); e++)
{
__addEnumeration(*e);
}
for(std::vector<XsdChoice*>::iterator c = spec->c_begin(); c != spec->c_end(); c++)
{
__addChoice(*c);
}
for(std::vector<XsdInterval*>::iterator i = spec->i_begin(); i != spec->i_end(); i++)
{
__addInterval(*i);
}
for(std::vector<XsdRegularExpression*>::iterator r = spec->r_begin(); r != spec->r_end(); r++)
{
__addRegularExpression(*r);
}
__addRoot(spec->root());
delete spec;
}
catch (const OutOfMemoryException&)
{
XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
}
catch (const DOMException& e)
{
XERCES_STD_QUALIFIER cerr << "DOMException code is: " << e.code << XERCES_STD_QUALIFIER endl;
}
catch (...)
{
XERCES_STD_QUALIFIER cerr << "An error occurred creating the document" << XERCES_STD_QUALIFIER endl;
}
} // (inpl != NULL)
else
{
XERCES_STD_QUALIFIER cerr << "Requested implementation is not supported" << XERCES_STD_QUALIFIER endl;
}
}
YarsXSDGenerator::~YarsXSDGenerator()
{
// ???
}
DOMDocument* YarsXSDGenerator::doc()
{
return _doc;
}
void YarsXSDGenerator::__addSequence(XsdSequence *s)
{
// DOMComment *comment = _doc->createComment(X("comment"));
DOMElement *parent = _doc->createElement(YARS_XSD_COMPLEX_TYPE);
XsdElement *xsdElement = NULL;
XsdChoice *xsdChoice = NULL;
DOMElement *element = NULL;
DOMElement *choice = NULL;
parent->setAttribute(YARS_XSD_NAME, X(s->name().c_str()));
if(s->n_size() > 0)
{
DOMElement *sequence = _doc->createElement(YARS_XSD_SEQUENCE);
parent->appendChild(sequence);
for(std::vector<XsdNode*>::iterator n = s->n_begin(); n != s->n_end(); n++)
{
switch((*n)->nodeType())
{
case XSD_NODE_TYPE_ELEMENT:
element = _doc->createElement(YARS_XSD_ELEMENT);
xsdElement = ((XsdElement*)(*n));
__createElement(element, xsdElement);
sequence->appendChild(element);
break;
case XSD_NODE_TYPE_CHOICE:
choice = _doc->createElement(YARS_XSD_CHOICE);
xsdChoice = (XsdChoice*)(*n);
__createChoice(choice, xsdChoice);
sequence->appendChild(choice);
break;
}
}
}
if(s->a_size() > 0)
{
for(std::vector<XsdAttribute*>::iterator a = s->a_begin(); a != s->a_end(); a++)
{
element = _doc->createElement(YARS_XSD_ATTRIBUTE);
__createAttribute(element, *a);
parent->appendChild(element);
}
}
_root->appendChild(parent);
}
void YarsXSDGenerator::__createChoice(DOMElement *choice, XsdChoice *c)
{
if(c->maxOccursGiven())
{
choice->setAttribute(YARS_XSD_MAX_OCCURS, X(c->maxOccurs().c_str()));
}
if(c->minOccursGiven())
{
choice->setAttribute(YARS_XSD_MIN_OCCURS, X(c->minOccurs().c_str()));
}
if(c->e_size() > 0)
{
for(std::vector<XsdElement*>::iterator i = c->e_begin(); i != c->e_end(); i++)
{
DOMElement *element = _doc->createElement(YARS_XSD_ELEMENT);
__createElement(element, *i);
choice->appendChild(element);
}
}
if(c->s_size() > 0)
{
for(std::vector<XsdSequence*>::iterator s = c->s_begin(); s != c->s_end(); s++)
{
DOMElement *sequence = _doc->createElement(YARS_XSD_SEQUENCE);
__createSequence(sequence, *s);
choice->appendChild(sequence);
}
}
}
void YarsXSDGenerator::__createSequence(DOMElement *sequence, XsdSequence *s)
{
if(s->e_size() > 0)
{
for(std::vector<XsdElement*>::iterator i = s->e_begin(); i != s->e_end(); i++)
{
DOMElement *element = _doc->createElement(YARS_XSD_ELEMENT);
__createElement(element, *i);
sequence->appendChild(element);
}
}
}
void YarsXSDGenerator::__createElement(DOMElement *element, XsdElement *e)
{
if(e->maxOccursGiven())
{
element->setAttribute(YARS_XSD_MAX_OCCURS, X(e->maxOccurs().c_str()));
}
if(e->minOccursGiven())
{
element->setAttribute(YARS_XSD_MIN_OCCURS, X(e->minOccurs().c_str()));
}
element->setAttribute(YARS_XSD_NAME, X(e->name().c_str()));
if(e->type().size() > 0)
{
element->setAttribute(YARS_XSD_TYPE, X(e->type().c_str()));
}
if(e->a_size() > 0)
{
DOMElement *complexType = _doc->createElement(YARS_XSD_COMPLEX_TYPE);
for(std::vector<XsdAttribute*>::iterator a = e->a_begin(); a != e->a_end(); a++)
{
DOMElement *attr = _doc->createElement(YARS_XSD_ATTRIBUTE);
__createAttribute(attr, *a);
complexType->appendChild(attr);
}
element->appendChild(complexType);
}
}
void YarsXSDGenerator::__createAttribute(DOMElement *element, XsdAttribute *a)
{
element->setAttribute(YARS_XSD_NAME, X(a->name().c_str()));
element->setAttribute(YARS_XSD_TYPE, X(a->type().c_str()));
if(a->required())
{
element->setAttribute(YARS_XSD_USE, YARS_XSD_REQUIRED);
}
else
{
element->setAttribute(YARS_XSD_USE, YARS_XSD_OPTIONAL);
}
}
void YarsXSDGenerator::__addEnumeration(XsdEnumeration *e)
{
DOMElement *parent = _doc->createElement(YARS_XSD_SIMPLE_TYPE);
DOMElement *restriction = _doc->createElement(YARS_XSD_RESTRICTION);
restriction->setAttribute(YARS_XSD_BASE, X(e->type().c_str()));
parent->setAttribute(YARS_XSD_NAME, X(e->name().c_str()));
parent->appendChild(restriction);
for(std::vector<string>::iterator v = e->v_begin(); v != e->v_end(); v++)
{
DOMElement *element = _doc->createElement(YARS_XSD_ENUMERATION);
element->setAttribute(YARS_XSD_VALUE, X(v->c_str()));
restriction->appendChild(element);
}
_root->appendChild(parent);
}
void YarsXSDGenerator::__addChoice(XsdChoice *c)
{
DOMElement *parent = _doc->createElement(YARS_XSD_COMPLEX_TYPE);
DOMElement *choice = _doc->createElement(YARS_XSD_CHOICE);
if(c->minOccursGiven())
{
choice->setAttribute(YARS_XSD_MIN_OCCURS, X(c->minOccurs().c_str()));
}
if(c->maxOccursGiven())
{
choice->setAttribute(YARS_XSD_MAX_OCCURS, X(c->maxOccurs().c_str()));
}
parent->setAttribute(YARS_XSD_NAME, X(c->name().c_str()));
for(std::vector<XsdElement*>::iterator e = c->e_begin(); e != c->e_end(); e++)
{
DOMElement *element = _doc->createElement(YARS_XSD_ELEMENT);
__createElement(element, *e);
choice->appendChild(element);
}
for(std::vector<XsdSequence*>::iterator s = c->s_begin(); s != c->s_end(); s++)
{
DOMElement *sequence = _doc->createElement(YARS_XSD_SEQUENCE);
__createSequence(sequence, *s);
choice->appendChild(sequence);
}
parent->appendChild(choice);
if(c->a_size() > 0)
{
for(std::vector<XsdAttribute*>::iterator a = c->a_begin(); a != c->a_end(); a++)
{
DOMElement *element = _doc->createElement(YARS_XSD_ATTRIBUTE);
__createAttribute(element, *a);
parent->appendChild(element);
}
}
_root->appendChild(parent);
}
void YarsXSDGenerator::__addInterval(XsdInterval *i)
{
DOMElement *parent = _doc->createElement(YARS_XSD_SIMPLE_TYPE);
DOMElement *restriction = _doc->createElement(YARS_XSD_RESTRICTION);
restriction->setAttribute(YARS_XSD_BASE, X(i->type().c_str()));
parent->setAttribute(YARS_XSD_NAME, X(i->name().c_str()));
parent->appendChild(restriction);
DOMElement *min = _doc->createElement(YARS_XSD_MIN_INCLUSIVE);
min->setAttribute(YARS_XSD_VALUE, X(i->minimum().c_str()));
restriction->appendChild(min);
DOMElement *max = _doc->createElement(YARS_XSD_MAX_INCLUSIVE);
max->setAttribute(YARS_XSD_VALUE, X(i->maximum().c_str()));
restriction->appendChild(max);
_root->appendChild(parent);
}
void YarsXSDGenerator::__addRegularExpression(XsdRegularExpression *r)
{
DOMElement *parent = _doc->createElement(YARS_XSD_SIMPLE_TYPE);
DOMElement *restriction = _doc->createElement(YARS_XSD_RESTRICTION);
restriction->setAttribute(YARS_XSD_BASE, X(r->type().c_str()));
parent->setAttribute(YARS_XSD_NAME, X(r->name().c_str()));
parent->appendChild(restriction);
DOMElement *pattern = _doc->createElement(YARS_XSD_PATTERN);
pattern->setAttribute(YARS_XSD_VALUE, X(r->regExp().c_str()));
restriction->appendChild(pattern);
_root->appendChild(parent);
}
void YarsXSDGenerator::__addRoot(XsdSequence *s)
{
DOMElement *parent = _doc->createElement(YARS_XSD_ELEMENT);
DOMElement *complexType = _doc->createElement(YARS_XSD_COMPLEX_TYPE);
parent->setAttribute(YARS_XSD_NAME, X(s->name().c_str()));
parent->appendChild(complexType);
if(s->e_size() > 0)
{
DOMElement *sequence = _doc->createElement(YARS_XSD_SEQUENCE);
parent->appendChild(sequence);
for(std::vector<XsdElement*>::iterator e = s->e_begin(); e != s->e_end(); e++)
{
DOMElement *element = _doc->createElement(YARS_XSD_ELEMENT);
__createElement(element, *e);
sequence->appendChild(element);
}
complexType->appendChild(sequence);
}
if(s->a_size() > 0)
{
for(std::vector<XsdAttribute*>::iterator a = s->a_begin(); a != s->a_end(); a++)
{
DOMElement *element = _doc->createElement(YARS_XSD_ATTRIBUTE);
__createAttribute(element, *a);
complexType->appendChild(element);
}
}
_root->appendChild(parent);
}
DOMLSOutput* YarsXSDGenerator::out()
{
return _out;
}
|
tienla/fpga-zynq | rocket-chip/chisel3/chiselFrontend/src/main/scala/chisel3/core/When.scala | // See LICENSE for license details.
package chisel3.core
import scala.language.experimental.macros
import chisel3.internal._
import chisel3.internal.Builder.pushCommand
import chisel3.internal.firrtl._
import chisel3.internal.sourceinfo.{SourceInfo}
object when { // scalastyle:ignore object.name
/** Create a `when` condition block, where whether a block of logic is
* executed or not depends on the conditional.
*
* @param cond condition to execute upon
* @param block logic that runs only if `cond` is true
*
* @example
* {{{
* when ( myData === 3.U ) {
* // Some logic to run when myData equals 3.
* } .elsewhen ( myData === 1.U ) {
* // Some logic to run when myData equals 1.
* } .otherwise {
* // Some logic to run when myData is neither 3 nor 1.
* }
* }}}
*/
def apply(cond: Bool)(block: => Unit)(implicit sourceInfo: SourceInfo): WhenContext = {
new WhenContext(sourceInfo, cond, !cond, block)
}
}
/** Internal mechanism for generating a when. Because of the way FIRRTL
* commands are emitted, generating a FIRRTL elsewhen or nested whens inside
* elses would be difficult. Instead, this keeps track of the negative of the
* previous conditions, so when an elsewhen or otherwise is used, it checks
* that both the condition is true and all the previous conditions have been
* false.
*/
final class WhenContext(sourceInfo: SourceInfo, cond: Bool, prevCond: => Bool, block: => Unit) {
/** This block of logic gets executed if above conditions have been false
* and this condition is true.
*/
def elsewhen (elseCond: Bool)(block: => Unit)(implicit sourceInfo: SourceInfo): WhenContext = {
new WhenContext(sourceInfo, prevCond && elseCond, prevCond && !elseCond, block)
}
/** This block of logic gets executed only if the above conditions were all
* false. No additional logic blocks may be appended past the `otherwise`.
*/
def otherwise(block: => Unit)(implicit sourceInfo: SourceInfo): Unit =
new WhenContext(sourceInfo, prevCond, null, block)
pushCommand(WhenBegin(sourceInfo, cond.ref))
block
pushCommand(WhenEnd(sourceInfo))
}
|
dahlia-os/fuchsia-pine64-pinephone | src/developer/system_monitor/bin/harvester/gather_memory.cc | <gh_stars>10-100
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gather_memory.h"
#include <lib/syslog/cpp/macros.h>
#include <zircon/status.h>
#include "harvester.h"
#include "sample_bundle.h"
namespace harvester {
void AddGlobalMemorySamples(SampleBundle* samples, zx_handle_t root_resource) {
zx_info_kmem_stats_t stats;
zx_status_t err = zx_object_get_info(root_resource, ZX_INFO_KMEM_STATS,
&stats, sizeof(stats),
/*actual=*/nullptr, /*avail=*/nullptr);
if (err != ZX_OK) {
FX_LOGS(ERROR) << "ZX_INFO_KMEM_STATS error " << zx_status_get_string(err);
return;
}
FX_VLOGS(2) << "free memory total " << stats.free_bytes << ", heap "
<< stats.free_heap_bytes << ", vmo " << stats.vmo_bytes
<< ", mmu " << stats.mmu_overhead_bytes << ", ipc "
<< stats.ipc_bytes;
const std::string DEVICE_FREE = "memory:device_free_bytes";
const std::string KERNEL_TOTAL = "memory:kernel_total_bytes";
const std::string KERNEL_FREE = "memory:kernel_free_bytes";
const std::string KERNEL_OTHER = "memory:kernel_other_bytes";
const std::string VMO = "memory:vmo_bytes";
const std::string MMU_OVERHEAD = "memory:mmu_overhead_bytes";
const std::string IPC = "memory:ipc_bytes";
const std::string OTHER = "memory:device_other_bytes";
// Memory for the entire machine.
// Note: stats.total_bytes is recorded by InitialData().
samples->AddIntSample(DEVICE_FREE, stats.free_bytes);
// Memory in the kernel.
samples->AddIntSample(KERNEL_TOTAL, stats.total_heap_bytes);
samples->AddIntSample(KERNEL_FREE, stats.free_heap_bytes);
samples->AddIntSample(KERNEL_OTHER, stats.wired_bytes);
// Categorized memory.
samples->AddIntSample(MMU_OVERHEAD, stats.mmu_overhead_bytes);
samples->AddIntSample(VMO, stats.vmo_bytes);
samples->AddIntSample(IPC, stats.ipc_bytes);
samples->AddIntSample(OTHER, stats.other_bytes);
}
void GatherMemory::GatherDeviceProperties() {
const std::string DEVICE_TOTAL = "memory:device_total_bytes";
zx_info_kmem_stats_t stats;
zx_status_t err = zx_object_get_info(RootResource(), ZX_INFO_KMEM_STATS,
&stats, sizeof(stats),
/*actual=*/nullptr, /*avail=*/nullptr);
if (err != ZX_OK) {
FX_LOGS(ERROR) << ZxErrorString("ZX_INFO_KMEM_STATS", err);
return;
}
SampleList list;
list.emplace_back(DEVICE_TOTAL, stats.total_bytes);
DockyardProxyStatus status = Dockyard().SendSampleList(list);
if (status != DockyardProxyStatus::OK) {
FX_LOGS(ERROR) << DockyardErrorString("SendSampleList", status)
<< " The total memory value will be missing";
}
}
void GatherMemory::Gather() {
SampleBundle samples;
AddGlobalMemorySamples(&samples, RootResource());
samples.Upload(DockyardPtr());
}
} // namespace harvester
|
KNpTrue/lua-homebridge | bridge/src/ludplib.c | // Copyright (c) 2021 KNpTrue and homekit-bridge contributors
//
// Licensed under the MIT License.
// You may not use this file except in compliance with the License.
// See [CONTRIBUTORS.md] for the list of homekit-bridge project authors.
#include <lauxlib.h>
#include <pal/udp.h>
#include <HAPBase.h>
#include <HAPLog.h>
#include "lc.h"
#include "app_int.h"
static const HAPLogObject lnet_log = {
.subsystem = APP_BRIDGE_LOG_SUBSYSTEM,
.category = "ludp",
};
#define LUA_UDP_HANDLE_NAME "UdpHandle*"
static const char *net_domain_strs[] = PAL_NET_DOMAIN_STRS;
typedef struct {
pal_udp *udp;
size_t recv_nargs;
size_t err_nargs;
} ludp_handle;
#define LPAL_NET_UDP_GET_HANDLE(L, idx) \
luaL_checkudata(L, idx, LUA_UDP_HANDLE_NAME)
static pal_udp *ludp_to_pcb(lua_State *L, int idx) {
ludp_handle *handle = LPAL_NET_UDP_GET_HANDLE(L, idx);
if (!handle->udp) {
luaL_error(L, "attempt to use a closed handle");
}
return handle->udp;
}
static int ludp_open(lua_State *L) {
pal_net_domain domain = PAL_NET_DOMAIN_COUNT;
const char *str = luaL_checkstring(L, 1);
for (size_t i = 0; i < HAPArrayCount(net_domain_strs); i++) {
if (HAPStringAreEqual(net_domain_strs[i], str)) {
domain = i;
}
}
if (domain == PAL_NET_DOMAIN_COUNT) {
goto err;
}
ludp_handle *handle = lua_newuserdata(L, sizeof(ludp_handle));
luaL_setmetatable(L, LUA_UDP_HANDLE_NAME);
handle->udp = pal_udp_new(domain);
if (!handle->udp) {
goto err;
}
return 1;
err:
luaL_pushfail(L);
return 1;
}
static int ludp_handle_enable_broadcast(lua_State *L) {
pal_udp_enable_broadcast(ludp_to_pcb(L, 1));
return 0;
}
static bool ludp_port_valid(lua_Integer port) {
return ((port >= 0) && (port <= 65535));
}
static int ludp_handle_bind(lua_State *L) {
pal_udp *udp = ludp_to_pcb(L, 1);
const char *addr = luaL_checkstring(L, 2);
lua_Integer port = luaL_checkinteger(L, 3);
if (!ludp_port_valid(port)) {
luaL_argerror(L, 3, "port out of range");
}
lua_pushboolean(L,
pal_udp_bind(udp, addr, (uint16_t)port) == PAL_NET_ERR_OK);
return 1;
}
static int ludp_handle_connect(lua_State *L) {
pal_udp *udp = ludp_to_pcb(L, 1);
const char *addr = luaL_checkstring(L, 2);
lua_Integer port = luaL_checkinteger(L, 3);
if (!ludp_port_valid(port)) {
luaL_argerror(L, 3, "port out of range");
}
lua_pushboolean(L,
pal_udp_connect(udp, addr, (uint16_t)port) == PAL_NET_ERR_OK);
return 1;
}
static int ludp_handle_send(lua_State *L) {
pal_udp *udp = ludp_to_pcb(L, 1);
size_t len;
const char *data = luaL_checklstring(L, 2, &len);
lua_pushboolean(L, pal_udp_send(udp, data, len) == PAL_NET_ERR_OK);
return 1;
}
static int ludp_handle_sendto(lua_State *L) {
pal_udp *udp = ludp_to_pcb(L, 1);
size_t len;
const char *data = luaL_checklstring(L, 2, &len);
const char *addr = luaL_checkstring(L, 3);
lua_Integer port = luaL_checkinteger(L, 4);
if (!ludp_port_valid(port)) {
luaL_argerror(L, 3, "port out of range");
}
lua_pushboolean(L, pal_udp_sendto(udp, data, len, addr, (uint16_t)port) == PAL_NET_ERR_OK);
return 1;
}
static void ludp_recv_cb(pal_udp *udp, void *data, size_t len,
const char *from_addr, uint16_t from_port, void *arg) {
ludp_handle *handle = arg;
lua_State *L = app_get_lua_main_thread();
HAPAssert(lua_gettop(L) == 0);
lc_push_traceback(L);
HAPAssert(lua_rawgetp(L, LUA_REGISTRYINDEX, &handle->recv_nargs) == LUA_TTABLE);
lua_geti(L, 2, 1);
lua_pushlstring(L, (const char *)data, len);
lua_pushstring(L, from_addr);
lua_pushinteger(L, from_port);
for (int i = 2; i <= handle->recv_nargs + 1; i++) {
lua_geti(L, 2, i);
}
lua_remove(L, 2);
if (lua_pcall(L, handle->recv_nargs + 3, 0, 1)) {
HAPLogError(&lnet_log, "%s: %s", __func__, lua_tostring(L, -1));
}
lua_settop(L, 0);
lc_collectgarbage(L);
}
static int ludp_handle_set_recv_cb(lua_State *L) {
ludp_handle *handle = LPAL_NET_UDP_GET_HANDLE(L, 1);
if (!handle->udp) {
luaL_error(L, "attempt to use a closed handle");
}
int n = lua_gettop(L) - 1;
if (n == 0) {
lua_pushnil(L);
lua_rawsetp(L, LUA_REGISTRYINDEX, &handle->recv_nargs);
pal_udp_set_recv_cb(handle->udp, NULL, NULL);
return 0;
}
luaL_argexpected(L, lua_type(L, 2) == LUA_TFUNCTION, 2, "function");
lua_createtable(L, n, 0);
lua_insert(L, 2);
for (int i = n; i >= 1; i--) {
lua_seti(L, 2, i);
}
lua_rawsetp(L, LUA_REGISTRYINDEX, &handle->recv_nargs);
handle->recv_nargs = n - 1;
pal_udp_set_recv_cb(handle->udp, ludp_recv_cb, handle);
return 0;
}
static void ludp_err_cb(pal_udp *udp, pal_net_err err, void *arg) {
ludp_handle *handle = arg;
lua_State *L = app_get_lua_main_thread();
HAPAssert(lua_gettop(L) == 0);
lc_push_traceback(L);
HAPAssert(lua_rawgetp(L, LUA_REGISTRYINDEX, &handle->err_nargs) == LUA_TTABLE);
for (int i = 1; i <= handle->err_nargs + 1; i++) {
lua_geti(L, 2, i);
}
lua_remove(L, 2);
if (lua_pcall(L, handle->err_nargs, 0, 1)) {
HAPLogError(&lnet_log, "%s: %s", __func__, lua_tostring(L, -1));
}
lua_settop(L, 0);
lc_collectgarbage(L);
}
static int ludp_handle_set_err_cb(lua_State *L) {
ludp_handle *handle = LPAL_NET_UDP_GET_HANDLE(L, 1);
if (!handle->udp) {
luaL_error(L, "attempt to use a closed handle");
}
int n = lua_gettop(L) - 1;
if (n == 0) {
lua_pushnil(L);
lua_rawsetp(L, LUA_REGISTRYINDEX, &handle->err_nargs);
pal_udp_set_err_cb(handle->udp, NULL, NULL);
return 0;
}
luaL_argexpected(L, lua_type(L, 2) == LUA_TFUNCTION, 2, "function");
lua_createtable(L, n, 0);
lua_insert(L, 2);
for (int i = n; i >= 1; i--) {
lua_seti(L, 2, i);
}
lua_rawsetp(L, LUA_REGISTRYINDEX, &handle->err_nargs);
handle->err_nargs = n - 1;
pal_udp_set_err_cb(handle->udp, ludp_err_cb, handle);
return 0;
}
static void lhap_net_udp_handle_reset(lua_State *L, ludp_handle *handle) {
if (!handle->udp) {
return;
}
pal_udp_free(handle->udp);
lua_pushnil(L);
lua_rawsetp(L, LUA_REGISTRYINDEX, &handle->recv_nargs);
lua_pushnil(L);
lua_rawsetp(L, LUA_REGISTRYINDEX, &handle->err_nargs);
HAPRawBufferZero(handle, sizeof(*handle));
}
static int ludp_handle_close(lua_State *L) {
ludp_handle *handle = LPAL_NET_UDP_GET_HANDLE(L, 1);
if (!handle->udp) {
luaL_error(L, "attempt to use a closed handle");
}
lhap_net_udp_handle_reset(L, handle);
return 0;
}
static int ludp_handle_gc(lua_State *L) {
lhap_net_udp_handle_reset(L, LPAL_NET_UDP_GET_HANDLE(L, 1));
return 0;
}
static int ludp_handle_tostring(lua_State *L) {
ludp_handle *handle = LPAL_NET_UDP_GET_HANDLE(L, 1);
if (handle->udp) {
lua_pushfstring(L, "UDP handle (%p)", handle->udp);
} else {
lua_pushliteral(L, "UDP handle (closed)");
}
return 1;
}
static const luaL_Reg ludp_funcs[] = {
{"open", ludp_open},
{NULL, NULL},
};
/*
* methods for UdpHandle
*/
static const luaL_Reg ludp_handle_meth[] = {
{"enableBroadcast", ludp_handle_enable_broadcast},
{"bind", ludp_handle_bind},
{"connect", ludp_handle_connect},
{"send", ludp_handle_send},
{"sendto", ludp_handle_sendto},
{"setRecvCb", ludp_handle_set_recv_cb},
{"setErrCb", ludp_handle_set_err_cb},
{"close", ludp_handle_close},
{NULL, NULL}
};
/*
* metamethods for UdpHandle
*/
static const luaL_Reg ludp_handle_metameth[] = {
{"__index", NULL}, /* place holder */
{"__gc", ludp_handle_gc},
{"__close", ludp_handle_gc},
{"__tostring", ludp_handle_tostring},
{NULL, NULL}
};
static void ludp_createmeta(lua_State *L) {
luaL_newmetatable(L, LUA_UDP_HANDLE_NAME); /* metatable for UDP handle */
luaL_setfuncs(L, ludp_handle_metameth, 0); /* add metamethods to new metatable */
luaL_newlibtable(L, ludp_handle_meth); /* create method table */
luaL_setfuncs(L, ludp_handle_meth, 0); /* add udp handle methods to method table */
lua_setfield(L, -2, "__index"); /* metatable.__index = method table */
lua_pop(L, 1); /* pop metatable */
}
LUAMOD_API int luaopen_udp(lua_State *L) {
luaL_newlib(L, ludp_funcs);
ludp_createmeta(L);
return 1;
}
|
apache/lenya | org.apache.lenya.module.navigation/src/main/java/org/apache/lenya/modules/navigation/SiteFragmentGenerator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.lenya.modules.navigation;
import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
import org.apache.avalon.framework.parameters.ParameterException;
import org.apache.avalon.framework.parameters.Parameterizable;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.generation.ServiceableGenerator;
import org.apache.excalibur.source.Source;
import org.apache.excalibur.source.SourceValidity;
import org.apache.lenya.cms.publication.Publication;
import org.apache.lenya.cms.publication.Repository;
import org.apache.lenya.cms.publication.Session;
import org.apache.lenya.cms.site.Link;
import org.apache.lenya.cms.site.SiteException;
import org.apache.lenya.cms.site.SiteNode;
import org.apache.lenya.cms.site.SiteStructure;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
/**
* Generate a fragment of the site.
*/
public class SiteFragmentGenerator extends ServiceableGenerator implements
CacheableProcessingComponent, Parameterizable, NodeGenerator {
protected static final String PARAM_PUB = "pub";
protected static final String PARAM_AREA = "area";
protected static final String PARAM_LANG = "lang";
protected static final String PARAM_PATH = "path";
protected static final String PARAM_SELECTOR_PATH = "selectorPath";
protected static final String PARAM_SELECTOR = "selector";
protected static final String PREFIX = "site";
protected static final String NAMESPACE = "http://apache.org/lenya/site/1.0";
protected static final String ATTR_PUB = "pub";
protected static final String ATTR_AREA = "area";
protected static final String ELEM_FRAGMENT = "fragment";
protected static final String ELEM_NODE = "node";
protected static final String ELEM_LINK = "link";
protected static final String ATTR_UUID = "uuid";
protected static final String ATTR_NAME = "name";
protected static final String XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace";
protected static final String XML_PREFIX = "xml";
protected static final String ATTR_LANG = "lang";
protected static final String ATTR_LABEL = "label";
protected static final String ATTR_CURRENT = "current";
protected static final String ATTR_ANCESTOR_OF_CURRENT = "ancestorOfCurrent";
protected static final String ATTR_HREF = "href";
private SiteStructure site;
private String cacheKey;
private SourceValidity validity;
private String language;
private String selectorClass;
private String path;
private String selectorPath;
private Repository repository;
public void setup(org.apache.cocoon.environment.SourceResolver resolver, Map objectModel,
String src, Parameters params) throws ProcessingException, SAXException, IOException {
super.setup(resolver, objectModel, src, params);
Request request = ObjectModelHelper.getRequest(objectModel);
Source source = null;
try {
String pubId = params.getParameter(PARAM_PUB);
String area = params.getParameter(PARAM_AREA);
this.language = params.getParameter(PARAM_LANG);
this.path = params.getParameter(PARAM_PATH);
this.selectorPath = params.getParameter(PARAM_SELECTOR_PATH, "");
Session session = this.repository.getSession(request);
Publication pub = session.getPublication(pubId);
this.site = pub.getArea(area).getSite();
this.cacheKey = pubId + "/" + area;
source = resolver.resolveURI(this.site.getSourceURI());
this.validity = source.getValidity();
} catch (Exception e) {
throw new ProcessingException("Could not setup transformer: ", e);
} finally {
if (source != null) {
resolver.release(source);
}
}
}
/**
* @return The site structure to generate from.
*/
protected SiteStructure getSite() {
return this.site;
}
/**
* @return The language to generate the fragment for.
*/
protected String getLanguage() {
return this.language;
}
public Serializable getKey() {
if (this.cacheKey == null) {
throw new IllegalStateException("setup() has not been called.");
}
return this.cacheKey;
}
public SourceValidity getValidity() {
if (this.validity == null) {
throw new IllegalStateException("setup() has not been called.");
}
return this.validity;
}
protected String getPath() {
return this.path;
}
public void generate() throws IOException, SAXException, ProcessingException {
this.contentHandler.startDocument();
this.contentHandler.startPrefixMapping(PREFIX, NAMESPACE);
AttributesImpl attrs = new AttributesImpl();
addAttribute(attrs, ATTR_PUB, this.site.getPublication().getId());
addAttribute(attrs, ATTR_AREA, this.site.getArea());
this.contentHandler.startElement(NAMESPACE, ELEM_FRAGMENT, PREFIX + ':' + ELEM_FRAGMENT,
attrs);
generateFragment();
this.contentHandler.endElement(NAMESPACE, ELEM_FRAGMENT, PREFIX + ':' + ELEM_FRAGMENT);
this.contentHandler.endPrefixMapping(PREFIX);
this.contentHandler.endDocument();
}
protected void generateFragment() throws ProcessingException {
try {
FragmentSelector selector = (FragmentSelector) Class.forName(this.selectorClass)
.newInstance();
selector.selectFragment(this, getSite(), this.selectorPath, getLanguage());
} catch (Exception e) {
throw new ProcessingException(e);
}
}
public void startNode(SiteNode node) throws SAXException {
AttributesImpl attrs = new AttributesImpl();
addAttribute(attrs, ATTR_UUID, node.getUuid());
addAttribute(attrs, ATTR_NAME, node.getName());
if (getPath().startsWith(node.getPath() + "/")) {
addAttribute(attrs, ATTR_ANCESTOR_OF_CURRENT, Boolean.toString(true));
}
this.contentHandler.startElement(NAMESPACE, ELEM_NODE, PREFIX + ':' + ELEM_NODE, attrs);
}
public void endNode(SiteNode node) throws SAXException {
this.contentHandler.endElement(NAMESPACE, ELEM_NODE, PREFIX + ':' + ELEM_NODE);
}
public void generateLink(SiteNode node, String language) throws SAXException {
if (node.isVisible() && node.hasLink(language)) {
Link link = getLink(node, language);
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute(XML_NAMESPACE, ATTR_LANG, XML_PREFIX + ":" + ATTR_LANG, "CDATA",
link.getLanguage());
addAttribute(attrs, ATTR_LABEL, link.getLabel());
addAttribute(attrs, ATTR_HREF, getHref(link).getUri());
if (node.getPath().equals(getPath()) && language.equals(getLanguage())) {
addAttribute(attrs, ATTR_CURRENT, Boolean.toString(true));
}
this.contentHandler.startElement(NAMESPACE, ELEM_LINK, PREFIX + ':' + ELEM_LINK, attrs);
this.contentHandler.endElement(NAMESPACE, ELEM_LINK, PREFIX + ':' + ELEM_LINK);
}
}
protected Link getLink(SiteNode node, String language) throws SAXException {
try {
return node.getLink(language);
} catch (SiteException e) {
throw new SAXException(e);
}
}
protected org.apache.lenya.cms.linking.Link getHref(Link link) {
org.apache.lenya.cms.linking.Link href = new org.apache.lenya.cms.linking.Link();
href.setPubId(getSite().getPublication().getId());
href.setArea(getSite().getArea());
href.setUuid(link.getNode().getUuid());
href.setLanguage(link.getLanguage());
return href;
}
protected void addAttribute(AttributesImpl attrs, String name, String value) {
attrs.addAttribute("", name, name, "CDATA", value);
}
public void parameterize(Parameters params) throws ParameterException {
this.selectorClass = params.getParameter(PARAM_SELECTOR);
}
public void setRepository(Repository repository) {
this.repository = repository;
}
}
|
iridium-browser/iridium-browser | components/download/internal/background_service/download_store_unittest.cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/download/internal/background_service/download_store.h"
#include <algorithm>
#include <memory>
#include "base/bind.h"
#include "base/callback.h"
#include "base/guid.h"
#include "base/optional.h"
#include "components/download/internal/background_service/entry.h"
#include "components/download/internal/background_service/proto/entry.pb.h"
#include "components/download/internal/background_service/proto_conversions.h"
#include "components/download/internal/background_service/test/entry_utils.h"
#include "components/leveldb_proto/testing/fake_db.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::_;
namespace download {
class DownloadStoreTest : public testing::Test {
public:
DownloadStoreTest() : db_(nullptr) {}
~DownloadStoreTest() override = default;
void CreateDatabase() {
auto db = std::make_unique<leveldb_proto::test::FakeDB<protodb::Entry>>(
&db_entries_);
db_ = db.get();
store_ = std::make_unique<DownloadStore>(std::move(db));
}
void InitCallback(std::vector<Entry>* loaded_entries,
bool success,
std::unique_ptr<std::vector<Entry>> entries) {
loaded_entries->swap(*entries);
}
void LoadCallback(std::vector<protodb::Entry>* loaded_entries,
bool success,
std::unique_ptr<std::vector<protodb::Entry>> entries) {
loaded_entries->swap(*entries);
}
void RecoverCallback(bool success) { hard_recover_result_ = success; }
MOCK_METHOD1(StoreCallback, void(bool));
void PrepopulateSampleEntries() {
Entry item1 = test::BuildEntry(DownloadClient::TEST, base::GenerateGUID());
Entry item2 = test::BuildEntry(DownloadClient::TEST, base::GenerateGUID());
db_entries_.insert(
std::make_pair(item1.guid, ProtoConversions::EntryToProto(item1)));
db_entries_.insert(
std::make_pair(item2.guid, ProtoConversions::EntryToProto(item2)));
}
protected:
std::map<std::string, protodb::Entry> db_entries_;
leveldb_proto::test::FakeDB<protodb::Entry>* db_;
std::unique_ptr<DownloadStore> store_;
base::Optional<bool> hard_recover_result_;
DISALLOW_COPY_AND_ASSIGN(DownloadStoreTest);
};
TEST_F(DownloadStoreTest, Initialize) {
PrepopulateSampleEntries();
CreateDatabase();
ASSERT_FALSE(store_->IsInitialized());
std::vector<Entry> preloaded_entries;
store_->Initialize(base::BindOnce(&DownloadStoreTest::InitCallback,
base::Unretained(this),
&preloaded_entries));
db_->InitStatusCallback(leveldb_proto::Enums::InitStatus::kOK);
db_->LoadCallback(true);
ASSERT_TRUE(store_->IsInitialized());
ASSERT_EQ(2u, preloaded_entries.size());
}
TEST_F(DownloadStoreTest, HardRecover) {
PrepopulateSampleEntries();
CreateDatabase();
ASSERT_FALSE(store_->IsInitialized());
std::vector<Entry> preloaded_entries;
store_->Initialize(base::BindOnce(&DownloadStoreTest::InitCallback,
base::Unretained(this),
&preloaded_entries));
db_->InitStatusCallback(leveldb_proto::Enums::InitStatus::kOK);
db_->LoadCallback(true);
ASSERT_TRUE(store_->IsInitialized());
ASSERT_EQ(2u, preloaded_entries.size());
store_->HardRecover(base::BindOnce(&DownloadStoreTest::RecoverCallback,
base::Unretained(this)));
ASSERT_FALSE(store_->IsInitialized());
db_->DestroyCallback(true);
db_->InitStatusCallback(leveldb_proto::Enums::InitStatus::kOK);
ASSERT_TRUE(store_->IsInitialized());
ASSERT_TRUE(hard_recover_result_.has_value());
ASSERT_TRUE(hard_recover_result_.value());
}
TEST_F(DownloadStoreTest, HardRecoverDestroyFails) {
PrepopulateSampleEntries();
CreateDatabase();
ASSERT_FALSE(store_->IsInitialized());
std::vector<Entry> preloaded_entries;
store_->Initialize(base::BindOnce(&DownloadStoreTest::InitCallback,
base::Unretained(this),
&preloaded_entries));
db_->InitStatusCallback(leveldb_proto::Enums::InitStatus::kOK);
db_->LoadCallback(true);
ASSERT_TRUE(store_->IsInitialized());
ASSERT_EQ(2u, preloaded_entries.size());
store_->HardRecover(base::BindOnce(&DownloadStoreTest::RecoverCallback,
base::Unretained(this)));
ASSERT_FALSE(store_->IsInitialized());
db_->DestroyCallback(false);
ASSERT_FALSE(store_->IsInitialized());
ASSERT_TRUE(hard_recover_result_.has_value());
ASSERT_FALSE(hard_recover_result_.value());
}
TEST_F(DownloadStoreTest, HardRecoverInitFails) {
PrepopulateSampleEntries();
CreateDatabase();
ASSERT_FALSE(store_->IsInitialized());
std::vector<Entry> preloaded_entries;
store_->Initialize(base::BindOnce(&DownloadStoreTest::InitCallback,
base::Unretained(this),
&preloaded_entries));
db_->InitStatusCallback(leveldb_proto::Enums::InitStatus::kOK);
db_->LoadCallback(true);
ASSERT_TRUE(store_->IsInitialized());
ASSERT_EQ(2u, preloaded_entries.size());
store_->HardRecover(base::BindOnce(&DownloadStoreTest::RecoverCallback,
base::Unretained(this)));
ASSERT_FALSE(store_->IsInitialized());
db_->DestroyCallback(true);
db_->InitStatusCallback(leveldb_proto::Enums::InitStatus::kError);
ASSERT_FALSE(store_->IsInitialized());
ASSERT_TRUE(hard_recover_result_.has_value());
ASSERT_FALSE(hard_recover_result_.value());
}
TEST_F(DownloadStoreTest, Update) {
PrepopulateSampleEntries();
CreateDatabase();
std::vector<Entry> preloaded_entries;
store_->Initialize(base::BindOnce(&DownloadStoreTest::InitCallback,
base::Unretained(this),
&preloaded_entries));
db_->InitStatusCallback(leveldb_proto::Enums::InitStatus::kOK);
db_->LoadCallback(true);
ASSERT_TRUE(store_->IsInitialized());
ASSERT_EQ(2u, preloaded_entries.size());
Entry item1 = test::BuildEntry(DownloadClient::TEST, base::GenerateGUID());
Entry item2 = test::BuildEntry(DownloadClient::TEST, base::GenerateGUID());
EXPECT_CALL(*this, StoreCallback(true)).Times(2);
store_->Update(item1, base::BindOnce(&DownloadStoreTest::StoreCallback,
base::Unretained(this)));
db_->UpdateCallback(true);
store_->Update(item2, base::BindOnce(&DownloadStoreTest::StoreCallback,
base::Unretained(this)));
db_->UpdateCallback(true);
// Query the database directly and check for the entry.
auto protos = std::make_unique<std::vector<protodb::Entry>>();
db_->LoadEntries(base::BindOnce(&DownloadStoreTest::LoadCallback,
base::Unretained(this), protos.get()));
db_->LoadCallback(true);
ASSERT_EQ(4u, protos->size());
ASSERT_TRUE(test::CompareEntryList(
{preloaded_entries[0], preloaded_entries[1], item1, item2},
*ProtoConversions::EntryVectorFromProto(std::move(protos))));
}
TEST_F(DownloadStoreTest, Remove) {
PrepopulateSampleEntries();
CreateDatabase();
std::vector<Entry> preloaded_entries;
store_->Initialize(base::BindOnce(&DownloadStoreTest::InitCallback,
base::Unretained(this),
&preloaded_entries));
db_->InitStatusCallback(leveldb_proto::Enums::InitStatus::kOK);
db_->LoadCallback(true);
ASSERT_EQ(2u, preloaded_entries.size());
// Remove the entry.
EXPECT_CALL(*this, StoreCallback(true)).Times(1);
store_->Remove(preloaded_entries[0].guid,
base::BindOnce(&DownloadStoreTest::StoreCallback,
base::Unretained(this)));
db_->UpdateCallback(true);
// Query the database directly and check for the entry removed.
auto protos = std::make_unique<std::vector<protodb::Entry>>();
db_->LoadEntries(base::BindOnce(&DownloadStoreTest::LoadCallback,
base::Unretained(this), protos.get()));
db_->LoadCallback(true);
ASSERT_EQ(1u, protos->size());
ASSERT_TRUE(test::CompareEntryList(
{preloaded_entries[1]},
*ProtoConversions::EntryVectorFromProto(std::move(protos))));
}
TEST_F(DownloadStoreTest, InitializeFailed) {
PrepopulateSampleEntries();
CreateDatabase();
std::vector<Entry> preloaded_entries;
store_->Initialize(base::BindOnce(&DownloadStoreTest::InitCallback,
base::Unretained(this),
&preloaded_entries));
db_->InitStatusCallback(leveldb_proto::Enums::InitStatus::kError);
ASSERT_FALSE(store_->IsInitialized());
ASSERT_TRUE(preloaded_entries.empty());
}
TEST_F(DownloadStoreTest, InitialLoadFailed) {
PrepopulateSampleEntries();
CreateDatabase();
std::vector<Entry> preloaded_entries;
store_->Initialize(base::BindOnce(&DownloadStoreTest::InitCallback,
base::Unretained(this),
&preloaded_entries));
db_->InitStatusCallback(leveldb_proto::Enums::InitStatus::kOK);
db_->LoadCallback(false);
ASSERT_FALSE(store_->IsInitialized());
ASSERT_TRUE(preloaded_entries.empty());
}
TEST_F(DownloadStoreTest, UnsuccessfulUpdateOrRemove) {
Entry item1 = test::BuildEntry(DownloadClient::TEST, base::GenerateGUID());
CreateDatabase();
std::vector<Entry> entries;
store_->Initialize(base::BindOnce(&DownloadStoreTest::InitCallback,
base::Unretained(this), &entries));
db_->InitStatusCallback(leveldb_proto::Enums::InitStatus::kOK);
db_->LoadCallback(true);
ASSERT_TRUE(store_->IsInitialized());
ASSERT_TRUE(entries.empty());
// Update failed.
EXPECT_CALL(*this, StoreCallback(false)).Times(1);
store_->Update(item1, base::BindOnce(&DownloadStoreTest::StoreCallback,
base::Unretained(this)));
db_->UpdateCallback(false);
// Remove failed.
EXPECT_CALL(*this, StoreCallback(false)).Times(1);
store_->Remove(item1.guid, base::BindOnce(&DownloadStoreTest::StoreCallback,
base::Unretained(this)));
db_->UpdateCallback(false);
}
TEST_F(DownloadStoreTest, AddThenRemove) {
CreateDatabase();
std::vector<Entry> entries;
store_->Initialize(base::BindOnce(&DownloadStoreTest::InitCallback,
base::Unretained(this), &entries));
db_->InitStatusCallback(leveldb_proto::Enums::InitStatus::kOK);
db_->LoadCallback(true);
ASSERT_TRUE(entries.empty());
Entry item1 = test::BuildEntry(DownloadClient::TEST, base::GenerateGUID());
Entry item2 = test::BuildEntry(DownloadClient::TEST, base::GenerateGUID());
EXPECT_CALL(*this, StoreCallback(true)).Times(2);
store_->Update(item1, base::BindOnce(&DownloadStoreTest::StoreCallback,
base::Unretained(this)));
db_->UpdateCallback(true);
store_->Update(item2, base::BindOnce(&DownloadStoreTest::StoreCallback,
base::Unretained(this)));
db_->UpdateCallback(true);
// Query the database directly and check for the entry.
auto protos = std::make_unique<std::vector<protodb::Entry>>();
db_->LoadEntries(base::BindOnce(&DownloadStoreTest::LoadCallback,
base::Unretained(this), protos.get()));
db_->LoadCallback(true);
ASSERT_EQ(2u, protos->size());
// Remove the entry.
EXPECT_CALL(*this, StoreCallback(true)).Times(1);
store_->Remove(item1.guid, base::BindOnce(&DownloadStoreTest::StoreCallback,
base::Unretained(this)));
db_->UpdateCallback(true);
// Query the database directly and check for the entry removed.
protos->clear();
db_->LoadEntries(base::BindOnce(&DownloadStoreTest::LoadCallback,
base::Unretained(this), protos.get()));
db_->LoadCallback(true);
ASSERT_EQ(1u, protos->size());
ASSERT_TRUE(test::CompareEntryList(
{item2}, *ProtoConversions::EntryVectorFromProto(std::move(protos))));
}
} // namespace download
|
aqnotecom/lang.java.cryptology | src/main/java/com/aqnote/shared/cryptology/digest/MD.java | /*
* Copyright 2013-2023 "<NAME>"<<EMAIL>>
* Licensed under the AQNote License, Version 1.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.aqnote.com/licenses/LICENSE-1.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aqnote.shared.cryptology.digest;
import static com.aqnote.shared.cryptology.cert.constant.BCConstant.JCE_PROVIDER;
import static org.apache.commons.lang.StringUtils.isBlank;
import static com.aqnote.shared.cryptology.Constants.UTF_8;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.jcajce.provider.digest.MD2;
import org.bouncycastle.jcajce.provider.digest.MD4;
import org.bouncycastle.jcajce.provider.digest.MD5;
import com.aqnote.shared.cryptology.AQProviderUtil;
import com.aqnote.shared.cryptology.util.lang.ByteUtil;
/**
* 类Md5.java的实现描述:TODO 类实现描述 query OID: http://www.oid-info.com/get/2.16.840.1.101.3.4.2.6
*
* @author "<NAME>"<<EMAIL>> May 8, 2012 1:59:09 PM
*/
public class MD {
private static final String OID_MD2 = PKCSObjectIdentifiers.md2.toString();
private static final String OID_MD4 = PKCSObjectIdentifiers.md4.toString();
private static final String OID_MD5 = PKCSObjectIdentifiers.md5.toString();
static {
AQProviderUtil.addBCProvider();
}
public final static String md2(String src) {
if (isBlank(src)) return "";
try {
return md2(src.getBytes(UTF_8));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
}
public final static String md2(byte[] src) {
if (src == null) return "";
try {
// MessageDigest messageDigest = MessageDigest.getInstance("MD2");
MessageDigest messageDigest = MessageDigest.getInstance(OID_MD2, JCE_PROVIDER);
messageDigest.update(src);
return new String(ByteUtil.toHexBytes(messageDigest.digest()));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
return "";
}
public final static String _md2(byte[] src) {
if (src == null) return "";
MD2.Digest md = new MD2.Digest();
md.update(src);
return new String(ByteUtil.toHexBytes(md.digest()));
}
public final static String md4(String src) {
if (isBlank(src)) return "";
try {
return md4(src.getBytes(UTF_8));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
}
public final static String md4(byte[] src) {
if (src == null) return "";
try {
// MessageDigest messageDigest = MessageDigest.getInstance("MD4");
MessageDigest messageDigest = MessageDigest.getInstance(OID_MD4, JCE_PROVIDER);
messageDigest.update(src);
return new String(ByteUtil.toHexBytes(messageDigest.digest()));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
return "";
}
public final static String _md4(byte[] src) {
if (src == null) return "";
MD4.Digest md = new MD4.Digest();
md.update(src);
return new String(ByteUtil.toHexBytes(md.digest()));
}
public final static String md5(String src) {
if (isBlank(src)) return "";
try {
return md5(src.getBytes(UTF_8));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
}
public final static String md5(byte[] src) {
if (src == null) return "";
try {
// MessageDigest messageDigest = MessageDigest.getInstance("MD5");
MessageDigest messageDigest = MessageDigest.getInstance(OID_MD5, JCE_PROVIDER);
messageDigest.update(src);
return new String(ByteUtil.toHexBytes(messageDigest.digest()));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
return "";
}
public final static String _md5(byte[] src) {
if (src == null) return "";
MD5.Digest md = new MD5.Digest();
return new String(ByteUtil.toHexBytes(md.digest()));
}
}
|
BruceZhang1993/JavaStarterLearning | src/io/github/brucezhang1993/lesson2/Demo.java | <gh_stars>0
package io.github.brucezhang1993.lesson2;
import java.util.Arrays;
/**
* @author bruce
*/
public class Demo {
public static void main(String[] args) {
// Practice 1
// byte 127 => 01111111 => int 127
byte a1 = 127;
// byte 128 => 10000000 => int -128
// byte b1 = 128;
// byte -128 => 10000000 => int -128
byte c1 = -128;
String a2 = Integer.toBinaryString(a1 & 0xff);
String c2 = Integer.toBinaryString(c1 & 0xff);
System.out.println(a2);
System.out.println(c2);
// System.out.println(Integer.toBinaryString(b1 & 0xff));
int a3 = Integer.parseInt(a2, 2);
int c3 = Integer.parseInt(c2, 2);
System.out.println(a3);
System.out.println(c3);
// Practice 2
AnotherInteger i1 = AnotherInteger.valueOf(1024);
AnotherInteger i2 = AnotherInteger.valueOf(1024);
AnotherInteger i3 = AnotherInteger.valueOf(-20);
AnotherInteger i4 = AnotherInteger.valueOf(-20);
System.out.println(i1.getValue());
System.out.println(i2.getValue());
System.out.println(i3.getValue());
System.out.println(i4.getValue());
System.out.println(i1 == i2);
System.out.println(i3 == i4);
// Practice 3
System.out.println(Converter.intFromString("120"));
System.out.println(Converter.longFromString("1245728913"));
System.out.println(Converter.floatFromString("120.134"));
System.out.println(Converter.doubleFromString("10.1122355"));
System.out.println("abcdefg => " + Arrays.toString(Converter.bytesFromString("abcdefg")));
System.out.println(Converter.asString(1200));
System.out.println(Arrays.toString(new byte[]{97, 98, 99, 100}) + " => " + Converter.asString(new byte[] {97, 98, 99, 100}));
// Practice 4
System.out.println("a => " + Converter.char2ascii('a'));
System.out.println("98 => " + Converter.ascii2char(98));
// Practice 5
System.out.println("123 => " + Converter.baseTransform("123", 10, 2));
System.out.println("123 => " + Converter.baseTransform("123", 10, 16));
System.out.println("1111011 => " + Converter.baseTransform("1111011", 2, 10));
System.out.println("7d => " + Converter.baseTransform("7d", 16, 10));
System.out.println("1111011 => " + Converter.baseTransform("1111011", 2, 16));
System.out.println("7d => " + Converter.baseTransform("7d", 16, 2));
}
}
|
felipepessoto/diagnostics | src/SOS/lldbplugin/swift-4.1/lldb/Target/JITLoaderList.h | //===-- JITLoaderList.h -----------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef liblldb_JITLoaderList_h_
#define liblldb_JITLoaderList_h_
#include <mutex>
#include <vector>
#include "lldb/lldb-forward.h"
namespace lldb_private {
//----------------------------------------------------------------------
/// @class JITLoaderList JITLoaderList.h "lldb/Target/JITLoaderList.h"
///
/// Class used by the Process to hold a list of its JITLoaders.
//----------------------------------------------------------------------
class JITLoaderList {
public:
JITLoaderList();
~JITLoaderList();
void Append(const lldb::JITLoaderSP &jit_loader_sp);
void Remove(const lldb::JITLoaderSP &jit_loader_sp);
size_t GetSize() const;
lldb::JITLoaderSP GetLoaderAtIndex(size_t idx);
void DidLaunch();
void DidAttach();
void ModulesDidLoad(ModuleList &module_list);
private:
std::vector<lldb::JITLoaderSP> m_jit_loaders_vec;
std::recursive_mutex m_jit_loaders_mutex;
};
} // namespace lldb_private
#endif // liblldb_JITLoaderList_h_
|
hwalinga/django-computedfields | setup.py | <reponame>hwalinga/django-computedfields<gh_stars>0
from setuptools import setup, find_packages
with open('README.md', 'r') as f:
long_description = f.read()
def get_version(path):
with open(path) as f:
for line in f:
if line.startswith('__version__'):
delim = '"' if '"' in line else "'"
return line.split(delim)[1]
else:
raise RuntimeError('Unable to find version string.')
setup(
name='django-computedfields',
packages=find_packages(exclude=['example']),
include_package_data=True,
install_requires=[],
version=get_version('computedfields/__init__.py'),
license='MIT',
description='autoupdated database fields for model methods',
long_description=long_description,
long_description_content_type='text/markdown',
author='netzkolchose',
author_email='<EMAIL>',
url='https://github.com/netzkolchose/django-computedfields',
download_url='https://github.com/netzkolchose/django-computedfields/archive/0.1.3.tar.gz',
keywords=['django', 'method', 'decorator', 'autoupdate', 'persistent', 'field'],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Database',
'Topic :: Database :: Front-Ends',
'Topic :: Software Development :: Libraries',
'Framework :: Django',
'Framework :: Django :: 2.2',
'Framework :: Django :: 3.0',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8'
],
)
|
cbrz/curly | test/helpers/mock-fs.js | <filename>test/helpers/mock-fs.js
'use strict';
const mockFs = require('mock-fs');
global.mockFs = mockFs;
|
plast-lab/DelphJ | examples/dstm2/manager/BaseManager.java | <filename>examples/dstm2/manager/BaseManager.java
/*
* BaseManager.java
*
* Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, California 95054, U.S.A. All rights reserved.
*
* Sun Microsystems, Inc. has intellectual property rights relating to
* technology embodied in the product that is described in this
* document. In particular, and without limitation, these
* intellectual property rights may include one or more of the
* U.S. patents listed at http://www.sun.com/patents and one or more
* additional patents or pending patent applications in the U.S. and
* in other countries.
*
* U.S. Government Rights - Commercial software.
* Government users are subject to the Sun Microsystems, Inc. standard
* license agreement and applicable provisions of the FAR and its
* supplements. Use is subject to license terms. Sun, Sun
* Microsystems, the Sun logo and Java are trademarks or registered
* trademarks of Sun Microsystems, Inc. in the U.S. and other
* countries.
*
* This product is covered and controlled by U.S. Export Control laws
* and may be subject to the export or import laws in other countries.
* Nuclear, missile, chemical biological weapons or nuclear maritime
* end uses or end users, whether direct or indirect, are strictly
* prohibited. Export or reexport to countries subject to
* U.S. embargo or to entities identified on U.S. export exclusion
* lists, including, but not limited to, the denied persons and
* specially designated nationals lists is strictly prohibited.
*/
package examples.dstm2fromClass.manager;
import examples.dstm2fromClass.ContentionManager;
import examples.dstm2fromClass.Transaction;
import java.util.Collection;
/**
*
* @author mph
*/
public class BaseManager implements ContentionManager {
long priority;
/** Creates a new instance of BaseManager */
public BaseManager() {
priority = 0;
}
public void resolveConflict(Transaction me, Transaction other) {
}
public void resolveConflict(Transaction me, Collection<Transaction> other) {
}
public long getPriority() {
return priority;
}
public void setPriority(long value) {
priority = value;
}
public void openSucceeded() {
}
/**
* Local-spin sleep method -- more accurate than Thread.sleep()
* Difference discovered by <NAME>.
*/
protected void sleep(int ns) {
long startTime = System.nanoTime();
long stopTime = 0;
do {
stopTime = System.nanoTime();
} while((stopTime - startTime) < ns);
}
public void committed() {
}
}
|
Aaz0og/NSI | PROJETS/PROJET V2/Niels Romain 23-12.py | <gh_stars>0
x = [0, 3, 6, 9]
y = [0, 3, 6, 9]
def test(x, y):
sol = 0
stock = 0
for elemy in y:
for elemx1 in x:
print("elemx1:", elemx1, "elemy:", elemy, "Stock:", stock)
if elemx1 - stock == elemy or elemx1 == elemy or elemx1 + stock == elemy:
sol += 1
print("Solution:", sol)
stock = elemx1
return sol
"""
sarix = 0
for i in range(len(x)):
sarix += i
sariy = 0
for i in range(len(y)):
sariy += i
print("SariY",sariy,"SariX",sarix)
"""
def carres(tablex, tabley):
Stocky = 0
Stockx = 0
sol = 0
for arx in tablex:
for ary in tabley:
if carrestest(arx, Stockx, Stocky, ary) == True:
sol += 1
print("Solution:", sol)
Stocky = ary
Stockx = arx
def carrestest(arx, stockx, stocky, ary):
if arx - stockx == ary:
return True
if arx - stockx == ary - stocky:
return True
if arx - stockx == ary + stocky:
return True
if arx + stockx == ary:
return True
if arx + stockx == ary - stocky:
return True
if arx + stockx == ary + stocky:
return True
if arx == ary:
return True
carres(x, y)
def carrestest(arx, stockx, stocky, ary):
if arx - stockx == ary:
return True
if arx - stockx == ary - stocky:
return True
if arx - stockx == ary + stocky:
return True
if arx + stockx == ary:
return True
if arx + stockx == ary - stocky:
return True
if arx + stockx == ary + stocky:
return True
if arx == ary:
return True
sol = 0
"""
for ax in x:
for bx in x:
for ay in y:
for by in y:
if carrestest(ax,bx,by,ay)== True:
sol+=1
print(sol)
"""
def trouvercarres(x, y):
sol = 0
for lentx in x:
for rapidex in x:
for lenty in y:
for rapidey in y:
if rapidex - lentx == rapidey - lenty:
sol += 1
return sol
def carrestestcomplique(x, y):
xlist = list()
ylist = list()
grosse_liste = list()
print(len(x), len(y))
for i in range(len(x)):
try:
xlist.append(x[i + 1] - x[i])
except IndexError:
xlist.append(x[i])
for i in range(len(y)):
try:
ylist.append(y[i + 1] - y[i])
except IndexError:
ylist.append(y[i])
print(xlist, ylist)
grosse_liste += xlist + ylist
grosse_liste = xlist + list(set(ylist) - set(xlist))
print(grosse_liste)
"""
sol =0
for xgrosse in grosse_liste:
for ygrosse in grosse_liste:
if xgrosse == ygrosse:
sol +=1
return sol
"""
return len(grosse_liste)
def carrecoordonnes(lstx, lsty):
coordx = list()
coordy = list()
for lentx in range(len(lstx)):
try:
coordx.append(lstx[lentx])
coordx.append(lstx[lentx + 1])
except IndexError:
coordx.append(lstx[lentx])
# coordx.append(lstx[lentx])
for lenty in range(len(lsty)):
try:
coordy.append(lsty[lenty])
coordy.append(lsty[lenty + 1])
except IndexError:
coordy.append(lsty[lenty])
# coordy.append(lsty[lenty])
return coordx, coordy
|
rio-31/android_frameworks_base-1 | services/core/java/com/android/server/wm/ConfigurationContainer.java | /*
* Copyright (C) 2017 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
*/
package com.android.server.wm;
import static android.app.WindowConfiguration.ACTIVITY_TYPE_ASSISTANT;
import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME;
import static android.app.WindowConfiguration.ACTIVITY_TYPE_RECENTS;
import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
import static android.app.WindowConfiguration.activityTypeToString;
import static android.app.WindowConfiguration.windowingModeToString;
import static com.android.server.wm.ConfigurationContainerProto.FULL_CONFIGURATION;
import static com.android.server.wm.ConfigurationContainerProto.MERGED_OVERRIDE_CONFIGURATION;
import static com.android.server.wm.ConfigurationContainerProto.OVERRIDE_CONFIGURATION;
import android.annotation.CallSuper;
import android.app.WindowConfiguration;
import android.content.res.Configuration;
import android.graphics.Point;
import android.graphics.Rect;
import android.util.proto.ProtoOutputStream;
import com.android.internal.annotations.VisibleForTesting;
import java.io.PrintWriter;
import java.util.ArrayList;
/**
* Contains common logic for classes that have override configurations and are organized in a
* hierarchy.
*/
public abstract class ConfigurationContainer<E extends ConfigurationContainer> {
/**
* {@link #Rect} returned from {@link #getRequestedOverrideBounds()} to prevent original value
* from being set directly.
*/
private Rect mReturnBounds = new Rect();
/**
* Contains requested override configuration settings applied to this configuration container.
*/
private Configuration mRequestedOverrideConfiguration = new Configuration();
/**
* Contains the requested override configuration with parent and policy constraints applied.
* This is the set of overrides that gets applied to the full and merged configurations.
*/
private Configuration mResolvedOverrideConfiguration = new Configuration();
/** True if mRequestedOverrideConfiguration is not empty */
private boolean mHasOverrideConfiguration;
/**
* Contains full configuration applied to this configuration container. Corresponds to full
* parent's config with applied {@link #mResolvedOverrideConfiguration}.
*/
private Configuration mFullConfiguration = new Configuration();
/** The bit mask of the last override fields of full configuration. */
private int mLastOverrideConfigurationChanges;
/**
* Contains merged override configuration settings from the top of the hierarchy down to this
* particular instance. It is different from {@link #mFullConfiguration} because it starts from
* topmost container's override config instead of global config.
*/
private Configuration mMergedOverrideConfiguration = new Configuration();
private ArrayList<ConfigurationContainerListener> mChangeListeners = new ArrayList<>();
// TODO: Can't have ag/2592611 soon enough!
private final Configuration mTmpConfig = new Configuration();
// Used for setting bounds
private final Rect mTmpRect = new Rect();
static final int BOUNDS_CHANGE_NONE = 0;
// Return value from {@link setBounds} indicating the position of the override bounds changed.
static final int BOUNDS_CHANGE_POSITION = 1;
// Return value from {@link setBounds} indicating the size of the override bounds changed.
static final int BOUNDS_CHANGE_SIZE = 1 << 1;
/**
* Returns full configuration applied to this configuration container.
* This method should be used for getting settings applied in each particular level of the
* hierarchy.
*/
public Configuration getConfiguration() {
return mFullConfiguration;
}
/** Returns the last changes from applying override configuration. */
int getLastOverrideConfigurationChanges() {
return mLastOverrideConfigurationChanges;
}
/**
* Notify that parent config changed and we need to update full configuration.
* @see #mFullConfiguration
*/
public void onConfigurationChanged(Configuration newParentConfig) {
mTmpConfig.setTo(mResolvedOverrideConfiguration);
resolveOverrideConfiguration(newParentConfig);
mFullConfiguration.setTo(newParentConfig);
mLastOverrideConfigurationChanges =
mFullConfiguration.updateFrom(mResolvedOverrideConfiguration);
if (!mTmpConfig.equals(mResolvedOverrideConfiguration)) {
onMergedOverrideConfigurationChanged();
// This depends on the assumption that change-listeners don't do
// their own override resolution. This way, dependent hierarchies
// can stay properly synced-up with a primary hierarchy's constraints.
// Since the hierarchies will be merged, this whole thing will go away
// before the assumption will be broken.
// Inform listeners of the change.
for (int i = mChangeListeners.size() - 1; i >= 0; --i) {
mChangeListeners.get(i).onRequestedOverrideConfigurationChanged(
mResolvedOverrideConfiguration);
}
}
for (int i = getChildCount() - 1; i >= 0; --i) {
final ConfigurationContainer child = getChildAt(i);
child.onConfigurationChanged(mFullConfiguration);
}
}
/**
* Resolves the current requested override configuration into
* {@link #mResolvedOverrideConfiguration}
*
* @param newParentConfig The new parent configuration to resolve overrides against.
*/
void resolveOverrideConfiguration(Configuration newParentConfig) {
mResolvedOverrideConfiguration.setTo(mRequestedOverrideConfiguration);
}
/** Returns requested override configuration applied to this configuration container. */
public Configuration getRequestedOverrideConfiguration() {
return mRequestedOverrideConfiguration;
}
/** Returns the resolved override configuration. */
Configuration getResolvedOverrideConfiguration() {
return mResolvedOverrideConfiguration;
}
/**
* Update override configuration and recalculate full config.
* @see #mRequestedOverrideConfiguration
* @see #mFullConfiguration
*/
public void onRequestedOverrideConfigurationChanged(Configuration overrideConfiguration) {
// Pre-compute this here, so we don't need to go through the entire Configuration when
// writing to proto (which has significant cost if we write a lot of empty configurations).
mHasOverrideConfiguration = !Configuration.EMPTY.equals(overrideConfiguration);
mRequestedOverrideConfiguration.setTo(overrideConfiguration);
// Update full configuration of this container and all its children.
final ConfigurationContainer parent = getParent();
onConfigurationChanged(parent != null ? parent.getConfiguration() : Configuration.EMPTY);
}
/**
* Get merged override configuration from the top of the hierarchy down to this particular
* instance. This should be reported to client as override config.
*/
public Configuration getMergedOverrideConfiguration() {
return mMergedOverrideConfiguration;
}
/**
* Update merged override configuration based on corresponding parent's config and notify all
* its children. If there is no parent, merged override configuration will set equal to current
* override config.
* @see #mMergedOverrideConfiguration
*/
void onMergedOverrideConfigurationChanged() {
final ConfigurationContainer parent = getParent();
if (parent != null) {
mMergedOverrideConfiguration.setTo(parent.getMergedOverrideConfiguration());
mMergedOverrideConfiguration.updateFrom(mResolvedOverrideConfiguration);
} else {
mMergedOverrideConfiguration.setTo(mResolvedOverrideConfiguration);
}
for (int i = getChildCount() - 1; i >= 0; --i) {
final ConfigurationContainer child = getChildAt(i);
child.onMergedOverrideConfigurationChanged();
}
}
/**
* Indicates whether this container has not requested any bounds different from its parent. In
* this case, it will inherit the bounds of the first ancestor which specifies a bounds subject
* to policy constraints.
*
* @return {@code true} if no explicit bounds have been requested at this container level.
* {@code false} otherwise.
*/
public boolean matchParentBounds() {
return getRequestedOverrideBounds().isEmpty();
}
/**
* Returns whether the bounds specified are considered the same as the existing requested
* override bounds. This is either when the two bounds are equal or the requested override
* bounds are empty and the specified bounds is null.
*
* @return {@code true} if the bounds are equivalent, {@code false} otherwise
*/
public boolean equivalentRequestedOverrideBounds(Rect bounds) {
return equivalentBounds(getRequestedOverrideBounds(), bounds);
}
/**
* Returns whether the two bounds are equal to each other or are a combination of null or empty.
*/
public static boolean equivalentBounds(Rect bounds, Rect other) {
return bounds == other
|| (bounds != null && (bounds.equals(other) || (bounds.isEmpty() && other == null)))
|| (other != null && other.isEmpty() && bounds == null);
}
/**
* Returns the effective bounds of this container, inheriting the first non-empty bounds set in
* its ancestral hierarchy, including itself.
* @return
*/
public Rect getBounds() {
mReturnBounds.set(getConfiguration().windowConfiguration.getBounds());
return mReturnBounds;
}
public void getBounds(Rect outBounds) {
outBounds.set(getBounds());
}
/**
* Sets {@code out} to the top-left corner of the bounds as returned by {@link #getBounds()}.
*/
public void getPosition(Point out) {
Rect bounds = getBounds();
out.set(bounds.left, bounds.top);
}
/**
* Returns the bounds requested on this container. These may not be the actual bounds the
* container ends up with due to policy constraints. The {@link Rect} handed back is
* shared for all calls to this method and should not be modified.
*/
public Rect getRequestedOverrideBounds() {
mReturnBounds.set(getRequestedOverrideConfiguration().windowConfiguration.getBounds());
return mReturnBounds;
}
/**
* Returns {@code true} if the {@link WindowConfiguration} in the requested override
* {@link Configuration} specifies bounds.
*/
public boolean hasOverrideBounds() {
return !getRequestedOverrideBounds().isEmpty();
}
/**
* Sets the passed in {@link Rect} to the current bounds.
* @see {@link #getRequestedOverrideBounds()}.
*/
public void getRequestedOverrideBounds(Rect outBounds) {
outBounds.set(getRequestedOverrideBounds());
}
/**
* Sets the bounds at the current hierarchy level, overriding any bounds set on an ancestor.
* This value will be reported when {@link #getBounds()} and
* {@link #getRequestedOverrideBounds()}. If
* an empty {@link Rect} or null is specified, this container will be considered to match its
* parent bounds {@see #matchParentBounds} and will inherit bounds from its parent.
* @param bounds The bounds defining the container size.
* @return a bitmask representing the types of changes made to the bounds.
*/
public int setBounds(Rect bounds) {
int boundsChange = diffRequestedOverrideBounds(bounds);
if (boundsChange == BOUNDS_CHANGE_NONE) {
return boundsChange;
}
mTmpConfig.setTo(getRequestedOverrideConfiguration());
mTmpConfig.windowConfiguration.setBounds(bounds);
onRequestedOverrideConfigurationChanged(mTmpConfig);
return boundsChange;
}
public int setBounds(int left, int top, int right, int bottom) {
mTmpRect.set(left, top, right, bottom);
return setBounds(mTmpRect);
}
int diffRequestedOverrideBounds(Rect bounds) {
if (equivalentRequestedOverrideBounds(bounds)) {
return BOUNDS_CHANGE_NONE;
}
int boundsChange = BOUNDS_CHANGE_NONE;
final Rect existingBounds = getRequestedOverrideBounds();
if (bounds == null || existingBounds.left != bounds.left
|| existingBounds.top != bounds.top) {
boundsChange |= BOUNDS_CHANGE_POSITION;
}
if (bounds == null || existingBounds.width() != bounds.width()
|| existingBounds.height() != bounds.height()) {
boundsChange |= BOUNDS_CHANGE_SIZE;
}
return boundsChange;
}
boolean hasOverrideConfiguration() {
return mHasOverrideConfiguration;
}
public WindowConfiguration getWindowConfiguration() {
return mFullConfiguration.windowConfiguration;
}
/** Returns the windowing mode the configuration container is currently in. */
public int getWindowingMode() {
return mFullConfiguration.windowConfiguration.getWindowingMode();
}
/** Returns the windowing mode override that is requested by this container. */
public int getRequestedOverrideWindowingMode() {
return mRequestedOverrideConfiguration.windowConfiguration.getWindowingMode();
}
/** Sets the requested windowing mode override for the configuration container. */
public void setWindowingMode(/*@WindowConfiguration.WindowingMode*/ int windowingMode) {
mTmpConfig.setTo(getRequestedOverrideConfiguration());
mTmpConfig.windowConfiguration.setWindowingMode(windowingMode);
onRequestedOverrideConfigurationChanged(mTmpConfig);
}
/** Sets the always on top flag for this configuration container.
* When you call this function, make sure that the following functions are called as well to
* keep proper z-order.
* - {@Link DisplayContent#positionStackAt(POSITION_TOP, TaskStack)};
* - {@Link ActivityDisplay#positionChildAtTop(ActivityStack)};
* */
public void setAlwaysOnTop(boolean alwaysOnTop) {
mTmpConfig.setTo(getRequestedOverrideConfiguration());
mTmpConfig.windowConfiguration.setAlwaysOnTop(alwaysOnTop);
onRequestedOverrideConfigurationChanged(mTmpConfig);
}
/** Sets the windowing mode for the configuration container. */
void setDisplayWindowingMode(int windowingMode) {
mTmpConfig.setTo(getRequestedOverrideConfiguration());
mTmpConfig.windowConfiguration.setDisplayWindowingMode(windowingMode);
onRequestedOverrideConfigurationChanged(mTmpConfig);
}
/**
* Returns true if this container is currently in multi-window mode. I.e. sharing the screen
* with another activity.
*/
public boolean inMultiWindowMode() {
/*@WindowConfiguration.WindowingMode*/ int windowingMode =
mFullConfiguration.windowConfiguration.getWindowingMode();
return windowingMode != WINDOWING_MODE_FULLSCREEN
&& windowingMode != WINDOWING_MODE_UNDEFINED;
}
/** Returns true if this container is currently in split-screen windowing mode. */
public boolean inSplitScreenWindowingMode() {
/*@WindowConfiguration.WindowingMode*/ int windowingMode =
mFullConfiguration.windowConfiguration.getWindowingMode();
return windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY
|| windowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
}
/** Returns true if this container is currently in split-screen secondary windowing mode. */
public boolean inSplitScreenSecondaryWindowingMode() {
/*@WindowConfiguration.WindowingMode*/ int windowingMode =
mFullConfiguration.windowConfiguration.getWindowingMode();
return windowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
}
public boolean inSplitScreenPrimaryWindowingMode() {
return mFullConfiguration.windowConfiguration.getWindowingMode()
== WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
}
/**
* Returns true if this container can be put in either
* {@link WindowConfiguration#WINDOWING_MODE_SPLIT_SCREEN_PRIMARY} or
* {@link WindowConfiguration##WINDOWING_MODE_SPLIT_SCREEN_SECONDARY} windowing modes based on
* its current state.
*/
public boolean supportsSplitScreenWindowingMode() {
return mFullConfiguration.windowConfiguration.supportSplitScreenWindowingMode();
}
public boolean inPinnedWindowingMode() {
return mFullConfiguration.windowConfiguration.getWindowingMode() == WINDOWING_MODE_PINNED;
}
public boolean inFreeformWindowingMode() {
return mFullConfiguration.windowConfiguration.getWindowingMode() == WINDOWING_MODE_FREEFORM;
}
/** Returns the activity type associated with the the configuration container. */
/*@WindowConfiguration.ActivityType*/
public int getActivityType() {
return mFullConfiguration.windowConfiguration.getActivityType();
}
/** Sets the activity type to associate with the configuration container. */
public void setActivityType(/*@WindowConfiguration.ActivityType*/ int activityType) {
int currentActivityType = getActivityType();
if (currentActivityType == activityType) {
return;
}
if (currentActivityType != ACTIVITY_TYPE_UNDEFINED) {
throw new IllegalStateException("Can't change activity type once set: " + this
+ " activityType=" + activityTypeToString(activityType));
}
mTmpConfig.setTo(getRequestedOverrideConfiguration());
mTmpConfig.windowConfiguration.setActivityType(activityType);
onRequestedOverrideConfigurationChanged(mTmpConfig);
}
public boolean isActivityTypeHome() {
return getActivityType() == ACTIVITY_TYPE_HOME;
}
public boolean isActivityTypeRecents() {
return getActivityType() == ACTIVITY_TYPE_RECENTS;
}
public boolean isActivityTypeAssistant() {
return getActivityType() == ACTIVITY_TYPE_ASSISTANT;
}
public boolean isActivityTypeStandard() {
return getActivityType() == ACTIVITY_TYPE_STANDARD;
}
public boolean isActivityTypeStandardOrUndefined() {
/*@WindowConfiguration.ActivityType*/ final int activityType = getActivityType();
return activityType == ACTIVITY_TYPE_STANDARD || activityType == ACTIVITY_TYPE_UNDEFINED;
}
public boolean hasCompatibleActivityType(ConfigurationContainer other) {
/*@WindowConfiguration.ActivityType*/ int thisType = getActivityType();
/*@WindowConfiguration.ActivityType*/ int otherType = other.getActivityType();
if (thisType == otherType) {
return true;
}
if (thisType == ACTIVITY_TYPE_ASSISTANT) {
// Assistant activities are only compatible with themselves...
return false;
}
// Otherwise we are compatible if us or other is not currently defined.
return thisType == ACTIVITY_TYPE_UNDEFINED || otherType == ACTIVITY_TYPE_UNDEFINED;
}
/**
* Returns true if this container is compatible with the input windowing mode and activity type.
* The container is compatible:
* - If {@param activityType} and {@param windowingMode} match this container activity type and
* windowing mode.
* - If {@param activityType} is {@link WindowConfiguration#ACTIVITY_TYPE_UNDEFINED} or
* {@link WindowConfiguration#ACTIVITY_TYPE_STANDARD} and this containers activity type is also
* standard or undefined and its windowing mode matches {@param windowingMode}.
* - If {@param activityType} isn't {@link WindowConfiguration#ACTIVITY_TYPE_UNDEFINED} or
* {@link WindowConfiguration#ACTIVITY_TYPE_STANDARD} or this containers activity type isn't
* also standard or undefined and its activity type matches {@param activityType} regardless of
* if {@param windowingMode} matches the containers windowing mode.
*/
public boolean isCompatible(int windowingMode, int activityType) {
final int thisActivityType = getActivityType();
final int thisWindowingMode = getWindowingMode();
final boolean sameActivityType = thisActivityType == activityType;
final boolean sameWindowingMode = thisWindowingMode == windowingMode;
if (sameActivityType && sameWindowingMode) {
return true;
}
if ((activityType != ACTIVITY_TYPE_UNDEFINED && activityType != ACTIVITY_TYPE_STANDARD)
|| !isActivityTypeStandardOrUndefined()) {
// Only activity type need to match for non-standard activity types that are defined.
return sameActivityType;
}
// Otherwise we are compatible if the windowing mode is the same.
return sameWindowingMode;
}
public void registerConfigurationChangeListener(ConfigurationContainerListener listener) {
if (mChangeListeners.contains(listener)) {
return;
}
mChangeListeners.add(listener);
listener.onRequestedOverrideConfigurationChanged(mResolvedOverrideConfiguration);
}
public void unregisterConfigurationChangeListener(ConfigurationContainerListener listener) {
mChangeListeners.remove(listener);
}
@VisibleForTesting
boolean containsListener(ConfigurationContainerListener listener) {
return mChangeListeners.contains(listener);
}
/**
* Must be called when new parent for the container was set.
*/
void onParentChanged() {
final ConfigurationContainer parent = getParent();
// Removing parent usually means that we've detached this entity to destroy it or to attach
// to another parent. In both cases we don't need to update the configuration now.
if (parent != null) {
// Update full configuration of this container and all its children.
onConfigurationChanged(parent.mFullConfiguration);
// Update merged override configuration of this container and all its children.
onMergedOverrideConfigurationChanged();
}
}
/**
* Write to a protocol buffer output stream. Protocol buffer message definition is at
* {@link com.android.server.wm.ConfigurationContainerProto}.
*
* @param proto Stream to write the ConfigurationContainer object to.
* @param fieldId Field Id of the ConfigurationContainer as defined in the parent
* message.
* @param logLevel Determines the amount of data to be written to the Protobuf.
* @hide
*/
@CallSuper
protected void writeToProto(ProtoOutputStream proto, long fieldId,
@WindowTraceLogLevel int logLevel) {
// Critical log level logs only visible elements to mitigate performance overheard
if (logLevel != WindowTraceLogLevel.ALL && !mHasOverrideConfiguration) {
return;
}
final long token = proto.start(fieldId);
mRequestedOverrideConfiguration.writeToProto(proto, OVERRIDE_CONFIGURATION,
logLevel == WindowTraceLogLevel.CRITICAL);
if (logLevel == WindowTraceLogLevel.ALL) {
mFullConfiguration.writeToProto(proto, FULL_CONFIGURATION, false /* critical */);
mMergedOverrideConfiguration.writeToProto(proto, MERGED_OVERRIDE_CONFIGURATION,
false /* critical */);
}
proto.end(token);
}
/**
* Dumps the names of this container children in the input print writer indenting each
* level with the input prefix.
*/
public void dumpChildrenNames(PrintWriter pw, String prefix) {
final String childPrefix = prefix + " ";
pw.println(getName()
+ " type=" + activityTypeToString(getActivityType())
+ " mode=" + windowingModeToString(getWindowingMode())
+ " override-mode=" + windowingModeToString(getRequestedOverrideWindowingMode()));
for (int i = getChildCount() - 1; i >= 0; --i) {
final E cc = getChildAt(i);
pw.print(childPrefix + "#" + i + " ");
cc.dumpChildrenNames(pw, childPrefix);
}
}
String getName() {
return toString();
}
public boolean isAlwaysOnTop() {
return mFullConfiguration.windowConfiguration.isAlwaysOnTop();
}
abstract protected int getChildCount();
abstract protected E getChildAt(int index);
abstract protected ConfigurationContainer getParent();
}
|
io7m/cardant | com.io7m.cardant.protocol.inventory.v1/src/main/java/com/io7m/cardant/protocol/inventory/v1/beans/impl/ListLocationsBehaviourDocumentImpl.java | <gh_stars>0
/*
* An XML document type.
* Localname: ListLocationsBehaviour
* Namespace: urn:com.io7m.cardant.inventory:1
* Java type: com.io7m.cardant.protocol.inventory.v1.beans.ListLocationsBehaviourDocument
*
* Automatically generated - do not modify.
*/
package com.io7m.cardant.protocol.inventory.v1.beans.impl;
import javax.xml.namespace.QName;
import org.apache.xmlbeans.QNameSet;
/**
* A document containing one ListLocationsBehaviour(@urn:com.io7m.cardant.inventory:1) element.
*
* This is a complex type.
*/
public class ListLocationsBehaviourDocumentImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements com.io7m.cardant.protocol.inventory.v1.beans.ListLocationsBehaviourDocument {
private static final long serialVersionUID = 1L;
public ListLocationsBehaviourDocumentImpl(org.apache.xmlbeans.SchemaType sType) {
super(sType);
}
private static final QName[] PROPERTY_QNAME = {
new QName("urn:com.io7m.cardant.inventory:1", "ListLocationsBehaviour"),
};
private static final QNameSet[] PROPERTY_QSET = {
QNameSet.forArray( new QName[] {
new QName("urn:com.io7m.cardant.inventory:1", "ListLocationsAll"),
new QName("urn:com.io7m.cardant.inventory:1", "ListLocationWithDescendants"),
new QName("urn:com.io7m.cardant.inventory:1", "ListLocationsBehaviour"),
new QName("urn:com.io7m.cardant.inventory:1", "ListLocationExact"),
}),
};
/**
* Gets the "ListLocationsBehaviour" element
*/
@Override
public com.io7m.cardant.protocol.inventory.v1.beans.ListLocationsBehaviourType getListLocationsBehaviour() {
synchronized (monitor()) {
check_orphaned();
com.io7m.cardant.protocol.inventory.v1.beans.ListLocationsBehaviourType target = null;
target = (com.io7m.cardant.protocol.inventory.v1.beans.ListLocationsBehaviourType)get_store().find_element_user(PROPERTY_QSET[0], 0);
return (target == null) ? null : target;
}
}
/**
* Sets the "ListLocationsBehaviour" element
*/
@Override
public void setListLocationsBehaviour(com.io7m.cardant.protocol.inventory.v1.beans.ListLocationsBehaviourType listLocationsBehaviour) {
synchronized (monitor()) {
check_orphaned();
com.io7m.cardant.protocol.inventory.v1.beans.ListLocationsBehaviourType target = null;
target = (com.io7m.cardant.protocol.inventory.v1.beans.ListLocationsBehaviourType)get_store().find_element_user(PROPERTY_QSET[0], 0);
if (target == null) {
target = (com.io7m.cardant.protocol.inventory.v1.beans.ListLocationsBehaviourType)get_store().add_element_user(PROPERTY_QNAME[0]);
}
target.set(listLocationsBehaviour);
}
}
/**
* Appends and returns a new empty "ListLocationsBehaviour" element
*/
@Override
public com.io7m.cardant.protocol.inventory.v1.beans.ListLocationsBehaviourType addNewListLocationsBehaviour() {
synchronized (monitor()) {
check_orphaned();
com.io7m.cardant.protocol.inventory.v1.beans.ListLocationsBehaviourType target = null;
target = (com.io7m.cardant.protocol.inventory.v1.beans.ListLocationsBehaviourType)get_store().add_element_user(PROPERTY_QNAME[0]);
return target;
}
}
}
|
fengwenkai/DEV | wish-pay-web/src/main/java/com/wish/pay/web/exception/ErrorCode.java | package com.wish.pay.web.exception;
public enum ErrorCode {
BAD_REQUEST(400, 400), UNAUTHORIZED(401, 401), FORBIDDEN(403, 403), INTERNAL_SERVER_ERROR(500, 500),
BOOK_STATUS_WRONG(1100, 400), BOOK_OWNERSHIP_WRONG(1101, 403), NO_TOKEN(1102, 401);
public int code;
public int httpStatus;
ErrorCode(int code, int httpStatus) {
this.code = code;
this.httpStatus = httpStatus;
}
}
|
intellstartup/django-caravaggio-rest-api | src/caravaggio_rest_api/users/api/permissions.py | <gh_stars>0
# -*- coding: utf-8 -*
# Copyright (c) 2019 BuildGroup Data Services, Inc.
# All rights reserved.
# This software is proprietary and confidential and may not under
# any circumstances be used, copied, or distributed.
from django.contrib.auth.models import AnonymousUser
from rest_framework import permissions
class ClientAdminPermission(permissions.BasePermission):
"""
Global permission check for blacklisted IPs.
"""
def has_permission(self, request, view):
if isinstance(request.user, AnonymousUser):
return False
permission = bool((request.user and request.user.is_staff) or (request.user and request.user.is_client_staff))
return permission
class OrganizationAdminPermission(permissions.BasePermission):
"""
Permission check for users that are owners of an organization
or are part of the administrators list of an organization
"""
def has_permission(self, request, view):
if isinstance(request.user, AnonymousUser):
return False
permission = bool(
(request.user and request.user.is_staff)
or (request.user and request.user.is_client_staff)
or (request.user.owner_of.count())
or (request.user.administrator_of.count())
)
return permission
class OrganizationUserAdminPermission(OrganizationAdminPermission):
def has_object_permission(self, request, view, user):
# Super user
if request.user and request.user.is_staff:
return True
# The user are from different client (external system)
if request.user.client.id != user.client.id:
return False
# Super user of the same organization
if request.user and request.user.is_client_staff:
return True
# Let's see if the authenticated user is administrator of any of the
# organizations the user object is a member of.
admin_of = request.user.owner_of.all().union(request.user.administrator_of.all()).distinct()
user_organizations = (
user.member_of.all()
.union(user.restricted_member_of.all())
.union(user.administrator_of.all())
.union(user.owner_of.all())
.distinct()
)
return bool(len(set(admin_of).intersection(user_organizations)))
|
kavahub/learnjava | core-java/core-java-lang/src/main/java/io/github/kavahub/learnjava/math/CombinationUseApacheCommonsExample.java | package io.github.kavahub.learnjava.math;
import java.util.Arrays;
import java.util.Iterator;
import org.apache.commons.math3.util.CombinatoricsUtils;
/**
*
* 排列组合,使用commons库
*
* @author <NAME>
* @since 1.0.0
*/
public class CombinationUseApacheCommonsExample {
private static final int N = 6;
private static final int R = 3;
/**
* Print all combinations of r elements from a set
* @param n - number of elements in set
* @param r - number of elements in selection
*/
public static void generate(int n, int r) {
Iterator<int[]> iterator = CombinatoricsUtils.combinationsIterator(n, r);
while (iterator.hasNext()) {
final int[] combination = iterator.next();
System.out.println(Arrays.toString(combination));
}
}
public static void main(String[] args) {
generate(N, R);
}
}
|
914802951/sdl_core_v4.0_winceport | src/components/connection_handler/test/heart_beat_monitor_test.cc | /*
* Copyright (c) 2013-2014, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of the Ford Motor Company nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <string>
#include <iostream>
#include "gtest/gtest.h"
#include "connection_handler/heartbeat_monitor.h"
#include "connection_handler/connection.h"
#include "connection_handler/connection_handler.h"
#include "connection_handler/mock_connection_handler.h"
namespace {
const int32_t MILLISECONDS_IN_SECOND = 1000;
const int32_t MICROSECONDS_IN_MILLISECONDS = 1000;
const int32_t MICROSECONDS_IN_SECOND = 1000 * 1000;
}
namespace test {
namespace components {
namespace connection_handler_test {
using ::testing::_;
class HeartBeatMonitorTest : public testing::Test {
public:
HeartBeatMonitorTest() : conn(NULL) {
kTimeout = 5000u;
}
protected:
testing::NiceMock<MockConnectionHandler> connection_handler_mock;
connection_handler::Connection* conn;
uint32_t kTimeout;
static const connection_handler::ConnectionHandle kConnectionHandle =
0xABCDEF;
virtual void SetUp() {
conn = new connection_handler::Connection(
kConnectionHandle, 0, &connection_handler_mock, kTimeout);
}
virtual void TearDown() { delete conn; }
};
ACTION_P2(RemoveSession, conn, session_id) { conn->RemoveSession(session_id); }
TEST_F(HeartBeatMonitorTest, TimerNotStarted) {
// Whithout StartHeartBeat nothing to be call
EXPECT_CALL(connection_handler_mock, CloseSession(_, _)).Times(0);
EXPECT_CALL(connection_handler_mock, CloseConnection(_)).Times(0);
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, _)).Times(0);
conn->AddNewSession();
testing::Mock::AsyncVerifyAndClearExpectations(kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND);
}
TEST_F(HeartBeatMonitorTest, TimerNotElapsed) {
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, _)).Times(0);
EXPECT_CALL(connection_handler_mock, CloseSession(_, _)).Times(0);
EXPECT_CALL(connection_handler_mock, CloseConnection(_)).Times(0);
const uint32_t session = conn->AddNewSession();
conn->StartHeartBeat(session);
testing::Mock::AsyncVerifyAndClearExpectations(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND);
}
TEST_F(HeartBeatMonitorTest, TimerElapsed) {
const uint32_t session = conn->AddNewSession();
EXPECT_CALL(connection_handler_mock, CloseSession(_, session, _))
.WillOnce(RemoveSession(conn, session));
EXPECT_CALL(connection_handler_mock, CloseConnection(_));
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, session));
conn->StartHeartBeat(session);
testing::Mock::AsyncVerifyAndClearExpectations(2 * kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND);
}
TEST_F(HeartBeatMonitorTest, KeptAlive) {
EXPECT_CALL(connection_handler_mock, CloseSession(_, _)).Times(0);
EXPECT_CALL(connection_handler_mock, CloseConnection(_)).Times(0);
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, _)).Times(0);
const uint32_t session = conn->AddNewSession();
conn->StartHeartBeat(session);
#if defined(OS_WIN32) || defined(OS_WINCE)
Sleep(kTimeout - MILLISECONDS_IN_SECOND);
conn->KeepAlive(session);
Sleep(kTimeout - MILLISECONDS_IN_SECOND);
conn->KeepAlive(session);
Sleep(kTimeout - MILLISECONDS_IN_SECOND);
conn->KeepAlive(session);
Sleep(kTimeout - MILLISECONDS_IN_SECOND);
#else
usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND);
conn->KeepAlive(session);
usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND);
conn->KeepAlive(session);
usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND);
conn->KeepAlive(session);
usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND);
#endif
}
TEST_F(HeartBeatMonitorTest, NotKeptAlive) {
const uint32_t session = conn->AddNewSession();
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, session));
EXPECT_CALL(connection_handler_mock, CloseSession(_, session, _))
.WillOnce(RemoveSession(conn, session));
EXPECT_CALL(connection_handler_mock, CloseConnection(_));
conn->StartHeartBeat(session);
#if defined(OS_WIN32) || defined(OS_WINCE)
Sleep(kTimeout - MILLISECONDS_IN_SECOND);
conn->KeepAlive(session);
Sleep(kTimeout - MILLISECONDS_IN_SECOND);
conn->KeepAlive(session);
Sleep(kTimeout - MILLISECONDS_IN_SECOND);
conn->KeepAlive(session);
Sleep(5 * kTimeout + MILLISECONDS_IN_SECOND);
#else
usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND);
conn->KeepAlive(session);
usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND);
conn->KeepAlive(session);
usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND);
conn->KeepAlive(session);
usleep(2 * kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND);
#endif
}
TEST_F(HeartBeatMonitorTest, TwoSessionsElapsed) {
const uint32_t kSession1 = conn->AddNewSession();
const uint32_t kSession2 = conn->AddNewSession();
EXPECT_CALL(connection_handler_mock, CloseSession(_, kSession1, _))
.WillOnce(RemoveSession(conn, kSession1));
EXPECT_CALL(connection_handler_mock, CloseSession(_, kSession2, _))
.WillOnce(RemoveSession(conn, kSession2));
EXPECT_CALL(connection_handler_mock, CloseConnection(_));
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, kSession1));
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, kSession2));
conn->StartHeartBeat(kSession1);
conn->StartHeartBeat(kSession2);
testing::Mock::AsyncVerifyAndClearExpectations(2 * kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND);
}
TEST_F(HeartBeatMonitorTest, IncreaseHeartBeatTimeout) {
const uint32_t kSession = conn->AddNewSession();
EXPECT_CALL(connection_handler_mock, CloseSession(_, _)).Times(0);
EXPECT_CALL(connection_handler_mock, CloseConnection(_)).Times(0);
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, _)).Times(0);
const uint32_t kNewTimeout = kTimeout + MICROSECONDS_IN_MILLISECONDS;
conn->StartHeartBeat(kSession);
conn->SetHeartBeatTimeout(kNewTimeout, kSession);
// new timeout greater by old timeout so mock object shouldn't be invoked
testing::Mock::AsyncVerifyAndClearExpectations(kTimeout * MICROSECONDS_IN_MILLISECONDS);
}
TEST_F(HeartBeatMonitorTest, DecreaseHeartBeatTimeout) {
const uint32_t kSession = conn->AddNewSession();
EXPECT_CALL(connection_handler_mock, CloseSession(_, kSession, _))
.WillOnce(RemoveSession(conn, kSession));
EXPECT_CALL(connection_handler_mock, CloseConnection(_));
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, kSession));
const uint32_t kNewTimeout = kTimeout - MICROSECONDS_IN_MILLISECONDS;
conn->StartHeartBeat(kSession);
conn->SetHeartBeatTimeout(kNewTimeout, kSession);
// new timeout less than old timeout so mock object should be invoked
testing::Mock::AsyncVerifyAndClearExpectations(kTimeout * 2 * MICROSECONDS_IN_MILLISECONDS);
}
} // namespace connection_handler_test
} // namespace components
} // namespace test
|
antoniovazquezaraujo/LeTrain | src/main/java/letrain/track/ConnectableTrack.java | <filename>src/main/java/letrain/track/ConnectableTrack.java
package letrain.track;
import letrain.map.Dir;
interface ConnectableTrack {
Track getConnectedTrack(Dir dir);
boolean connectTrack(Dir dir, Track t);
Track disconnectTrack(Dir dir);
}
|
wenfeifei/miniblink49 | gen/blink/bindings/modules/v8/V8CanvasPattern.cpp | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "config.h"
#include "V8CanvasPattern.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/V8DOMConfiguration.h"
#include "bindings/core/v8/V8ObjectConstructor.h"
#include "bindings/core/v8/V8SVGMatrix.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"
namespace blink {
// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const WrapperTypeInfo V8CanvasPattern::wrapperTypeInfo = { gin::kEmbedderBlink, V8CanvasPattern::domTemplate, V8CanvasPattern::refObject, V8CanvasPattern::derefObject, V8CanvasPattern::trace, 0, 0, V8CanvasPattern::preparePrototypeObject, V8CanvasPattern::installConditionallyEnabledProperties, "CanvasPattern", 0, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::NotInheritFromEventTarget, WrapperTypeInfo::Independent, WrapperTypeInfo::GarbageCollectedObject };
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic pop
#endif
// This static member must be declared by DEFINE_WRAPPERTYPEINFO in CanvasPattern.h.
// For details, see the comment of DEFINE_WRAPPERTYPEINFO in
// bindings/core/v8/ScriptWrappable.h.
const WrapperTypeInfo& CanvasPattern::s_wrapperTypeInfo = V8CanvasPattern::wrapperTypeInfo;
namespace CanvasPatternV8Internal {
static void setTransformMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 1)) {
V8ThrowException::throwException(createMinimumArityTypeErrorForMethod(info.GetIsolate(), "setTransform", "CanvasPattern", 1, info.Length()), info.GetIsolate());
return;
}
CanvasPattern* impl = V8CanvasPattern::toImpl(info.Holder());
SVGMatrixTearOff* transform;
{
transform = V8SVGMatrix::toImplWithTypeCheck(info.GetIsolate(), info[0]);
}
impl->setTransform(transform);
}
static void setTransformMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
CanvasPatternV8Internal::setTransformMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
} // namespace CanvasPatternV8Internal
static void installV8CanvasPatternTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate)
{
functionTemplate->ReadOnlyPrototype();
v8::Local<v8::Signature> defaultSignature;
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, "CanvasPattern", v8::Local<v8::FunctionTemplate>(), V8CanvasPattern::internalFieldCount,
0, 0,
0, 0,
0, 0);
v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instanceTemplate);
v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototypeTemplate);
if (RuntimeEnabledFeatures::experimentalCanvasFeaturesEnabled()) {
const V8DOMConfiguration::MethodConfiguration setTransformMethodConfiguration = {
"setTransform", CanvasPatternV8Internal::setTransformMethodCallback, 0, 1, V8DOMConfiguration::ExposedToAllScripts,
};
V8DOMConfiguration::installMethod(isolate, prototypeTemplate, defaultSignature, v8::None, setTransformMethodConfiguration);
}
// Custom toString template
functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate());
}
v8::Local<v8::FunctionTemplate> V8CanvasPattern::domTemplate(v8::Isolate* isolate)
{
return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), installV8CanvasPatternTemplate);
}
bool V8CanvasPattern::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}
v8::Local<v8::Object> V8CanvasPattern::findInstanceInPrototypeChain(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}
CanvasPattern* V8CanvasPattern::toImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value)
{
return hasInstance(value, isolate) ? toImpl(v8::Local<v8::Object>::Cast(value)) : 0;
}
void V8CanvasPattern::refObject(ScriptWrappable* scriptWrappable)
{
}
void V8CanvasPattern::derefObject(ScriptWrappable* scriptWrappable)
{
}
} // namespace blink
|
ganlanshugod/wechat-client | wechat-cp-client/src/main/java/org/bana/wechat/cp/message/param/file/FileMessageParam.java | <reponame>ganlanshugod/wechat-client
/**
* @Company 青鸟软通
* @Title: FileMessageParam.java
* @Package org.bana.wechat.qy.message.param.file
* @author <NAME>
* @date 2015-5-27 下午9:27:18
* @version V1.0
*/
package org.bana.wechat.cp.message.param.file;
import org.bana.wechat.cp.common.Constants;
import org.bana.wechat.cp.message.param.MessageParam;
/**
* @ClassName: FileMessageParam
* @Description: file消息
*
*/
public class FileMessageParam extends MessageParam {
private static final long serialVersionUID = 7308130039543425531L;
private FileMessage file;
/**
* <p>Description: </p>
* @author <NAME>
* @date 2015-5-27 下午9:40:33
*/
public FileMessageParam() {
setMsgtype(Constants.file消息.getValue());
}
/**
* @Description: 属性 file 的get方法
* @return file
*/
public FileMessage getFile() {
return file;
}
/**
* @Description: 属性 file 的set方法
* @param file
*/
public void setFile(FileMessage file) {
this.file = file;
}
/**
* <p>Description: </p>
* @author <NAME>
* @date 2015-5-27 下午9:28:31
* @return
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "FileMessageParam [file=" + file + ", touser=" + touser + ", toparty=" + toparty + ", totag=" + totag + ", msgtype=" + msgtype + ", agentid=" + agentid + ", safe="
+ safe + "]";
}
}
|
davideriboli/Nodebox3 | NDBX-App/nodebox-master/src/main/java/nodebox/graphics/Transform.java | package nodebox.graphics;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
public class Transform implements Cloneable {
public enum Mode {
CORNER, CENTER
}
private AffineTransform affineTransform;
public static Transform translated(double tx, double ty) {
Transform t = new Transform();
t.translate(tx, ty);
return t;
}
public static Transform translated(Point t) {
return translated(t.x, t.y);
}
public static Transform rotated(double degrees) {
Transform t = new Transform();
t.rotate(degrees);
return t;
}
public static Transform rotatedRadians(double radians) {
Transform t = new Transform();
t.rotateRadians(radians);
return t;
}
public static Transform scaled(double scale) {
Transform t = new Transform();
t.scale(scale);
return t;
}
public static Transform scaled(double sx, double sy) {
Transform t = new Transform();
t.scale(sx, sy);
return t;
}
public static Transform scaled(Point s) {
return scaled(s.x, s.y);
}
public static Transform skewed(double skew) {
Transform t = new Transform();
t.skew(skew);
return t;
}
public static Transform skewed(double kx, double ky) {
Transform t = new Transform();
t.skew(kx, ky);
return t;
}
public Transform() {
affineTransform = new AffineTransform();
}
public Transform(double m00, double m10, double m01, double m11, double m02, double m12) {
affineTransform = new AffineTransform(m00, m10, m01, m11, m02, m12);
}
public Transform(AffineTransform affineTransform) {
this.affineTransform = affineTransform;
}
public Transform(Transform other) {
this.affineTransform = (AffineTransform) other.affineTransform.clone();
}
//// Transform changes ////
public void translate(Point point) {
affineTransform.translate(point.x, point.y);
}
public void translate(double tx, double ty) {
affineTransform.translate(tx, ty);
}
public void rotate(double degrees) {
double radians = degrees * Math.PI / 180;
affineTransform.rotate(radians);
}
public void rotateRadians(double radians) {
affineTransform.rotate(radians);
}
public void scale(double scale) {
affineTransform.scale(scale, scale);
}
public void scale(double sx, double sy) {
affineTransform.scale(sx, sy);
}
public void skew(double skew) {
skew(skew, skew);
}
public void skew(double kx, double ky) {
kx = Math.PI * kx / 180.0;
ky = Math.PI * ky / 180.0;
affineTransform.concatenate(new AffineTransform(1, Math.tan(ky), -Math.tan(kx), 1, 0, 0));
}
public boolean invert() {
try {
affineTransform = affineTransform.createInverse();
return true;
} catch (NoninvertibleTransformException e) {
return false;
}
}
public void append(Transform t) {
affineTransform.concatenate(t.affineTransform);
}
public void prepend(Transform t) {
affineTransform.preConcatenate(t.affineTransform);
}
//// Operations ////
public Point map(Point p) {
Point2D.Double p2 = new Point2D.Double();
affineTransform.transform(p.toPoint2D(), p2);
return new Point(p2);
}
public Rect map(Rect r) {
// TODO: The size conversion might be incorrect. (using deltaTransform) In that case, make topLeft and bottomRight points.
Point2D origin = new Point2D.Double(r.getX(), r.getY());
Point2D size = new Point2D.Double(r.getWidth(), r.getHeight());
Point2D transformedOrigin = new Point2D.Double();
Point2D transformedSize = new Point2D.Double();
affineTransform.transform(origin, transformedOrigin);
affineTransform.deltaTransform(size, transformedSize);
return new Rect(transformedOrigin.getX(), transformedOrigin.getY(), transformedSize.getX(), transformedSize.getY());
}
public IGeometry map(IGeometry shape) {
if (shape instanceof Path) {
return map((Path) shape);
} else if (shape instanceof Geometry) {
return map((Geometry) shape);
} else {
throw new RuntimeException("Unsupported geometry type " + shape);
}
}
public Path map(Path p) {
Path newPath = new Path(p, false);
for (Contour c : p.getContours()) {
Contour newContour = new Contour(map(c.getPoints()), c.isClosed());
newPath.add(newContour);
}
return newPath;
}
public Geometry map(Geometry g) {
Geometry newGeometry = new Geometry();
for (Path p : g.getPaths()) {
Path newPath = map(p);
newGeometry.add(newPath);
}
return newGeometry;
}
/**
* Transform all the given points and return a list of transformed points.
* Points are immutable, so they can not be transformed in-place.
*
* @param points The points to transform.
* @return The list of transformed points.
*/
public List<Point> map(List<Point> points) {
// Prepare the points for the AffineTransform transformation.
double[] coords = new double[points.size() * 2];
int i = 0;
for (Point pt : points) {
coords[i++] = pt.x;
coords[i++] = pt.y;
}
affineTransform.transform(coords, 0, coords, 0, points.size());
// Convert the transformed points into a new List.
List<Point> transformed = new ArrayList<Point>(points.size());
int pointIndex = 0;
for (i = 0; i < coords.length; i += 2) {
transformed.add(new Point(coords[i], coords[i + 1], points.get(pointIndex).type));
pointIndex++;
}
return transformed;
}
public Rect convertBoundsToFrame(Rect bounds) {
AffineTransform t = fullTransform(bounds);
Point2D transformedOrigin = new Point2D.Double();
Point2D transformedSize = new Point2D.Double();
t.transform(new Point2D.Double(bounds.getX(), bounds.getY()), transformedOrigin);
t.deltaTransform(new Point2D.Double(bounds.getWidth(), bounds.getHeight()), transformedSize);
return new Rect(transformedOrigin.getX(), transformedOrigin.getY(), transformedSize.getX(), transformedSize.getY());
}
private AffineTransform fullTransform(Rect bounds) {
double cx = bounds.getX() + bounds.getWidth() / 2;
double cy = bounds.getY() + bounds.getHeight() / 2;
AffineTransform t = new AffineTransform();
t.translate(cx, cy);
t.preConcatenate(affineTransform);
t.translate(-cx, -cy);
return t;
}
@Override
protected Transform clone() {
return new Transform(this);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Transform)) return false;
return getAffineTransform().equals(((Transform) obj).getAffineTransform());
}
public void apply(Graphics2D g, Rect bounds) {
AffineTransform t = fullTransform(bounds);
g.transform(t);
}
public AffineTransform getAffineTransform() {
return affineTransform;
}
}
|
tariqporter/blocks-ds-netlify | src/code_examples/TextAreaExample.js | import React from "react"
const { TextArea } = require('blocks-react').Input;
class TextAreaExample extends React.Component {
constructor(props) {
super(props);
this.state = {
value: "On the eighty-fifth day of his unlucky streak, Santiago takes his skiff into the Gulf Stream, sets his lines and, by noon, has his bait taken by a big fish that he is sure is a marlin."
};
}
onChange(e) {
this.setState({ value: e.target.value });
}
render() {
return (
<TextArea
value={this.state.value}
onChange={e => this.onChange(e)}
/>
);
}
}
export default TextAreaExample;
|
asanoviskhak/Outtalent | Leetcode/385. Mini Parser/solution1.py | # """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
# class NestedInteger:
# def __init__(self, value=None):
# """
# If value is not specified, initializes an empty list.
# Otherwise initializes a single integer equal to value.
# """
#
# def isInteger(self):
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# :rtype bool
# """
#
# def add(self, elem):
# """
# Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
# :rtype void
# """
#
# def setInteger(self, value):
# """
# Set this NestedInteger to hold a single integer equal to value.
# :rtype void
# """
#
# def getInteger(self):
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# :rtype int
# """
#
# def getList(self):
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# :rtype List[NestedInteger]
# """
class Solution:
def deserialize(self, s: str) -> NestedInteger:
if not s: return NestedInteger()
if s[0] != '[':
result = NestedInteger()
result.setInteger(int(s))
return result
if s[0] == '[':
result = NestedInteger()
current = ''
braket = 0
for c in s[1:-1]:
if c == '[':
braket += 1
elif c == ']':
braket -= 1
if braket == 0 and c == ',':
if current: result.add(self.deserialize(current))
current = ''
else:
current += c
if current: result.add(self.deserialize(current))
return result
|
ouxianghui/mediasoup-client | RoomClient/service/i_signaling_observer.h | #pragma once
#include <memory>
#include "signaling_models.h"
namespace vi {
class ISignalingObserver {
public:
virtual ~ISignalingObserver() = default;
virtual void onOpened() = 0;
virtual void onClosed() = 0;
// Request from SFU
virtual void onNewConsumer(std::shared_ptr<signaling::NewConsumerRequest> request) = 0;
virtual void onNewDataConsumer(std::shared_ptr<signaling::NewDataConsumerRequest> request) = 0;
// Notification from SFU
virtual void onProducerScore(std::shared_ptr<signaling::ProducerScoreNotification> notification) = 0;
virtual void onConsumerScore(std::shared_ptr<signaling::ConsumerScoreNotification> notification) = 0;
virtual void onNewPeer(std::shared_ptr<signaling::NewPeerNotification> notification) = 0;
virtual void onPeerClosed(std::shared_ptr<signaling::PeerClosedNotification> notification) = 0;
virtual void onPeerDisplayNameChanged(std::shared_ptr<signaling::PeerDisplayNameChangedNotification> notification) = 0;
virtual void onConsumerPaused(std::shared_ptr<signaling::ConsumerPausedNotification> notification) = 0;
virtual void onConsumerResumed(std::shared_ptr<signaling::ConsumerResumedNotification> notification) = 0;
virtual void onConsumerClosed(std::shared_ptr<signaling::ConsumerClosedNotification> notification) = 0;
virtual void onConsumerLayersChanged(std::shared_ptr<signaling::ConsumerLayersChangedNotification> notification) = 0;
virtual void onDataConsumerClosed(std::shared_ptr<signaling::DataConsumerClosedNotification> notification) = 0;
virtual void onDownlinkBwe(std::shared_ptr<signaling::DownlinkBweNotification> notification) = 0;
virtual void onActiveSpeaker(std::shared_ptr<signaling::ActiveSpeakerNotification> notification) = 0;
};
}
|
hqbao/dlp_tf | face_detection_xsml/rename.py | import tensorflow as tf
import numpy as np
from models import build_model, nsm
from datagen import genanchors, comiou, load_dataset, genxy, genxy_com
output_path = 'output/xsmall'
ishape = [512, 512, 3] # [64, 64, 3], [128, 128, 3], [256, 256, 3], [512, 512, 3]
asizes = [[32, 32]]
total_classes = 1
resnet_settings = [[8, 8, 32], [24, [2, 2]]]
model = build_model(
ishape=ishape,
resnet_settings=resnet_settings,
k=len(asizes),
total_classes=total_classes,
net_name='XNet')
# model.summary()
model.load_weights('{}/weights_best_precision.h5'.format(output_path))
model.save_weights('{}/weights_.h5'.format(output_path))
|
kelvin-olaiya/OOP20-iUniversity | src/main/java/iuniversity/controller/exams/ExamBookingControllerImpl.java | package iuniversity.controller.exams;
import java.util.stream.Collectors;
import iuniversity.controller.AbstractController;
import iuniversity.model.didactics.Course;
import iuniversity.model.exams.ExamCall;
import iuniversity.model.exams.ExamResult.ExamResultType;
import iuniversity.model.user.Student;
import iuniversity.view.exams.ExamBookingView;
/**
* Manages the booking of an exam call.
*/
public class ExamBookingControllerImpl extends AbstractController implements ExamBookingController {
private static final String BOOKING_ERROR_MESSAGE = "Impossibile iscriversi all'appello d'esame";
private boolean alreadySucceded(final Student student, final Course course) {
return this.getModel().getExamManager().getExamReports().stream()
.filter(r -> r.getResult().getResultType() == ExamResultType.SUCCEDED)
.filter(r -> r.getCourse().equals(course)).anyMatch(r -> r.getStudent().equals(student));
}
private boolean isFollowedByStudent(final Course course, final Student student) {
return student.getDegreeProgramme().getCourses().contains(course);
}
private boolean alreadyRegistered(final ExamCall examCall, final Student student) {
return examCall.getRegisteredStudents().contains(student);
}
/**
* {@inheritDoc}
*/
@Override
public void displayAvailableExamCalls() {
checkStudent();
((ExamBookingView) this.getView()).setAvailableExamCalls(this.getModel().getExamManager().getExamCalls()
.stream().filter(e -> !alreadyRegistered(e, getLoggedStudent()))
.filter(e -> e.isOpen())
.filter(e -> isFollowedByStudent(e.getCourse(), getLoggedStudent()))
.filter(e -> !alreadySucceded(getLoggedStudent(), e.getCourse())).collect(Collectors.toSet()));
}
/**
* {@inheritDoc}
*/
@Override
public void bookExamCall(final ExamCall examCall) {
checkStudent();
if (!this.getModel().getExamManager().registerStudent(examCall, getLoggedStudent())) {
this.getView().showErrorMessage(BOOKING_ERROR_MESSAGE);
} else {
this.saveExamCalls();
}
}
}
|
josecoelho/amugefi | spec/routing/conta_routing_spec.rb | <reponame>josecoelho/amugefi<gh_stars>0
require "rails_helper"
RSpec.describe ContaController, type: :routing do
describe "routing" do
it "routes to #index" do
expect(:get => "/conta").to route_to("conta#index")
end
it "routes to #new" do
expect(:get => "/conta/new").to route_to("conta#new")
end
it "routes to #show" do
expect(:get => "/conta/1").to route_to("conta#show", :id => "1")
end
it "routes to #edit" do
expect(:get => "/conta/1/edit").to route_to("conta#edit", :id => "1")
end
it "routes to #create" do
expect(:post => "/conta").to route_to("conta#create")
end
it "routes to #update via PUT" do
expect(:put => "/conta/1").to route_to("conta#update", :id => "1")
end
it "routes to #update via PATCH" do
expect(:patch => "/conta/1").to route_to("conta#update", :id => "1")
end
it "routes to #destroy" do
expect(:delete => "/conta/1").to route_to("conta#destroy", :id => "1")
end
end
end
|
shaojiankui/iOS10-Runtime-Headers | Frameworks/PhotosUI.framework/PUPhotoEditLayoutSupport.h | /* Generated by RuntimeBrowser
Image: /System/Library/Frameworks/PhotosUI.framework/PhotosUI
*/
@interface PUPhotoEditLayoutSupport : NSObject
+ (id)layoutConstraintsForHidingSecondaryView:(id)arg1 layoutOrientation:(long long)arg2;
+ (id)layoutConstraintsForHidingView:(id)arg1 layoutOrientation:(long long)arg2;
+ (void)transitionFromBarView:(id)arg1 orientation:(long long)arg2 toBarView:(id)arg3 orientation:(long long)arg4 coordinator:(id)arg5 completionHandler:(id /* block */)arg6;
@end
|
MewX/contendo-viewer-v1.6.3 | net/zamasoft/reader/book/a/e.java | package net.zamasoft.reader.book.a;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import net.zamasoft.reader.book.m;
public class e {
public static final int a = 3;
public String b;
public String c;
public long d;
public int e = 1;
public m.a[] f;
public m.a[] g;
public int h;
public boolean a(File paramFile) throws IOException {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(paramFile));
try {
if (objectInputStream.readInt() == 3) {
this.h = objectInputStream.readInt();
this.e = objectInputStream.readInt();
this.b = objectInputStream.readUTF();
this.c = objectInputStream.readUTF();
this.d = objectInputStream.readLong();
try {
this.f = (m.a[])objectInputStream.readObject();
this.g = (m.a[])objectInputStream.readObject();
} catch (ClassNotFoundException classNotFoundException) {}
boolean bool = true;
objectInputStream.close();
return bool;
}
objectInputStream.close();
} catch (Throwable throwable) {
try {
objectInputStream.close();
} catch (Throwable throwable1) {
throwable.addSuppressed(throwable1);
}
throw throwable;
}
return false;
}
public void b(File paramFile) throws IOException {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(paramFile));
try {
objectOutputStream.writeInt(3);
objectOutputStream.writeInt(this.h);
objectOutputStream.writeInt(this.e);
objectOutputStream.writeUTF(this.b);
objectOutputStream.writeUTF(this.c);
objectOutputStream.writeLong(this.d);
objectOutputStream.writeObject(this.f);
objectOutputStream.writeObject(this.g);
objectOutputStream.close();
} catch (Throwable throwable) {
try {
objectOutputStream.close();
} catch (Throwable throwable1) {
throwable.addSuppressed(throwable1);
}
throw throwable;
}
}
}
/* Location: /mnt/r/ConTenDoViewer.jar!/net/zamasoft/reader/book/a/e.class
* Java compiler version: 11 (55.0)
* JD-Core Version: 1.1.3
*/ |
MAhsan-Raza/AlgorithmsPractice | LeetCode./Trees./MaximumDepthofBinaryTree.cpp | <reponame>MAhsan-Raza/AlgorithmsPractice
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
protected:
void maxDepth(TreeNode* crnt, int& crntDpt, int& maxDpt)
{
if(!crnt) return;
++crntDpt;
maxDepth(crnt->left, crntDpt, maxDpt);
maxDepth(crnt->right, crntDpt, maxDpt);
--crntDpt;
maxDpt = std::max(crntDpt, maxDpt);
}
public:
int maxDepth(TreeNode* root)
{
int cd = 1;
int md = 0;
maxDepth(root, cd, md);
return md;
}
};
|
opuseirios/incake-wechat-2017 | src/assets/js/convertibility-way.js | <filename>src/assets/js/convertibility-way.js<gh_stars>1-10
(function($, window, document){
$(".close").click(function(){
$(".hint").fadeOut();
});
})(jQuery, window, document);
|
zipated/src | third_party/android_tools/sdk/sources/android-25/com/android/systemui/tv/pip/PipMenuActivity.java | <gh_stars>1000+
/*
* Copyright (C) 2016 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.
*/
package com.android.systemui.tv.pip;
import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import com.android.systemui.R;
import com.android.systemui.Interpolators;
/**
* Activity to show the PIP menu to control PIP.
*/
public class PipMenuActivity extends Activity implements PipManager.Listener {
private static final String TAG = "PipMenuActivity";
private final PipManager mPipManager = PipManager.getInstance();
private Animator mFadeInAnimation;
private Animator mFadeOutAnimation;
private View mPipControlsView;
private boolean mRestorePipSizeWhenClose;
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.tv_pip_menu);
mPipManager.addListener(this);
mRestorePipSizeWhenClose = true;
mPipControlsView = (PipControlsView) findViewById(R.id.pip_controls);
mFadeInAnimation = AnimatorInflater.loadAnimator(
this, R.anim.tv_pip_menu_fade_in_animation);
mFadeInAnimation.setTarget(mPipControlsView);
mFadeOutAnimation = AnimatorInflater.loadAnimator(
this, R.anim.tv_pip_menu_fade_out_animation);
mFadeOutAnimation.setTarget(mPipControlsView);
}
private void restorePipAndFinish() {
if (mRestorePipSizeWhenClose) {
// When PIP menu activity is closed, restore to the default position.
mPipManager.resizePinnedStack(PipManager.STATE_PIP_OVERLAY);
}
finish();
}
@Override
public void onResume() {
super.onResume();
mFadeInAnimation.start();
}
@Override
public void onPause() {
super.onPause();
mFadeOutAnimation.start();
restorePipAndFinish();
}
@Override
protected void onDestroy() {
super.onDestroy();
mPipManager.removeListener(this);
mPipManager.resumePipResizing(
PipManager.SUSPEND_PIP_RESIZE_REASON_WAITING_FOR_MENU_ACTIVITY_FINISH);
}
@Override
public void onBackPressed() {
restorePipAndFinish();
}
@Override
public void onPipEntered() { }
@Override
public void onPipActivityClosed() {
finish();
}
@Override
public void onShowPipMenu() { }
@Override
public void onMoveToFullscreen() {
// Moving PIP to fullscreen is implemented by resizing PINNED_STACK with null bounds.
// This conflicts with restoring PIP position, so disable it.
mRestorePipSizeWhenClose = false;
finish();
}
@Override
public void onPipResizeAboutToStart() {
finish();
mPipManager.suspendPipResizing(
PipManager.SUSPEND_PIP_RESIZE_REASON_WAITING_FOR_MENU_ACTIVITY_FINISH);
}
}
|
sigurasg/ghidra | Ghidra/Features/PDB/src/main/java/ghidra/app/util/bin/format/pdb/ApplyTables.java | <gh_stars>10-100
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.util.bin.format.pdb;
import ghidra.app.util.importer.MessageLog;
import ghidra.util.exception.CancelledException;
import ghidra.util.task.TaskMonitor;
import ghidra.xml.XmlElement;
import ghidra.xml.XmlPullParser;
class ApplyTables {
private ApplyTables() {
// static use only
}
static void applyTo(PdbParser pdbParser, XmlPullParser xmlParser, TaskMonitor monitor,
MessageLog log) throws CancelledException {
while (xmlParser.hasNext()) {
if (monitor.isCancelled()) {
return;
}
XmlElement elem = xmlParser.next();
if (elem.isEnd() && elem.getName().equals("tables")) {
break;
}
String tableName = elem.getAttribute("name");
if ("Symbols".equals(tableName)) {
ApplySymbols.applyTo(pdbParser, xmlParser, monitor, log);
}
else if ("SourceFiles".equals(tableName)) {
ApplySourceFiles.applyTo(pdbParser, xmlParser, monitor, log);
}
else if ("Sections".equals(tableName)) {//TODO
}
}
}
}
|
1and1-webhosting-infrastructure/TypedRest-Java | core/src/main/java/net/typedrest/PagedCollectionEndpoint.java | package net.typedrest;
/**
* REST endpoint that represents a collection of <code>TEntity</code>s as
* {@link ElementEndpoint}s with pagination support.
*
* @param <TEntity> The type of entity the endpoint represents.
*
* @deprecated Use {@link CollectionEndpoint} instead.
*/
@Deprecated
public interface PagedCollectionEndpoint<TEntity>
extends GenericPagedCollectionEndpoint<TEntity, ElementEndpoint<TEntity>>, CollectionEndpoint<TEntity> {
}
|
antonmedv/year | packages/1986/06/23/index.js | module.exports = new Date(1986, 5, 23)
|
pageinsec/security_content | bin/automated_detection_testing/ci/labeled_data/modules/github_service.py |
import git
import os
import logging
import glob
import subprocess
# Logger
logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))
LOGGER = logging.getLogger(__name__)
SECURITY_CONTENT_URL = "https://github.com/splunk/security_content"
class GithubService:
def __init__(self, security_content_branch):
self.security_content_branch = security_content_branch
self.security_content_repo_obj = self.clone_project(SECURITY_CONTENT_URL, f"security_content", f"develop")
self.security_content_repo_obj.git.checkout(security_content_branch)
def clone_project(self, url, project, branch):
LOGGER.info(f"Clone Security Content Project")
repo_obj = git.Repo.clone_from(url, project, branch=branch)
return repo_obj
def get_test_files(self):
path = 'security_content/tests/endpoint'
test_files = []
for root, directories, files in os.walk(path, topdown=False):
for name in files:
file_path = os.path.join(root, name)
if not os.path.basename(file_path).startswith('ssa') and os.path.basename(file_path).endswith('.yml'):
test_files.append(file_path)
# for testing
#test_files = ['security_content/tests/endpoint/certutil_exe_certificate_extraction.test.yml']
test_files.remove('security_content/tests/endpoint/winword_spawning_windows_script_host.test.yml')
test_files.remove('security_content/tests/endpoint/winword_spawning_powershell.test.yml')
test_files.remove('security_content/tests/endpoint/winword_spawning_cmd.test.yml')
# test_files.remove('security_content/tests/endpoint/bitsadmin_download_file.test.yml')
# test_files.remove('security_content/tests/endpoint/bcdedit_failure_recovery_modification.test.yml')
return sorted(test_files, reverse=True)[61:]
# def get_changed_test_files(self):
# branch1 = self.security_content_branch
# branch2 = 'develop'
# g = git.Git('security_content')
# changed_test_files = []
# if branch1 != 'develop':
# differ = g.diff('--name-status', branch2 + '...' + branch1)
# changed_files = differ.splitlines()
# for file_path in changed_files:
# # added or changed test files
# if file_path.startswith('A') or file_path.startswith('M'):
# if 'tests' in file_path:
# if not os.path.basename(file_path).startswith('ssa') and os.path.basename(file_path).endswith('.test.yml'):
# if file_path not in changed_test_files:
# changed_test_files.append(file_path)
# # changed detections
# if 'detections' in file_path:
# if not os.path.basename(file_path).startswith('ssa') and os.path.basename(file_path).endswith('.yml'):
# file_path_base = os.path.splitext(file_path)[0].replace('detections', 'tests') + '.test'
# file_path_new = file_path_base + '.yml'
# if file_path_new not in changed_test_files:
# changed_test_files.append(file_path_new)
# return changed_test_files
|
AYCHSave/MoneyManage | auth-service/src/main/java/com/money/management/auth/repository/UserRepository.java | <gh_stars>1-10
package com.money.management.auth.repository;
import com.money.management.auth.domain.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface UserRepository extends CrudRepository<User, String> {
Optional<User> findUsersByUsername(String username);
}
|
cacheflowe/haxademic | src/com/haxademic/core/text/FitTextSourceBuffer.java | package com.haxademic.core.text;
import com.haxademic.core.app.P;
import processing.core.PFont;
import processing.core.PGraphics;
public class FitTextSourceBuffer {
protected PFont font;
protected int color;
protected PGraphics buffer;
// This is the large offscreen canvas we draw text into.
// This text is then cropped and turned into a tiling texture
public FitTextSourceBuffer(PFont font, int color) {
this.font = font;
this.color = color;
buffer = P.p.createGraphics(4096, P.ceil(font.getSize() * 1.1f));
buffer.smooth(8);
}
public PGraphics buffer() {
return buffer;
}
public void updateText(String text) {
// draw
buffer.beginDraw();
buffer.clear();
buffer.background(0, 0);
buffer.noStroke();
buffer.background(0, 0);
buffer.fill(color);
buffer.textAlign(P.CENTER, P.CENTER);
buffer.textFont(font);
// buffer.textLeading(font.getSize() * 0.75f);
buffer.text(text, 0, 0, buffer.width, buffer.height);
buffer.endDraw();
}
} |
JosueGauthier/Surface-de-Bezier-Python | cast2.py | """
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% function [XPP,YPP]=cast2(t,XP,YP)
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% Enveloppe convexe d'une courbe de Bézier
%% Construction des points de contrôle
%% Deuxième partie t dans [0.5,1.]
%%
%% Données : t valeur du paramètre
%% XP, YP coordonnées des points de contrôle
%%
%% Résultats : XPP,YPP coordonnées des points de contrôle
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%% Introduction au calcul scientifique par la pratique %%%%%%%
%%%%%%% <NAME>, <NAME>, <NAME> et <NAME> %%%%%%%
%%%%%%% Dunod, 2005 %%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
"""
import numpy as np
def cast2(t,XP,YP):
m = (np.shape(XP)[0]) - 1
xx = np.zeros(m)
yy = np.zeros(m)
for k in range(0,m):
xx[m-1-k] = XP[k]
yy[m-1-k] = YP[k]
XPP = np.zeros(m)
YPP = np.zeros(m)
for kk in range(0,m):
xxx = xx.copy()
yyy = yy.copy()
XPP[m-1-kk] = xx[kk]
YPP[m-1-kk] = yy[kk]
for k in range(kk,m):
xx[k]=t*xxx[k]+(1-t)*xxx[k]
yy[k]=t*yyy[k]+(1-t)*yyy[k]
XPP[0]=xx[m-1]
YPP[0]=yy[m-1]
return (XPP,YPP) |
schechenkin/Hazel_RoboCatGame | RoboCat/Src/NetworkManager.cpp | #include <RoboCatPCH.h>
NetworkManager::NetworkManager() :
mBytesSentThisFrame( 0 ),
mDropPacketChance( 0.f ),
mSimulatedLatency( 0.f )
{
}
NetworkManager::~NetworkManager()
{
}
bool NetworkManager::Init( uint16_t inPort )
{
mSocket = SocketUtil::CreateUDPSocket( INET );
SocketAddress ownAddress( INADDR_ANY, inPort );
mSocket->Bind( ownAddress );
HZ_CORE_INFO("Initializing NetworkManager at port {0}", inPort);
mBytesReceivedPerSecond = WeightedTimedMovingAverage( 1.f );
mBytesSentPerSecond = WeightedTimedMovingAverage( 1.f );
//did we bind okay?
if( mSocket == nullptr )
{
return false;
}
if( mSocket->SetNonBlockingMode( true ) != NO_ERROR )
{
return false;
}
return true;
}
void NetworkManager::ProcessIncomingPackets()
{
ReadIncomingPacketsIntoQueue();
ProcessQueuedPackets();
UpdateBytesSentLastFrame();
}
void NetworkManager::ReadIncomingPacketsIntoQueue()
{
//should we just keep a static one?
char packetMem[ 1500 ];
int packetSize = sizeof( packetMem );
InputMemoryBitStream inputStream( packetMem, packetSize * 8 );
SocketAddress fromAddress;
//keep reading until we don't have anything to read ( or we hit a max number that we'll process per frame )
int receivedPackedCount = 0;
int totalReadByteCount = 0;
while( receivedPackedCount < kMaxPacketsPerFrameCount )
{
int readByteCount = mSocket->ReceiveFrom( packetMem, packetSize, fromAddress );
if( readByteCount == 0 )
{
//nothing to read
break;
}
else if( readByteCount == -WSAECONNRESET )
{
//port closed on other end, so DC this person immediately
HandleConnectionReset( fromAddress );
}
else if( readByteCount > 0 )
{
inputStream.ResetToCapacity( readByteCount );
++receivedPackedCount;
totalReadByteCount += readByteCount;
//now, should we drop the packet?
if( RoboMath::GetRandomFloat() >= mDropPacketChance )
{
//we made it
//shove the packet into the queue and we'll handle it as soon as we should...
//we'll pretend it wasn't received until simulated latency from now
//this doesn't sim jitter, for that we would need to.....
float simulatedReceivedTime = Timing::sInstance.GetTimef() + mSimulatedLatency;
mPacketQueue.emplace( simulatedReceivedTime, inputStream, fromAddress );
}
else
{
HZ_CORE_WARN("Dropped packet!");
//dropped!
}
}
else
{
HZ_CORE_ERROR("uhoh, error? exit or just keep going?");
}
}
if( totalReadByteCount > 0 )
{
mBytesReceivedPerSecond.UpdatePerSecond( static_cast< float >( totalReadByteCount ) );
}
}
void NetworkManager::ProcessQueuedPackets()
{
//look at the front packet...
while( !mPacketQueue.empty() )
{
ReceivedPacket& nextPacket = mPacketQueue.front();
if( Timing::sInstance.GetTimef() > nextPacket.GetReceivedTime() )
{
ProcessPacket( nextPacket.GetPacketBuffer(), nextPacket.GetFromAddress() );
mPacketQueue.pop();
}
else
{
break;
}
}
}
void NetworkManager::SendPacket( const OutputMemoryBitStream& inOutputStream, const SocketAddress& inFromAddress )
{
int sentByteCount = mSocket->SendTo( inOutputStream.GetBufferPtr(), inOutputStream.GetByteLength(), inFromAddress );
if( sentByteCount > 0 )
{
mBytesSentThisFrame += sentByteCount;
}
}
void NetworkManager::UpdateBytesSentLastFrame()
{
if( mBytesSentThisFrame > 0 )
{
mBytesSentPerSecond.UpdatePerSecond( static_cast< float >( mBytesSentThisFrame ) );
mBytesSentThisFrame = 0;
}
}
NetworkManager::ReceivedPacket::ReceivedPacket( float inReceivedTime, InputMemoryBitStream& ioInputMemoryBitStream, const SocketAddress& inFromAddress ) :
mReceivedTime( inReceivedTime ),
mFromAddress( inFromAddress ),
mPacketBuffer( ioInputMemoryBitStream )
{
}
void NetworkManager::AddToNetworkIdToGameObjectMap( GameObjectPtr inGameObject )
{
HZ_CORE_TRACE("NetworkManager::AddToNetworkIdToGameObjectMap");
mNetworkIdToGameObjectMap[ inGameObject->GetNetworkId() ] = inGameObject;
}
void NetworkManager::RemoveFromNetworkIdToGameObjectMap( GameObjectPtr inGameObject )
{
HZ_CORE_TRACE("NetworkManager::RemoveFromNetworkIdToGameObjectMap");
mNetworkIdToGameObjectMap.erase( inGameObject->GetNetworkId() );
} |
damirs11/extern-java-sdk | extern-api-java-sdk-common/src/main/java/ru/kontur/extern_api/sdk/model/UsnDataV2.java | <gh_stars>1-10
/*
* MIT License
*
* Copyright (c) 2018 SKB Kontur
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package ru.kontur.extern_api.sdk.model;
import com.google.gson.annotations.SerializedName;
/**
* <p>
* Класс предназначен для формирования разделов УСН декларации
* </p>
* @author <NAME>
*/
public class UsnDataV2 implements UsnData {
private Integer nomKorr = null;
private Integer poMestu = null;
private Integer prizNp = null;
private String ubytPred = null;
private String ischislMin = null;
private PeriodIndicators zaKv = null;
private PeriodIndicators zaPg = null;
private PeriodIndicators za9m = null;
private TaxPeriodIndicators zaNalPer = null;
/**
* <p>Возвращает значение поля "НомКорр" - номер корректировки</p>
* @return значение поля "НомКорр" - номер корректировки
*/
public Integer getNomKorr() {
return nomKorr;
}
/**
* <p>Устанавливает значение поля "НомКорр" - номер корректировки</p>
* @param nomKorr значение поля "НомКорр" - номер корректировки
*/
public void setNomKorr(Integer nomKorr) {
this.nomKorr = nomKorr;
}
/**
* <p>Возвращает значение поля "ПоМесту" - код места, по которому представляется документ(120,210,215)</p>
* @return значение поля "ПоМесту" - код места, по которому представляется документ(120,210,215)
*/
public Integer getPoMestu() {
return poMestu;
}
/**
* <p>Устанавливает значение поля "ПоМесту" - код места, по которому представляется документ(120,210,215)</p>
* @param poMestu значение поля "ПоМесту" - код места, по которому представляется документ(120,210,215)
*/
public void setPoMestu(Integer poMestu) {
this.poMestu = poMestu;
}
/**
* <p>Возвращает значение поля "ПризНП" - признак налогоплательщика (1,2)</p>
* @return значение поля "ПризНП" - признак налогоплательщика (1,2)
*/
public Integer getPrizNp() {
return prizNp;
}
/**
* <p>Устанавливает значение поля "ПризНП" - признак налогоплательщика (1,2)</p>
* @param prizNp значение поля "ПризНП" - признак налогоплательщика (1,2)
*/
public void setPrizNp(Integer prizNp) {
this.prizNp = prizNp;
}
/**
* <p>Возвращает значение поля "УбытПред" - сумма убытка</p>
* @return значение поля "УбытПред" - сумма убытка
*/
public String getUbytPred() {
return ubytPred;
}
/**
* <p>Устанавливает значение поля "УбытПред" - сумма убытка</p>
* @param ubytPred значение поля "УбытПред" - сумма убытка
*/
public void setUbytPred(String ubytPred) {
this.ubytPred = ubytPred;
}
/**
* <p>Возвращает значение поля "ИсчислМин" - сумма исчисленного минимального налога за налоговый период</p>
* @return значение поля "ИсчислМин" - сумма исчисленного минимального налога за налоговый период
*/
public String getIschislMin() {
return ischislMin;
}
/**
* <p>Устанавливает значение поля "ИсчислМин" - сумма исчисленного минимального налога за налоговый период</p>
* @param ischislMin значение поля "ИсчислМин" - сумма исчисленного минимального налога за налоговый период
*/
public void setIschislMin(String ischislMin) {
this.ischislMin = ischislMin;
}
/**
* <p>Возвращает значение поля "ЗаКв" - показатели за первый квартал, могут отсутствовать</p>
* @return значение поля "ЗаКв" - показатели за первый квартал, могут отсутствовать
*/
public PeriodIndicators getZaKv() {
return zaKv;
}
/**
* <p>Устанавливает значение поля "ЗаКв" - показатели за первый квартал, могут отсутствовать</p>
* @param zaKv значение поля "ЗаКв" - показатели за первый квартал, могут отсутствовать
*/
public void setZaKv(PeriodIndicators zaKv) {
this.zaKv = zaKv;
}
/**
* <p>Возвращает значение поля "ЗаПг" - показатели за полугодие, могут отсутствовать</p>
* @return значение поля "ЗаПг" - показатели за полугодие, могут отсутствовать
*/
public PeriodIndicators getZaPg() {
return zaPg;
}
/**
* <p>Устанавливает значение поля "ЗаПг" - показатели за полугодие, могут отсутствовать</p>
* @param zaPg значение поля "ЗаПг" - показатели за полугодие, могут отсутствовать
*/
public void setZaPg(PeriodIndicators zaPg) {
this.zaPg = zaPg;
}
/**
* <p>Возвращает значение поля "За9м" - показатели за девять месяцев, могут отсутствовать</p>
* @return значение поля "За9м" - показатели за девять месяцев, могут отсутствовать
*/
public PeriodIndicators getZa9m() {
return za9m;
}
/**
* <p>Устанавливает значение поля "За9м" - показатели за девять месяцев, могут отсутствовать</p>
* @param za9m значение поля "За9м" - показатели за девять месяцев, могут отсутствовать
*/
public void setZa9m(PeriodIndicators za9m) {
this.za9m = za9m;
}
/**
* <p>Возвращает значение поля "ЗаНалПер" - показатели за налоговый период</p>
* @return значение поля "ЗаНалПер" - показатели за налоговый период
*/
public TaxPeriodIndicators getZaNalPer() {
return zaNalPer;
}
/**
* <p>Устанавливает значение поля "ЗаНалПер" - показатели за налоговый период</p>
* @param zaNalPer значение поля "ЗаНалПер" - показатели за налоговый период
*/
public void setZaNalPer(TaxPeriodIndicators zaNalPer) {
this.zaNalPer = zaNalPer;
}
}
|
DeadZoneLuna/csso-src | src/materialsystem/stdshaders/aftershock_helper.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
#include "BaseVSShader.h"
#include "mathlib/vmatrix.h"
#include "aftershock_helper.h"
#include "convar.h"
// Auto generated inc files
#include "aftershock_vs20.inc"
#include "aftershock_ps20.inc"
#include "aftershock_ps20b.inc"
void InitParamsAftershock( CBaseVSShader *pShader, IMaterialVar** params, const char *pMaterialName, AftershockVars_t &info )
{
// Set material flags
SET_FLAGS2( MATERIAL_VAR2_SUPPORTS_HW_SKINNING );
SET_FLAGS2( MATERIAL_VAR2_NEEDS_TANGENT_SPACES );
SET_FLAGS( MATERIAL_VAR_TRANSLUCENT );
SET_FLAGS2( MATERIAL_VAR2_NEEDS_POWER_OF_TWO_FRAME_BUFFER_TEXTURE );
// Set material parameter default values
if ( ( info.m_nRefractAmount != -1 ) && ( !params[info.m_nRefractAmount]->IsDefined() ) )
{
params[info.m_nRefractAmount]->SetFloatValue( kDefaultRefractAmount );
}
if ( ( info.m_nColorTint != -1 ) && ( !params[info.m_nColorTint]->IsDefined() ) )
{
params[info.m_nColorTint]->SetVecValue( kDefaultColorTint[0], kDefaultColorTint[1], kDefaultColorTint[2], kDefaultColorTint[3] );
}
if( (info.m_nBumpFrame != -1 ) && !params[info.m_nBumpFrame]->IsDefined() )
{
params[info.m_nBumpFrame]->SetIntValue( 0 );
}
if ( ( info.m_nSilhouetteThickness != -1 ) && ( !params[info.m_nSilhouetteThickness]->IsDefined() ) )
{
params[info.m_nSilhouetteThickness]->SetFloatValue( kDefaultSilhouetteThickness );
}
if ( ( info.m_nSilhouetteColor != -1 ) && ( !params[info.m_nSilhouetteColor]->IsDefined() ) )
{
params[info.m_nSilhouetteColor]->SetVecValue( kDefaultSilhouetteColor[0], kDefaultSilhouetteColor[1], kDefaultSilhouetteColor[2], kDefaultSilhouetteColor[3] );
}
if ( ( info.m_nGroundMin != -1 ) && ( !params[info.m_nGroundMin]->IsDefined() ) )
{
params[info.m_nGroundMin]->SetFloatValue( kDefaultGroundMin );
}
if ( ( info.m_nGroundMax != -1 ) && ( !params[info.m_nGroundMax]->IsDefined() ) )
{
params[info.m_nGroundMax]->SetFloatValue( kDefaultGroundMax );
}
if ( ( info.m_nBlurAmount != -1 ) && ( !params[info.m_nBlurAmount]->IsDefined() ) )
{
params[info.m_nBlurAmount]->SetFloatValue( kDefaultBlurAmount );
}
SET_PARAM_FLOAT_IF_NOT_DEFINED( info.m_nTime, 0.0f );
}
void InitAftershock( CBaseVSShader *pShader, IMaterialVar** params, AftershockVars_t &info )
{
// Load textures
if ( (info.m_nBumpmap != -1) && params[info.m_nBumpmap]->IsDefined() )
{
pShader->LoadTexture( info.m_nBumpmap );
}
}
void DrawAftershock( CBaseVSShader *pShader, IMaterialVar** params, IShaderDynamicAPI *pShaderAPI,
IShaderShadow* pShaderShadow, AftershockVars_t &info, VertexCompressionType_t vertexCompression )
{
bool bBumpMapping = ( info.m_nBumpmap == -1 ) || !params[info.m_nBumpmap]->IsTexture() ? 0 : 1;
SHADOW_STATE
{
// Set stream format (note that this shader supports compression)
unsigned int flags = VERTEX_POSITION | VERTEX_NORMAL | VERTEX_FORMAT_COMPRESSED;
int nTexCoordCount = 1;
int userDataSize = 0;
pShaderShadow->VertexShaderVertexFormat( flags, nTexCoordCount, NULL, userDataSize );
// Vertex Shader
DECLARE_STATIC_VERTEX_SHADER( aftershock_vs20 );
SET_STATIC_VERTEX_SHADER( aftershock_vs20 );
// Pixel Shader
if( g_pHardwareConfig->SupportsPixelShaders_2_b() )
{
DECLARE_STATIC_PIXEL_SHADER( aftershock_ps20b );
SET_STATIC_PIXEL_SHADER( aftershock_ps20b );
}
else
{
DECLARE_STATIC_PIXEL_SHADER( aftershock_ps20 );
SET_STATIC_PIXEL_SHADER( aftershock_ps20 );
}
// Textures
pShaderShadow->EnableTexture( SHADER_SAMPLER0, true ); // Refraction texture
pShaderShadow->EnableSRGBRead( SHADER_SAMPLER0, true );
pShaderShadow->EnableTexture( SHADER_SAMPLER1, true ); // Bump
pShaderShadow->EnableSRGBRead( SHADER_SAMPLER1, false ); // Not sRGB
pShaderShadow->EnableSRGBWrite( true );
// Blending
pShader->EnableAlphaBlending( SHADER_BLEND_SRC_ALPHA, SHADER_BLEND_ONE_MINUS_SRC_ALPHA );
pShaderShadow->EnableAlphaWrites( false );
// !!! We need to turn this back on because EnableAlphaBlending() above disables it!
//pShaderShadow->EnableDepthWrites( true );
}
DYNAMIC_STATE
{
// Set Vertex Shader Combos
DECLARE_DYNAMIC_VERTEX_SHADER( aftershock_vs20 );
SET_DYNAMIC_VERTEX_SHADER_COMBO( SKINNING, pShaderAPI->GetCurrentNumBones() > 0 );
SET_DYNAMIC_VERTEX_SHADER_COMBO( COMPRESSED_VERTS, (int)vertexCompression );
SET_DYNAMIC_VERTEX_SHADER( aftershock_vs20 );
// Set Vertex Shader Constants
if ( info.m_nBumpTransform != -1 )
{
pShader->SetVertexShaderTextureTransform( VERTEX_SHADER_SHADER_SPECIFIC_CONST_1, info.m_nBumpTransform );
}
// Time % 1000
float vPackedVsConst1[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
float flTime = IS_PARAM_DEFINED( info.m_nTime ) && params[info.m_nTime]->GetFloatValue() > 0.0f ? params[info.m_nTime]->GetFloatValue() : pShaderAPI->CurrentTime();
vPackedVsConst1[0] = flTime;
vPackedVsConst1[0] -= (float)( (int)( vPackedVsConst1[0] / 1000.0f ) ) * 1000.0f;
pShaderAPI->SetVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_0, vPackedVsConst1, 1 );
// Set Pixel Shader Combos
if( g_pHardwareConfig->SupportsPixelShaders_2_b() )
{
DECLARE_DYNAMIC_PIXEL_SHADER( aftershock_ps20b );
SET_DYNAMIC_PIXEL_SHADER( aftershock_ps20b );
}
else
{
DECLARE_DYNAMIC_PIXEL_SHADER( aftershock_ps20 );
SET_DYNAMIC_PIXEL_SHADER( aftershock_ps20 );
}
// Bind textures
pShaderAPI->BindStandardTexture( SHADER_SAMPLER0, TEXTURE_FRAME_BUFFER_FULL_TEXTURE_0 ); // Refraction Map
if ( bBumpMapping )
{
pShader->BindTexture( SHADER_SAMPLER1, info.m_nBumpmap, info.m_nBumpFrame );
}
// Set Pixel Shader Constants
float vEyePos[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
pShaderAPI->GetWorldSpaceCameraPosition( vEyePos );
pShaderAPI->SetPixelShaderConstant( 5, vEyePos, 1 );
float vPackedConst1[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
vPackedConst1[0] = IS_PARAM_DEFINED( info.m_nBlurAmount ) ? params[info.m_nBlurAmount]->GetFloatValue() : kDefaultBlurAmount;
vPackedConst1[1] = IS_PARAM_DEFINED( info.m_nRefractAmount ) ? params[info.m_nRefractAmount]->GetFloatValue() : kDefaultRefractAmount;
vPackedConst1[3] = vPackedVsConst1[0]; // Time
pShaderAPI->SetPixelShaderConstant( 6, vPackedConst1, 1 );
// Refract color tint
pShaderAPI->SetPixelShaderConstant( 7, IS_PARAM_DEFINED( info.m_nColorTint ) ? params[info.m_nColorTint]->GetVecValue() : kDefaultColorTint, 1 );
// Silhouette values
float vPackedConst8[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
vPackedConst8[0] = IS_PARAM_DEFINED( info.m_nSilhouetteColor ) ? params[info.m_nSilhouetteColor]->GetVecValue()[0] : kDefaultSilhouetteColor[0];
vPackedConst8[1] = IS_PARAM_DEFINED( info.m_nSilhouetteColor ) ? params[info.m_nSilhouetteColor]->GetVecValue()[1] : kDefaultSilhouetteColor[1];
vPackedConst8[2] = IS_PARAM_DEFINED( info.m_nSilhouetteColor ) ? params[info.m_nSilhouetteColor]->GetVecValue()[2] : kDefaultSilhouetteColor[2];
vPackedConst8[3] = IS_PARAM_DEFINED( info.m_nSilhouetteThickness ) ? params[info.m_nSilhouetteThickness]->GetFloatValue() : kDefaultSilhouetteThickness;
pShaderAPI->SetPixelShaderConstant( 8, vPackedConst8, 1 );
// Ground min/max
float vPackedConst9[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
vPackedConst9[0] = IS_PARAM_DEFINED( info.m_nGroundMin ) ? params[info.m_nGroundMin]->GetFloatValue() : kDefaultGroundMin;
vPackedConst9[1] = IS_PARAM_DEFINED( info.m_nGroundMax ) ? params[info.m_nGroundMax]->GetFloatValue() : kDefaultGroundMax;
pShaderAPI->SetPixelShaderConstant( 9, vPackedConst9, 1 );
// Set c0 and c1 to contain first two rows of ViewProj matrix
VMatrix mView, mProj;
pShaderAPI->GetMatrix( MATERIAL_VIEW, mView.m[0] );
pShaderAPI->GetMatrix( MATERIAL_PROJECTION, mProj.m[0] );
VMatrix mViewProj = mView * mProj;
mViewProj = mViewProj.Transpose3x3();
pShaderAPI->SetPixelShaderConstant( 0, mViewProj.m[0], 2 );
}
pShader->Draw();
}
|
ragnarok87/zarb-go | util/slice_test.go | package util
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestSliceToInt(t *testing.T) {
i1 := -1
s := IntToSlice(i1)
i2 := SliceToInt(s)
assert.Equal(t, i1, i2)
}
func TestSliceToUInt(t *testing.T) {
i1 := uint(0)
i1--
s := UIntToSlice(i1)
i2 := SliceToUInt(s)
assert.Equal(t, i1, i2)
}
func TestSliceToInt64(t *testing.T) {
i1 := MaxInt64
s := Int64ToSlice(i1)
i2 := SliceToInt64(s)
assert.Equal(t, i1, i2)
}
func TestSliceToUInt64(t *testing.T) {
i1 := MaxUint64
s := UInt64ToSlice(i1)
i2 := SliceToUInt64(s)
assert.Equal(t, i1, i2)
}
|
clumsy456/huaweicloud-sdk-go-v3 | services/iotda/v5/model/model_device_message_condition.go | package model
import (
"encoding/json"
"strings"
)
// 条件中设备消息类型的信息,自定义结构。
type DeviceMessageCondition struct {
// 设备关联的产品ID,用于唯一标识一个产品模型,在管理门户导入产品模型后由平台分配获得。
ProductId *string `json:"product_id,omitempty"`
// 产品关联的topic信息,用于过滤消息中指定topic消息。
Topic *string `json:"topic,omitempty"`
}
func (o DeviceMessageCondition) String() string {
data, err := json.Marshal(o)
if err != nil {
return "DeviceMessageCondition struct{}"
}
return strings.Join([]string{"DeviceMessageCondition", string(data)}, " ")
}
|
SSG-DRD-IOT/commercial-iot-security-system | opencv/experiments_raw/videoStreaming/videoStreaming.py | <filename>opencv/experiments_raw/videoStreaming/videoStreaming.py
import numpy as np
import cv2
from onlinevid import OnlineVideo
import time
url = 'http://192.168.0.108:8080/video'
# cap = OnlineVideo('http://172.16.58.3/mjpg/1/video.mjpg?camera=1')
cap = OnlineVideo(url)
# frame_old = np.zeros((480, 640), np.uint8)
# http://192.168.0.108:8080/video.mjpg
while(True):
frame = cap.getFrame()
# if frame == None:
# # frame = np.zeros((480, 640), np.uint8)
# frame = frame_old
# frame_old = frame
# time.sleep(.01)
# print np.shape(frame)
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == 27:
break
elif cv2.waitKey(1) & 0xFF == ord('r'):
cap = OnlineVideo(url)
print('retarting')
cv2.destroyAllWindows()
|
mbarall/opensha-dev | src/scratch/kevin/simulators/ruptures/CatalogSRF_Writer.java | package scratch.kevin.simulators.ruptures;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.opensha.sha.simulators.RSQSimEvent;
import org.opensha.sha.simulators.srf.RSQSimEventSlipTimeFunc;
import org.opensha.sha.simulators.srf.RSQSimSRFGenerator;
import org.opensha.sha.simulators.srf.RSQSimSRFGenerator.SRFInterpolationMode;
import org.opensha.sha.simulators.srf.SRF_PointData;
import org.opensha.sha.simulators.utils.SimulatorUtils;
import com.google.common.base.Preconditions;
import scratch.kevin.simulators.RSQSimCatalog;
import scratch.kevin.simulators.RSQSimCatalog.Catalogs;
public class CatalogSRF_Writer {
public static void main(String[] args) throws IOException {
File baseDir = new File("/data/kevin/simulators/catalogs");
RSQSimCatalog catalog = Catalogs.BRUCE_2457.instance(baseDir);
File outputDir = new File(catalog.getCatalogDir(), "srfs");
Preconditions.checkState(outputDir.exists() || outputDir.mkdir());
double minMag = 6.5;
double skipYears = 5000;
double maxDuration = 10000;
double dt = RSQSimBBP_Config.SRF_DT;
SRFInterpolationMode interp = RSQSimBBP_Config.SRF_INTERP_MODE;
double srfVersion = RSQSimBBP_Config.SRF_VERSION;
List<RSQSimEvent> events = catalog.loader().minMag(minMag).skipYears(skipYears).maxDuration(maxDuration).load();
System.out.println("Loaded "+events.size()+" events in "+SimulatorUtils.getSimulationDurationYears(events)+" yrs");
int cnt = 0;
for (RSQSimEvent e : events) {
if (cnt % 100 == 0)
System.out.println("Writing event "+cnt+"/"+events.size());
cnt++;
RSQSimEventSlipTimeFunc slipTimeFunc = catalog.getSlipTimeFunc(e);
File srfFile = new File(outputDir, "event_"+e.getID()+".srf");
List<SRF_PointData> srfPoints = RSQSimSRFGenerator.buildSRF(slipTimeFunc, e.getAllElements(), dt, interp);
SRF_PointData.writeSRF(srfFile, srfPoints, srfVersion);
}
}
}
|
LaudateCorpus1/devhub | tests/utils/validate-env-variables.test.js | <reponame>LaudateCorpus1/devhub
import { validateEnvVariables } from '../../src/utils/setup/validate-env-variables';
it('should properly require specific environment variables at build-time', () => {
const oldEnv = process.env;
process.env = {
...oldEnv,
};
// jest requires the test function to be wrapped, otherwise the error is not caught
expect(() => {
validateEnvVariables();
}).toThrow();
process.env.GATSBY_SITE = 'devhub';
process.env.GATSBY_PARSER_USER = 'test-user';
// Should throw unless all three env vars are set
// GATSBY_SITE, GATSBY_PARSER_USER, GATSBY_PARSER_BRANCH
expect(() => {
validateEnvVariables();
}).toThrow();
process.env.GATSBY_PARSER_BRANCH = 'test-branch';
expect(() => {
validateEnvVariables();
}).not.toThrow();
process.env = oldEnv;
});
|
desmosinc/fluent.js | fluent-react/examples/redux-async/src/App.js | <reponame>desmosinc/fluent.js<gh_stars>1-10
import React from 'react';
import { connect} from 'react-redux';
import { Localized } from 'fluent-react/compat';
import { changeLocales } from './actions';
function App(props) {
const { currentLocales, isFetching, changeLocales } = props;
const [current] = currentLocales;
const available = ['en-US', 'pl'];
const next = available[(available.indexOf(current ) + 1) % available.length];
return (
<div>
<Localized id="title">
<h1>Hello, world!</h1>
</Localized>
<Localized id="current" $locale={current}>
<p>{'Current locale: { $locale }'}</p>
</Localized>
<Localized id="change" $locale={next}>
<button disabled={isFetching} onClick={evt => changeLocales([next])}>
{'Change to { $locale }'}
</button>
</Localized>
</div>
);
}
const mapStateToProps = state => ({
currentLocales: state.currentLocales,
isFetching: state.isFetching
});
const mapDispatchToProps = { changeLocales };
export default connect(mapStateToProps, mapDispatchToProps)(App);
|
vot-developer/practice | src/test/java/org/algorithms/coding_patterns/educative/subsets/UniqueTreesTest.java | package org.algorithms.coding_patterns.educative.subsets;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class UniqueTreesTest {
@Test
void findUniqueTrees2() {
List<TreeNode> result = UniqueTrees.findUniqueTrees(2);
assertEquals(2, result.size());
assertEquals(1, result.get(0).val);
assertEquals(2, result.get(0).right.val);
assertEquals(2, result.get(1).val);
assertEquals(1, result.get(1).left.val);
}
} |
Bravedragon0313/dolglo313 | packages/admin-web-angular/src/app/pages/+profile/edit/basic-info/basic-info.component.js | <reponame>Bravedragon0313/dolglo313
import { __awaiter, __decorate, __metadata } from "tslib";
import { Component, Input } from '@angular/core';
import { FormBuilder, Validators, } from '@angular/forms';
import Admin from '@modules/server.common/entities/Admin';
import { takeUntil, first } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { AdminsService } from '../../../../@core/data/admins.service';
import { getDummyImage } from '@modules/server.common/utils';
import { ToasterService } from 'angular2-toaster';
import { TranslateService } from '@ngx-translate/core';
import 'rxjs/add/operator/debounceTime';
let BasicInfoComponent = class BasicInfoComponent {
constructor(formBuilder, adminsService, toasterService, _translateService) {
this.formBuilder = formBuilder;
this.adminsService = adminsService;
this.toasterService = toasterService;
this._translateService = _translateService;
this.INVALID_EMAIL_ADDRESS = 'INVALID_EMAIL_ADDRESS';
this.INVALID_URL = 'INVALID_URL';
this.NAME_MUST_CONTAIN_ONLY_LETTERS = 'NAME_MUST_CONTAIN_ONLY_LETTERS';
this.PREFIX = 'PROFILE_VIEW.';
this.ngDestroy$ = new Subject();
this.validations = {
usernameControl: () => {
this.username.valueChanges
.debounceTime(500)
.pipe(takeUntil(this.ngDestroy$))
.subscribe((value) => {
this.usernameErrorMsg = this.hasError(this.username)
? Object.keys(this.username.errors)[0]
: '';
});
},
emailControl: () => {
this.email.valueChanges
.debounceTime(500)
.pipe(takeUntil(this.ngDestroy$))
.subscribe((value) => {
this.emailErrorMsg = this.hasError(this.email)
? this.email.errors.email
? this.invalidEmailAddress()
: Object.keys(this.email.errors)[0]
: '';
});
},
firstNameControl: () => {
this.firstName.valueChanges
.debounceTime(500)
.pipe(takeUntil(this.ngDestroy$))
.subscribe((value) => {
this.firstNameErrorMsg = this.hasError(this.firstName)
? this.firstName.errors.pattern
? this.nameMustContainOnlyLetters()
: Object.keys(this.firstName.errors)[0]
: '';
});
},
lastNameControl: () => {
this.lastName.valueChanges
.debounceTime(500)
.pipe(takeUntil(this.ngDestroy$))
.subscribe((value) => {
this.lastNameErrorMsg = this.hasError(this.lastName)
? this.lastName.errors.pattern
? this.nameMustContainOnlyLetters()
: Object.keys(this.lastName.errors)[0]
: '';
});
},
};
this.getUploaderPlaceholderText();
this.buildForm();
this.bindFormControls();
this._applyTranslationOnSmartTable();
this.loadControls();
}
get pictureUrlErrorMsg() {
return this.picture.errors.pattern
? this.invalidURL()
: Object.keys(this.picture.errors)[0];
}
ngOnChanges() {
this._applyTranslationOnSmartTable();
if (this.admin) {
this.username.setValue(this.admin.name);
this.email.setValue(this.admin.email);
this.picture.setValue(this.admin.pictureUrl);
this.firstName.setValue(this.admin.firstName);
this.lastName.setValue(this.admin.lastName);
}
}
ngOnDestroy() {
this.ngDestroy$.next();
this.ngDestroy$.complete();
}
invalidEmailAddress() {
return this._translate(this.PREFIX + this.INVALID_EMAIL_ADDRESS);
}
invalidURL() {
return this._translate(this.PREFIX + this.INVALID_URL);
}
nameMustContainOnlyLetters() {
return this._translate(this.PREFIX + this.NAME_MUST_CONTAIN_ONLY_LETTERS);
}
saveChanges() {
return __awaiter(this, void 0, void 0, function* () {
try {
this.loading = true;
const res = yield this.adminsService
.updateById(this.admin.id, this.getAdminCreateObj())
.pipe(first())
.toPromise();
this.loading = false;
this.toasterService.pop('success', 'Successfully updated data');
}
catch (error) {
this.loading = false;
this.toasterService.pop('error', error);
}
});
}
buildForm() {
const imgUrlRegex = new RegExp(`(http(s?):)s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))`);
const nameRegex = new RegExp(`^[a-z ,.'-]+$`, 'i');
this.basicInfoForm = this.formBuilder.group({
username: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
picture: ['', [Validators.pattern(imgUrlRegex)]],
firstName: ['', Validators.pattern(nameRegex)],
lastName: ['', Validators.pattern(nameRegex)],
});
}
bindFormControls() {
this.username = this.basicInfoForm.get('username');
this.email = this.basicInfoForm.get('email');
this.picture = this.basicInfoForm.get('picture');
this.firstName = this.basicInfoForm.get('firstName');
this.lastName = this.basicInfoForm.get('lastName');
}
loadControls() {
this.validations.usernameControl();
this.validations.emailControl();
this.validations.firstNameControl();
this.validations.lastNameControl();
}
deleteImg() {
this.picture.setValue('');
this.basicInfoForm.markAsDirty();
}
_applyTranslationOnSmartTable() {
this._translateService.onLangChange.subscribe(() => {
this.loadControls();
});
}
hasError(control) {
return (control.touched || control.dirty) && control.errors;
}
getAdminCreateObj() {
if (!this.picture.value) {
const letter = this.username.value.charAt(0).toUpperCase();
this.picture.setValue(getDummyImage(300, 300, letter));
}
return {
name: this.username.value,
email: this.email.value,
firstName: this.firstName.value,
lastName: this.lastName.value,
pictureUrl: this.picture.value,
};
}
_translate(key) {
let translationResult = '';
this._translateService.get(key).subscribe((res) => {
translationResult = res;
});
return translationResult;
}
getUploaderPlaceholderText() {
return __awaiter(this, void 0, void 0, function* () {
this.uploaderPlaceholder = yield this._translateService
.get('PROFILE_VIEW.PICTURE_URL')
.pipe(first())
.toPromise();
});
}
};
__decorate([
Input(),
__metadata("design:type", Admin)
], BasicInfoComponent.prototype, "admin", void 0);
BasicInfoComponent = __decorate([
Component({
selector: 'ea-basic-info',
styleUrls: ['/basic-info.component.scss'],
templateUrl: './basic-info.component.html',
}),
__metadata("design:paramtypes", [FormBuilder,
AdminsService,
ToasterService,
TranslateService])
], BasicInfoComponent);
export { BasicInfoComponent };
//# sourceMappingURL=basic-info.component.js.map |
lacastrillov/marketplatform | src/main/java/com/lacv/marketplatform/dtos/MailDto.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.lacv.marketplatform.dtos;
import com.dot.gcpbasedot.annotation.ColumnWidth;
import com.dot.gcpbasedot.annotation.HideField;
import com.dot.gcpbasedot.annotation.Order;
import com.dot.gcpbasedot.annotation.ReadOnly;
import com.dot.gcpbasedot.annotation.TextField;
import com.dot.gcpbasedot.annotation.TypeFormField;
import com.dot.gcpbasedot.domain.BaseEntity;
import com.dot.gcpbasedot.enums.FieldType;
import com.dot.gcpbasedot.enums.HideView;
import java.util.Date;
/**
*
* @author lacastrillov
*/
public class MailDto implements BaseEntity {
private static final long serialVersionUID = 1L;
@Order(1)
@ColumnWidth(100)
@ReadOnly
private Integer id;
@Order(2)
@TextField("De")
private String mailFrom;
@Order(3)
@TextField("Para")
private String mailTo;
@Order(4)
@TextField("Asunto")
private String subject;
@Order(5)
@TextField("Mensaje")
@TypeFormField(FieldType.HTML_EDITOR)
@HideField({HideView.FILTER})
@ColumnWidth(500)
private String message;
@Order(6)
@TextField("Fecha Envío")
private Date sendDate;
@Order(7)
@TextField("Resultado")
@TypeFormField(value = FieldType.LIST, data = {"Pendiente", "Enviado", "Rechazado", "Error"})
private String result;
private MailTemplateDto mailTemplate;
public MailDto() {
}
public MailDto(Integer id) {
this.id = id;
}
@Override
public Integer getId() {
return id;
}
@Override
public void setId(Object id) {
this.id = (Integer) id;
}
public String getMailFrom() {
return mailFrom;
}
public void setMailFrom(String mailFrom) {
this.mailFrom = mailFrom;
}
public String getMailTo() {
return mailTo;
}
public void setMailTo(String mailTo) {
this.mailTo = mailTo;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Date getSendDate() {
return sendDate;
}
public void setSendDate(Date sendDate) {
this.sendDate = sendDate;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public MailTemplateDto getMailTemplate() {
return mailTemplate;
}
public void setMailTemplate(MailTemplateDto mailTemplate) {
this.mailTemplate = mailTemplate;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof MailDto)) {
return false;
}
MailDto other = (MailDto) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.lacv.marketplatform.entities.MailDto[ id=" + id + " ]";
}
}
|
sjoerdvankreel/xt-audio | src/cpp/sample/RenderSimple.cpp | <reponame>sjoerdvankreel/xt-audio
#define _USE_MATH_DEFINES 1
#include <xt/XtAudio.hpp>
#include <cmath>
#include <chrono>
#include <thread>
#include <cstdint>
static float _phase = 0.0f;
static float const Frequency = 440.0f;
static Xt::Channels const Channels(0, 0, 1, 0);
static Xt::Mix const Mix(44100, Xt::Sample::Float32);
static Xt::Format const Format(Mix, Channels);
static float
NextSample()
{
_phase += Frequency / Mix.rate;
if (_phase >= 1.0f) _phase = -1.0f;
return sinf(2.0f * _phase * static_cast<float>(M_PI));
}
static uint32_t
OnBuffer(Xt::Stream const& stream, Xt::Buffer const& buffer, void* user)
{
float* output = static_cast<float*>(buffer.output);
for (int32_t f = 0; f < buffer.frames; f++) output[f] = NextSample();
return 0;
}
int
RenderSimpleMain()
{
std::unique_ptr<Xt::Platform> platform = Xt::Audio::Init("", nullptr);
Xt::System system = platform->SetupToSystem(Xt::Setup::ConsumerAudio);
std::unique_ptr<Xt::Service> service = platform->GetService(system);
if (!service) return 0;
std::optional<std::string> id = service->GetDefaultDeviceId(true);
if(!id.has_value()) return 0;
std::unique_ptr<Xt::Device> device = service->OpenDevice(id.value());
if(!device->SupportsFormat(Format)) return 0;
double bufferSize = device->GetBufferSize(Format).current;
Xt::StreamParams streamParams(true, OnBuffer, nullptr, nullptr);
Xt::DeviceStreamParams deviceParams(streamParams, Format, bufferSize);
std::unique_ptr<Xt::Stream> stream = device->OpenStream(deviceParams, nullptr);
stream->Start();
std::this_thread::sleep_for(std::chrono::seconds(2));
stream->Stop();
return 0;
} |
glhrmfrts/TokuNoSora | core/src/com/habboi/tns/utils/FontManager.java | <filename>core/src/com/habboi/tns/utils/FontManager.java
package com.habboi.tns.utils;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.utils.GdxRuntimeException;
import java.util.HashMap;
/**
* Loads fonts of different sizes.
*/
public class FontManager {
private AssetManager am;
private HashMap<String, FontLoader.FontParameter> fontParams = new HashMap<>();
private static FontManager instance;
public static FontManager get() {
if (instance == null) {
instance = new FontManager();
}
return instance;
}
public void setAssetManager(AssetManager am) {
this.am = am;
}
public void loadFont(String file, int size) {
String key = getKey(file, size);
FontLoader.FontParameter param = new FontLoader.FontParameter(size);
fontParams.put(key, param);
am.load(key, BitmapFont.class, param);
}
public BitmapFont getFont(String file, int size) {
String key = getKey(file, size);
if (!am.isLoaded(key) || !fontParams.containsKey(key)) {
throw new GdxRuntimeException("font " + file + " not loaded with size: " + size);
}
return fontParams.get(key).font;
}
private String getKey(String file, int size) {
return file + "." + size;
}
}
|
phmills/Junicon | src/source/interpreter/src/main/java/edu/uidaho/junicon/interpreter/interpreter/Environment.java | //========================================================================
// Copyright (c) 2011 Orielle, LLC.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// This software is provided by the copyright holders and contributors
// "as is" and any express or implied warranties, including, but not
// limited to, the implied warranties of merchantability and fitness for
// a particular purpose are disclaimed. In no event shall the copyright
// holder or contributors be liable for any direct, indirect, incidental,
// special, exemplary, or consequential damages (including, but not
// limited to, procurement of substitute goods or services; loss of use,
// data, or profits; or business interruption) however caused and on any
// theory of liability, whether in contract, strict liability, or tort
// (including negligence or otherwise) arising in any way out of the use
// of this software, even if advised of the possibility of such damage.
//========================================================================
package edu.uidaho.junicon.interpreter.interpreter;
import java.util.*;
/**
* Provides thread-safe methods to set and get environment variables.
* Delegation of environment to another IEnvironment is supported.
*
* @author <NAME>
*/
public class Environment extends PropertiesExtender
implements IEnvironment, IPropertiesExtender
{
// Local environment
private Object envLock = new Object();
private Map<String, Object> localEnv = new HashMap<String, Object>();
private IEnvironment envDelegate = null;
/**
* Constructor.
*/
public Environment () {
init(null);
}
/**
* Constructor with delegate environment.
*/
public Environment (IEnvironment delegateEnvironment) {
super();
init(delegateEnvironment);
}
/**
* Constructor with delegate environment and default properties.
*/
public Environment (IEnvironment delegateEnvironment,
Properties defaultProperties) {
super(defaultProperties);
init(delegateEnvironment);
}
/**
* Initializer.
*/
private void init(IEnvironment delegateEnvironment) {
envDelegate = delegateEnvironment;
}
//======================================================================
// Environment access with delegation
//======================================================================
public Object getEnv (String name) {
Object retval = null;
synchronized (envLock) {
if (envDelegate == null) { retval = localEnv.get(name);
} else { retval = envDelegate.getEnv(name); };
};
return retval;
}
public Object getEnv (String name, Object defaultValue) {
Object retval = getEnv(name);
if (retval == null) { retval = defaultValue; };
return retval;
}
public void setEnv (String name, Object value) {
synchronized (envLock) {
if (envDelegate == null) { localEnv.put(name, value);
} else { envDelegate.setEnv(name, value); };
};
}
public String[] getEnvNames () {
String[] retval = null;
synchronized (envLock) {
if (envDelegate == null) {
retval = (String[]) localEnv.keySet().toArray(new String[0]);
} else { retval = envDelegate.getEnvNames(); };
};
return retval;
}
public void setDelegateEnvironment (IEnvironment delegate) {
init(delegate);
}
public IEnvironment getDelegateEnvironment () {
return envDelegate;
}
public IEnvironment getEnvironment () {
return this;
}
}
//==== END OF FILE
|
ghsecuritylab/AliOS-Things_rel_1.3.1 | security/libid2/sample/id2_test.c | <reponame>ghsecuritylab/AliOS-Things_rel_1.3.1
/**
* Copyright (C) 2017 The YunOS Project. All rights reserved.
*/
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "sm_id2.h"
#if CONFIG_AOS_SUPPORT
#include "aos/kernel.h"
#endif
#if ID2_MULT_SUPPORT
#include <pthread.h>
#endif
//only support aes key later
#define ID2_RSA_KEY 0
#define ID2_AES_KEY 1
#define ID_LEN (24)
#define SIGN_LEN (128)
#define THREAD_NUM 0x01
#define TEST_COUNT 0x01
#define SYM_TEST_DATA_LEN 48
#if ID2_MULT_SUPPORT
static uint8_t thread_id = 0;
#endif
uint8_t test_data[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88,
0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x00};
uint32_t test_data_len = 16;
uint8_t test_data1[SIGN_LEN] = {0x00};
uint32_t test_data1_len = SIGN_LEN;
static uint8_t aes_test_data[SYM_TEST_DATA_LEN] = {
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66
};
uint32_t short_test_count = 5;
uint32_t short_test_len[] = {13, 17, 35, 16, 32};
void id2_test_dump_data(char *name, uint8_t *data, uint32_t len)
{
uint32_t i;
printf("name is %s, len is %d\n", name, len);
for (i = 0; i < (len - len % 8); i += 8) {
printf("%s: %02x %02x %02x %02x %02x %02x %02x %02x\n",
name, data[i+0], data[i+1], data[i+2], data[i+3],
data[i+4], data[i+5], data[i+6], data[i+7]);
}
printf("%s:: ", name);
while(i < len) {
printf("%02x, ", data[i++]);
}
printf("\n");
return;
}
int test_get_id()
{
int ret;
uint8_t id_value[ID_LEN + 1];
uint32_t id2_len = ID_LEN;
ret = tee_get_ID2(id_value, &id2_len);
if (ret < 0) {
printf("fail to get ID!\n");
return ret;
}
id_value[ID_LEN] = '\0';
printf("id2_len is %d, ID2 ID: %s\n", id2_len, id_value);
return ret;
}
#if ID2_AES_KEY
int test_cipher(uint8_t cipher_type, uint8_t block_mode, uint8_t padding_type)
{
uint32_t test_len = 0;
int ret = 0;
uint8_t ID = KEY_ID_33;
cipher_param_t cipher_param;
uint8_t in[128];
uint32_t in_len = 0;
uint8_t *enc = NULL;
uint32_t enc_len = 0;
uint8_t *dec = NULL;
uint32_t dec_len = 0;
uint8_t *iv = NULL;
uint8_t iv_len = 0;
uint8_t test_iv[16] = {
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66,
};
if (padding_type == SM_PKCS5) {
test_len = SYM_TEST_DATA_LEN - 3;
} else {
test_len = SYM_TEST_DATA_LEN;
}
if (block_mode == SM_ECB) {
iv = NULL;
} else if (block_mode == SM_CBC || block_mode == SM_CTR) {
iv = test_iv;
iv_len = 16;
}
in_len = test_len;
cipher_param.cipher_type = cipher_type;
cipher_param.block_mode = block_mode;
cipher_param.padding_type = padding_type;
cipher_param.is_enc = SM_ENCRYPT;
memcpy(in, aes_test_data, test_len);
ret = tee_sym_cipher(ID, &cipher_param, iv, iv_len,
in, in_len, enc, &enc_len);
if (!ret) {
printf("fail to get cipher enc len\n");
ret = -1;
return ret;
}
enc = malloc(enc_len);
if (!enc) {
printf("malloc enc buffer failed\n");
return -1;
}
ret = tee_sym_cipher(ID, &cipher_param, iv, iv_len,
in, in_len, enc, &enc_len);
if (ret) {
printf("fail to cipher enc\n");
ret = -1;
goto clean1;
}
#if ID2_TEST_DEBUG
id2_test_dump_data("enc is:", enc, enc_len);
#endif
//test decrypt
cipher_param.is_enc = SM_DECRYPT;
ret = tee_sym_cipher(ID, &cipher_param, iv, iv_len,
enc, enc_len, dec, &dec_len);
if (!ret) {
printf("fail to get cipher dec len %d\n", ret);
ret = -1;
goto clean1;
}
dec = malloc(dec_len);
if (!dec) {
printf("malloc enc buffer failed\n");
ret = -1;
goto clean1;
}
ret = tee_sym_cipher(ID, &cipher_param, iv, iv_len,
enc, enc_len, dec, &dec_len);
if (ret) {
printf("fail to cipher dec\n");
ret = -1;
goto clean2;
}
#if ID2_TEST_DEBUG
id2_test_dump_data("dec is:", dec, dec_len);
#endif
if (memcmp(in, dec, in_len)) {
printf("decrypt result is not correct\n");
ret = -1;
} else {
printf("sym cipher test success\n");
}
clean2:
if (dec) {
free(dec);
dec = NULL;
}
clean1:
if (enc) {
free(enc);
enc = NULL;
}
return ret;
}
int test_cipher_short_buffer(uint8_t cipher_type,
uint8_t block_mode, uint32_t index)
{
uint32_t test_len = short_test_len[index];
int ret = 0;
uint8_t ID = KEY_ID_33;
cipher_param_t cipher_param;
uint8_t in[128];
uint32_t in_len = test_len;
uint8_t *enc = NULL;
uint32_t enc_len = 0;
uint8_t *dec = NULL;
uint32_t dec_len = 0;
uint8_t tmp_buf[SYM_TEST_DATA_LEN];
uint8_t *iv = NULL;
uint32_t iv_len = 0;
uint8_t test_iv[16] = {
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66,
};
cipher_param.cipher_type = cipher_type;
cipher_param.block_mode = block_mode;
cipher_param.padding_type = SM_PKCS5;
cipher_param.is_enc = SM_ENCRYPT;
if (block_mode == SM_ECB) {
iv = NULL;
} else if (block_mode == SM_CBC || block_mode == SM_CTR) {
iv = test_iv;
iv_len = 16;
}
memcpy(in, aes_test_data, test_len);
enc_len = in_len;
ret = tee_sym_cipher(ID, &cipher_param, iv, iv_len,
in, in_len, tmp_buf, &enc_len);
if (!ret) {
printf("fail to get cipher enc len\n");
ret = -1;
return ret;
}
printf("ID2_SHORT_BUFFER: get enc len is %d\n", enc_len);
enc = malloc(enc_len);
if (!enc) {
printf("malloc enc buffer failed\n");
return -1;
}
ret = tee_sym_cipher(ID, &cipher_param, iv, iv_len,
in, in_len, enc, &enc_len);
if (ret) {
printf("fail to cipher enc\n");
ret = -1;
goto clean1;
}
#if ID2_TEST_DEBUG
id2_test_dump_data("enc is:", enc, enc_len);
#endif
//test decrypt
cipher_param.is_enc = SM_DECRYPT;
dec_len = in_len - 1;
ret = tee_sym_cipher(ID, &cipher_param, iv, iv_len,
enc, enc_len, tmp_buf, &dec_len);
if (!ret) {
printf("fail to get cipher dec len %d\n", ret);
ret = -1;
goto clean1;
}
printf("ID2_SHORT_BUFFER: dec len is %d\n", dec_len);
dec = malloc(dec_len);
if (!dec) {
printf("malloc enc buffer failed\n");
ret = -1;
goto clean1;
}
ret = tee_sym_cipher(ID, &cipher_param, iv, iv_len,
enc, enc_len, dec, &dec_len);
if (ret) {
printf("fail to cipher dec\n");
ret = -1;
goto clean2;
}
#if ID2_TEST_DEBUG
id2_test_dump_data("dec is:", dec, dec_len);
#endif
if (memcmp(in, dec, in_len)) {
printf("decrypt result is not correct\n");
ret = -1;
} else {
printf("sym cipher test success\n");
}
clean2:
if (dec) {
free(dec);
dec = NULL;
}
clean1:
if (enc) {
free(enc);
enc = NULL;
}
return ret;
}
int test_sym_cipher()
{
int ret = 0;
ret = test_get_id();
if (ret) {
printf("get id failed\n");
return -1;
}
ret = test_cipher(SM_AES, SM_ECB, SM_PKCS5);
if (ret) {
printf("test aes ecb pkcs5 failed\n");
return ret;
}
ret = test_cipher(SM_AES, SM_CBC, SM_PKCS5);
if (ret) {
printf("test aes ecb pkcs5 failed\n");
return ret;
}
ret = test_cipher(SM_AES, SM_ECB, SM_No_PADDING);
if (ret) {
printf("test aes ecb no padding failed\n");
return ret;
}
ret = test_cipher(SM_AES, SM_CBC, SM_No_PADDING);
if (ret) {
printf("test aes ecb no padding failed\n");
return ret;
}
ret = test_cipher(SM_AES, SM_CTR, SM_No_PADDING);
if (ret) {
printf("test aes ecb no padding failed\n");
return ret;
}
return ret;
}
int test_short_sym_cipher()
{
int ret = 0;
int i = 0;
ret = test_get_id();
if (ret) {
printf("get id failed\n");
return -1;
}
for (i = 0; i < short_test_count; i++) {
ret = test_cipher_short_buffer(SM_AES, SM_ECB, i);
if (ret) {
printf("test aes ecb pkcs5 failed\n");
return ret;
}
ret = test_cipher_short_buffer(SM_AES, SM_CBC, i);
if (ret) {
printf("test aes ecb pkcs5 failed\n");
return ret;
}
}
return ret;
}
int test_whole_sym()
{
int ret = 0;
ret = test_sym_cipher();
if (ret) {
printf("test sym cipher success\n");
return -1;
}
printf("\n<<<<<<< test sym cipher success>>>>>>>>\n");
ret = test_short_sym_cipher();
if (ret) {
printf("test short sym cipher success\n");
return -1;
}
printf("\n<<<<<<< test short sym cipher success>>>>>>>>\n");
return 0;
}
int test_sym_perf()
{
int ret = 0;
uint32_t data_len = 100;
uint8_t data[128];
uint32_t test_num = 10000;
uint8_t ID = KEY_ID_33;
uint8_t enc[256];
uint32_t enc_len = 256;
uint8_t dec[256];
uint32_t dec_len = 256;
uint32_t i = 0;
cipher_param_t cipher_param;
#if (CONFIG_GENERIC_LINUX)
time_t start_time, end_time;
#else
long long yos_time1, yos_time2;
#endif
double total_time, av_time;
memset(data, 0x33, data_len);
#if (CONFIG_GENERIC_LINUX)
start_time = time(NULL);
#else
yos_time1 = aos_now_ms();
#endif
cipher_param.cipher_type = SM_AES;
cipher_param.block_mode = SM_ECB;
cipher_param.padding_type = SM_PKCS5;
cipher_param.is_enc = SM_ENCRYPT;
for(i = 0; i < test_num; i++) {
ret = tee_sym_cipher(ID, &cipher_param, NULL, 0,
data, data_len, enc, &enc_len);
if (ret < 0) {
printf("fail to sign data!\n");
return ret;
}
}
#if CONFIG_GENERIC_LINUX
end_time = time(NULL);
total_time = difftime(end_time, start_time);
#else
yos_time2 = aos_now_ms();
total_time = ((yos_time2 - yos_time1) & 0x00000000ffffffff);
#endif
av_time = total_time / test_num;
printf("cipher enc total time: %f, av_time: %f\n", total_time, av_time);
#if CONFIG_GENERIC_LINUX
start_time = time(NULL);
#else
yos_time1 = aos_now_ms();
#endif
cipher_param.is_enc = SM_DECRYPT;
for (i = 0; i < test_num; i++) {
ret = tee_sym_cipher(ID, &cipher_param, NULL, 0,
enc, enc_len, dec, &dec_len);
if (ret < 0) {
printf("fail to verify data!\n");
return ret;
}
}
#if CONFIG_GENERIC_LINUX
end_time = time(NULL);
total_time = difftime(end_time, start_time);
#else
yos_time2 = aos_now_ms();
total_time = ((yos_time2 - yos_time1) & 0x00000000ffffffff);
#endif
av_time = total_time / test_num;
printf("cipher dec total time: %f, av_time: %f\n", total_time, av_time);
return 0;
}
#endif
#if ID2_RSA_KEY
int test_sig_ver(uint8_t type, uint8_t *data, uint32_t data_len)
{
int ret;
uint8_t ID = KEY_ID_0;
uint8_t digest[SIGN_LEN];
uint32_t digest_len = SIGN_LEN;
ret = tee_RSA_sign(ID, data, data_len, digest, &digest_len, type);
if (ret < 0) {
printf("fail to sign data!\n");
return ret;
}
ret = tee_RSA_verify(ID, data, data_len, digest, digest_len, type);
if (ret < 0) {
printf("fail to verify data!\n");
return ret;
}
printf("test %d sig and ver success\n", type);
return 0;
}
int test_enc_dec(uint8_t padding, uint8_t *data, uint32_t data_len)
{
int ret;
uint8_t ID = KEY_ID_0;
uint8_t *enc_data = NULL;
uint32_t enc_len = 0;
uint8_t *dec_data = NULL;
uint32_t dec_len = 0;
if ((padding != SM_No_PADDING) &&
(padding != SM_PKCS1_PADDING)) {
printf("wriong padding type %d\n", padding);
return -1;
}
ret = tee_RSA_public_encrypt(ID,
data, data_len, enc_data, &enc_len, padding);
if (ret == 0) {
printf("fail to get enc len\n");
ret = -1;
return ret;
}
enc_data = malloc(enc_len);
if (!enc_data) {
printf("malloc failed\n");
return -1;
}
ret = tee_RSA_public_encrypt(ID,
data, data_len, enc_data, &enc_len, padding);
if (ret < 0 || enc_len != SIGN_LEN) {
printf("fail to encrypt data data len is %d,enc len is %d\n", data_len, enc_len);
ret = -1;
goto clean;
}
printf("rsa encrypted data len: %d\n", enc_len);
ret = tee_RSA_private_decrypt(ID,
enc_data, enc_len, dec_data, &dec_len, padding);
if (ret == 0) {
printf("fail to get decrypt len!\n");
ret = -1;
goto clean;
}
printf("rsa decrypted data len: %d\n", dec_len);
dec_data = malloc(dec_len);
if (!dec_data) {
free(dec_data);
dec_data = NULL;
}
ret = tee_RSA_private_decrypt(ID,
enc_data, enc_len, dec_data, &dec_len, padding);
if (ret < 0) {
printf("fail to decrypt len!\n");
ret = -1;
goto clean;
}
if (memcmp(data, dec_data, data_len)) {
printf("bad decrypt result\n");
#if ID2_TEST_DEBUG
id2_test_dump_data("data is:", data, data_len);
id2_test_dump_data("dec_data is:", dec_data, data_len);
#endif
ret = -1;
goto clean;
} else {
printf("test enc dec success\n");
}
clean:
if (enc_data) {
free(enc_data);
enc_data = NULL;
}
if (dec_data) {
free(dec_data);
dec_data = NULL;
}
return ret;
}
int test_sig_ver_perf(uint8_t type)
{
int ret = 0;
uint32_t data_len = 128;
uint8_t data[128];
uint32_t test_num = 100;
uint8_t ID = KEY_ID_0;
uint8_t digest[SIGN_LEN];
uint32_t digest_len = SIGN_LEN;
uint32_t i = 0;
#if CONFIG_GENERIC_LINUX
time_t start_time, end_time;
double total_time, av_time;
#else
long long yos_time1, yos_time2;
#endif
memset(data, 0x33, data_len);
#if CONFIG_GENERIC_LINUX
start_time = time(NULL);
#else
yos_time1 = aos_now_ms();
#endif
for(i = 0; i < test_num; i++) {
ret = tee_RSA_sign(ID, data, data_len, digest, &digest_len, type);
if (ret < 0) {
printf("fail to sign data!\n");
return ret;
}
}
#if CONFIG_GENERIC_LINUX
end_time = time(NULL);
total_time = difftime(end_time, start_time);
#else
yos_time2 = aos_now_ms();
total_time = ((yos_time2 - yos_time1) & 0x00000000ffffffff);
#endif
av_time = total_time / test_num;
printf("%d sign total time is %f, av_time is %f\n", type, total_time, av_time);
#if CONFIG_GENERIC_LINUX
start_time = time(NULL);
#else
yos_time1 = aos_now_ms();
#endif
for (i = 0; i < test_num; i++) {
ret = tee_RSA_verify(ID, data, data_len, digest, digest_len, type);
if (ret < 0) {
printf("fail to verify data!\n");
return ret;
}
}
#if CONFIG_GENERIC_LINUX
end_time = time(NULL);
total_time = difftime(end_time, start_time);
#else
yos_time2 = aos_now_ms();
total_time = ((yos_time2 - yos_time1) & 0x00000000ffffffff);
#endif
av_time = total_time / test_num;
printf("%d verify total time is %f, av_time is %f\n", type, total_time, av_time);
return 0;
}
int test_whole_rsa()
{
int ret = 0;
ret = test_get_id();
if (ret) {
printf("get id failed\n");
return -1;
}
ret = test_sig_ver(SM_MD5, test_data, test_data_len);
if (ret) {
printf("test MD5 sign verify failed\n");
return -1;
}
printf("test md5 sign and verify success\n");
ret = test_sig_ver(SM_SHA1, test_data, test_data_len);
if (ret) {
printf("test SHA1 sign verify failed\n");
return -1;
}
printf("test sha1 sign and verify success\n");
memset(test_data1, 0x33, test_data1_len);
#if 0
//not support yet
ret = test_enc_dec(SM_No_PADDING, test_data1, test_data1_len);
if (ret) {
printf("test no padding enc and dec failed\n");
return -1;
}
#endif
ret = test_enc_dec(SM_PKCS1_PADDING, test_data, test_data_len);
if (ret) {
printf("test pkcs1 enc and dec failed\n");
return -1;
}
return 0;
}
int id2_rsa_perf_test()
{
int ret = 0;
ret = test_sig_ver_perf(SM_MD5);
if (ret) {
printf("test md5 performance failed\n");
return ret;
}
ret = test_sig_ver_perf(SM_SHA1);
if (ret) {
printf("test sha1 performance failed\n");
return ret;
}
return ret;
}
#endif
#if ID2_MULT_SUPPORT
void * thread_content(void* argv)
{
int i = 0;
int ret = 0;
uint32_t id = 0;
printf("*** the %dth thread start ***\n", thread_id);
thread_id++;
id = thread_id;
for (i = 0; i < TEST_COUNT; i++) {
#if ID2_RSA_KEY
ret = test_whole_rsa();
#elif ID2_AES_KEY
ret = test_whole_sym();
#endif
if (ret) {
printf("%dth thread failed\n", id);
break;
}
}
printf("*** the %dth thread success ***\n", id);
return NULL;
}
int id2_fun_test()
{
int i = 0;
pthread_t thread[THREAD_NUM];
for(i = 0; i < THREAD_NUM; i++) {
pthread_create(&thread[i], NULL, thread_content, NULL);
}
for(i = 0; i < THREAD_NUM; i++) {
pthread_join(thread[i],NULL);
}
return 0;
}
inline void printf_help()
{
printf("Usage: prov_test [option]\n");
printf("-h: display helpful information.\n");
printf("-f: test function\n");
printf("-p: test performance\n");
return;
}
int id2_main(int argc, char *argv[])
{
int ret = 0;
if ((argc != 2) || (0 == strcmp(argv[1], "-h"))) {
printf_help();
return -1;
}
if (!strcmp(argv[1], "-f")) {
id2_fun_test();
} else if (!strcmp(argv[1], "-p")) {
#if ID2_RSA_KEY
ret = id2_rsa_perf_test();
#elif ID2_AES_KEY
ret = test_sym_perf();
#endif
if (ret) {
printf("id2 perf test failed\n");
return -1;
}
} else {
printf_help();
}
return 0;
}
#endif
|
edujsnogueira/Curso-Python-GG | CursoemVideoEx/ex005.py | # Exercício 5
# Faça um programa que leia um número inteiro e mostre na tela o seu sucessor e seu antecessor:
n = int(input('Digite um número inteiro:'))
print(f'O número digitado foi {n}, o seu antecessor é {n - 1} e o seu sucessor é {n + 1}.')
|
Sod-Momas/momas-project | momas-carshow/src/main/java/cc/momas/car/util/QueryCondition.java | <reponame>Sod-Momas/momas-project<gh_stars>0
package cc.momas.car.util;
public class QueryCondition {
@Override
public String toString() {
return "QueryCondition [brandId=" + brandId + ", maxPrice=" + maxPrice
+ ", minPrice=" + minPrice + ", modalId=" + modalId + "]";
}
private Integer brandId;
private Integer modalId;
private Double minPrice;
private Double maxPrice;
public Integer getBrandId() {
return brandId;
}
public Integer getModalId() {
return modalId;
}
public Double getMinPrice() {
return minPrice;
}
public Double getMaxPrice() {
return maxPrice;
}
public void setBrandId(Integer brandId) {
this.brandId = brandId;
}
public void setModalId(Integer modalId) {
this.modalId = modalId;
}
public void setMinPrice(Double minPrice) {
this.minPrice = minPrice;
}
public void setMaxPrice(Double maxPrice) {
this.maxPrice = maxPrice;
}
}
|
leozz37/makani | lib/bazel/c_rules.bzl | """This module contains rules for generating C libraries."""
# Most warnings are specified in lib/bazel/CROSSTOOL, but C-only warnings must
# be handled here. (CROSSTOOL can specify C++-only options, but not C-only.)
C_OPTS = [
"-std=c99",
"-Wmissing-prototypes",
"-Wnested-externs",
"-Wstrict-prototypes",
]
GCC_C_ONLY_WARNINGS = [
"-Wjump-misses-init",
]
DEFAULT_CC_LINKOPTS = select({
"//lib/bazel:q7_mode": ["-lstdc++"],
"//conditions:default": [],
})
# Generates a "nostatic" version of a .c file, in which "static" is stripped
# from all functions.
def nostatic_c_file(c_file):
output = "nostatic/" + c_file
native.genrule(
name = "gen_" + c_file[:-2] + "_nostatic",
srcs = [c_file],
outs = [output],
cmd = " ".join([
"PATH=/bin sed -E",
"'s/^(static inline|static) ([^=]*\()/\\2/' $< > $@",
]),
)
# Constructs the full set of copts from those specified for a particular rule.
def get_c_opts(copts_in):
return select({
"//lib/bazel:k8_gcc_mode": C_OPTS + GCC_C_ONLY_WARNINGS,
"//lib/bazel:q7_mode": C_OPTS + GCC_C_ONLY_WARNINGS,
"//conditions:default": C_OPTS,
}) + copts_in
def makani_c_library(
name,
hdrs = [],
srcs = [],
deps = [],
copts = [],
linkopts = [],
defines = [],
undefined_symbols = [],
nostatic_files = [],
**kwargs):
"""Wrapper around cc_library.
Also supports stripping of "static" from functions for use with tests. The
argument `nostatic_files` may be passed with a list of files that are
sources of this target. If nonempty, an additional target, with "_nostatic"
appended to the name, is created in which "static" is stripped from all
functions in the nostatic_files.
Args:
name: Name of the library.
hdrs: See native cc_library rule.
srcs: See native cc_library rule.
deps: See native cc_library rule. If you want to use a selector, pass in
the dict to which "select" should be applied.
copts: See native cc_library rule.
linkopts: See native cc_library rule.
defines: See native cc_library rule.
undefined_symbols: List of undefined symbols to provide to linker.
nostatic_files: List of files in the srcs attribute If nonempty, an
additional target, with "_nostatic" appended to the name, is created
in which "static" is stripped from all functions in the
nostatic_files.
**kwargs: Additional arguments to pass to the native cc_library rule.
"""
final_copts = get_c_opts(copts)
linkopts2 = linkopts + ["-Wl,--undefined=" + s for s in undefined_symbols]
# Setting linkstatic=1 tells Bazel not to consider generating a shared library
# (.so file) from this rule. Our TMS570 build is not compatible with shared
# libraries, and without this option, trying to directly build any
# makani_c_library under the TMS570 configuration (i.e. "bazel build --config
# tms570 <library_target_name>") would fail.
native.cc_library(
name = name,
hdrs = hdrs,
srcs = srcs,
defines = defines,
copts = final_copts,
deps = deps,
linkstatic = 1,
linkopts = linkopts2,
**kwargs
)
# Placing the nostatic files in a subdirectory rather than altering their
# basenames ensures that SetState() will still work in unit tests.
if nostatic_files:
nostatic_srcs = []
for s in srcs:
if s in nostatic_files:
nostatic_c_file(s)
nostatic_srcs += ["nostatic/" + s]
else:
nostatic_srcs += [s]
# Static functions typically don't have prototypes, so once they're no
# longer static, they'll trigger a missing prototype warning if we let them.
nostatic_c_opts = []
for w in C_OPTS:
if w != "-Wmissing-prototypes":
nostatic_c_opts += [w]
native.cc_library(
name = name + "_nostatic",
hdrs = hdrs,
srcs = nostatic_srcs,
deps = deps,
copts = copts + nostatic_c_opts,
defines = defines + ["MAKANI_TEST"],
linkopts = linkopts2,
**kwargs
)
def makani_c_binary(name, linkshared = 0, copts = [], archs = [], tags = [], **kwargs):
final_copts = get_c_opts(copts)
native.cc_binary(
name = name,
copts = final_copts,
linkshared = linkshared,
tags = tags + ["arch:%s" % a for a in archs],
**kwargs
)
def makani_cc_library(linkopts = [], **kwargs):
native.cc_library(
linkopts = linkopts + DEFAULT_CC_LINKOPTS,
**kwargs
)
def makani_cc_binary(
name,
linkopts = [],
linkshared = 0,
archs = [],
tags = [],
**kwargs):
native.cc_binary(
name = name,
linkopts = linkopts + DEFAULT_CC_LINKOPTS,
linkshared = linkshared,
tags = tags + ["arch:%s" % a for a in archs],
**kwargs
)
def makani_cc_test(
name,
srcs,
deps = [],
data = [],
copts = [],
linkopts = [],
size = "small",
args = [],
**kwargs):
deps2 = deps + ["@googletest//:gtest_lib"]
native.cc_test(
name = name,
srcs = srcs,
deps = deps2,
copts = copts,
linkopts = (linkopts + DEFAULT_CC_LINKOPTS),
data = data,
defines = ["MAKANI_TEST"],
size = size,
args = args,
**kwargs
)
|
FreddieDev/python-libnmap | examples/check_cpe.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from libnmap.parser import NmapParser
rep = NmapParser.parse_fromfile("libnmap/test/files/full_sudo6.xml")
print(
"Nmap scan discovered {0}/{1} hosts up".format(
rep.hosts_up, rep.hosts_total
)
)
for _host in rep.hosts:
if _host.is_up():
print(
"+ Host: {0} {1}".format(_host.address, " ".join(_host.hostnames))
)
# get CPE from service if available
for s in _host.services:
print(
" Service: {0}/{1} ({2})".format(
s.port, s.protocol, s.state
)
)
# NmapService.cpelist returns an array of CPE objects
for _serv_cpe in s.cpelist:
print(" CPE: {0}".format(_serv_cpe.cpestring))
if _host.os_fingerprinted:
print(" OS Fingerprints")
for osm in _host.os.osmatches:
print(
" Found Match:{0} ({1}%)".format(osm.name, osm.accuracy)
)
# NmapOSMatch.get_cpe() method return an array of string
# unlike NmapOSClass.cpelist which returns an array of CPE obj
for cpe in osm.get_cpe():
print("\t CPE: {0}".format(cpe))
|
marcusportmann/mmp-java | src/mmp-application-kafka/src/main/java/guru/mmp/avro/event/Event.java | /**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package guru.mmp.avro.event;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.message.BinaryMessageEncoder;
import org.apache.avro.message.BinaryMessageDecoder;
import org.apache.avro.message.SchemaStore;
@SuppressWarnings("all")
@org.apache.avro.specific.AvroGenerated
public class Event extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
private static final long serialVersionUID = -4294383026456084232L;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"Event\",\"namespace\":\"guru.mmp.avro.event\",\"fields\":[{\"name\":\"id\",\"type\":\"string\"},{\"name\":\"type\",\"type\":\"string\"},{\"name\":\"version\",\"type\":\"int\"},{\"name\":\"reference\",\"type\":[\"string\",\"null\"]},{\"name\":\"system\",\"type\":\"string\"},{\"name\":\"timestamp\",\"type\":\"long\"},{\"name\":\"data\",\"type\":\"bytes\"}]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
private static SpecificData MODEL$ = new SpecificData();
private static final BinaryMessageEncoder<Event> ENCODER =
new BinaryMessageEncoder<Event>(MODEL$, SCHEMA$);
private static final BinaryMessageDecoder<Event> DECODER =
new BinaryMessageDecoder<Event>(MODEL$, SCHEMA$);
/**
* Return the BinaryMessageDecoder instance used by this class.
*/
public static BinaryMessageDecoder<Event> getDecoder() {
return DECODER;
}
/**
* Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}.
* @param resolver a {@link SchemaStore} used to find schemas by fingerprint
*/
public static BinaryMessageDecoder<Event> createDecoder(SchemaStore resolver) {
return new BinaryMessageDecoder<Event>(MODEL$, SCHEMA$, resolver);
}
/** Serializes this Event to a ByteBuffer. */
public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
return ENCODER.encode(this);
}
/** Deserializes a Event from a ByteBuffer. */
public static Event fromByteBuffer(
java.nio.ByteBuffer b) throws java.io.IOException {
return DECODER.decode(b);
}
@Deprecated public java.lang.CharSequence id;
@Deprecated public java.lang.CharSequence type;
@Deprecated public int version;
@Deprecated public java.lang.CharSequence reference;
@Deprecated public java.lang.CharSequence system;
@Deprecated public long timestamp;
@Deprecated public java.nio.ByteBuffer data;
/**
* Default constructor. Note that this does not initialize fields
* to their default values from the schema. If that is desired then
* one should use <code>newBuilder()</code>.
*/
public Event() {}
/**
* All-args constructor.
* @param id The new value for id
* @param type The new value for type
* @param version The new value for version
* @param reference The new value for reference
* @param system The new value for system
* @param timestamp The new value for timestamp
* @param data The new value for data
*/
public Event(java.lang.CharSequence id, java.lang.CharSequence type, java.lang.Integer version, java.lang.CharSequence reference, java.lang.CharSequence system, java.lang.Long timestamp, java.nio.ByteBuffer data) {
this.id = id;
this.type = type;
this.version = version;
this.reference = reference;
this.system = system;
this.timestamp = timestamp;
this.data = data;
}
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
public java.lang.Object get(int field$) {
switch (field$) {
case 0: return id;
case 1: return type;
case 2: return version;
case 3: return reference;
case 4: return system;
case 5: return timestamp;
case 6: return data;
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
}
}
// Used by DatumReader. Applications should not call.
@SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value$) {
switch (field$) {
case 0: id = (java.lang.CharSequence)value$; break;
case 1: type = (java.lang.CharSequence)value$; break;
case 2: version = (java.lang.Integer)value$; break;
case 3: reference = (java.lang.CharSequence)value$; break;
case 4: system = (java.lang.CharSequence)value$; break;
case 5: timestamp = (java.lang.Long)value$; break;
case 6: data = (java.nio.ByteBuffer)value$; break;
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
}
}
/**
* Gets the value of the 'id' field.
* @return The value of the 'id' field.
*/
public java.lang.CharSequence getId() {
return id;
}
/**
* Sets the value of the 'id' field.
* @param value the value to set.
*/
public void setId(java.lang.CharSequence value) {
this.id = value;
}
/**
* Gets the value of the 'type' field.
* @return The value of the 'type' field.
*/
public java.lang.CharSequence getType() {
return type;
}
/**
* Sets the value of the 'type' field.
* @param value the value to set.
*/
public void setType(java.lang.CharSequence value) {
this.type = value;
}
/**
* Gets the value of the 'version' field.
* @return The value of the 'version' field.
*/
public java.lang.Integer getVersion() {
return version;
}
/**
* Sets the value of the 'version' field.
* @param value the value to set.
*/
public void setVersion(java.lang.Integer value) {
this.version = value;
}
/**
* Gets the value of the 'reference' field.
* @return The value of the 'reference' field.
*/
public java.lang.CharSequence getReference() {
return reference;
}
/**
* Sets the value of the 'reference' field.
* @param value the value to set.
*/
public void setReference(java.lang.CharSequence value) {
this.reference = value;
}
/**
* Gets the value of the 'system' field.
* @return The value of the 'system' field.
*/
public java.lang.CharSequence getSystem() {
return system;
}
/**
* Sets the value of the 'system' field.
* @param value the value to set.
*/
public void setSystem(java.lang.CharSequence value) {
this.system = value;
}
/**
* Gets the value of the 'timestamp' field.
* @return The value of the 'timestamp' field.
*/
public java.lang.Long getTimestamp() {
return timestamp;
}
/**
* Sets the value of the 'timestamp' field.
* @param value the value to set.
*/
public void setTimestamp(java.lang.Long value) {
this.timestamp = value;
}
/**
* Gets the value of the 'data' field.
* @return The value of the 'data' field.
*/
public java.nio.ByteBuffer getData() {
return data;
}
/**
* Sets the value of the 'data' field.
* @param value the value to set.
*/
public void setData(java.nio.ByteBuffer value) {
this.data = value;
}
/**
* Creates a new Event RecordBuilder.
* @return A new Event RecordBuilder
*/
public static guru.mmp.avro.event.Event.Builder newBuilder() {
return new guru.mmp.avro.event.Event.Builder();
}
/**
* Creates a new Event RecordBuilder by copying an existing Builder.
* @param other The existing builder to copy.
* @return A new Event RecordBuilder
*/
public static guru.mmp.avro.event.Event.Builder newBuilder(guru.mmp.avro.event.Event.Builder other) {
return new guru.mmp.avro.event.Event.Builder(other);
}
/**
* Creates a new Event RecordBuilder by copying an existing Event instance.
* @param other The existing instance to copy.
* @return A new Event RecordBuilder
*/
public static guru.mmp.avro.event.Event.Builder newBuilder(guru.mmp.avro.event.Event other) {
return new guru.mmp.avro.event.Event.Builder(other);
}
/**
* RecordBuilder for Event instances.
*/
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<Event>
implements org.apache.avro.data.RecordBuilder<Event> {
private java.lang.CharSequence id;
private java.lang.CharSequence type;
private int version;
private java.lang.CharSequence reference;
private java.lang.CharSequence system;
private long timestamp;
private java.nio.ByteBuffer data;
/** Creates a new Builder */
private Builder() {
super(SCHEMA$);
}
/**
* Creates a Builder by copying an existing Builder.
* @param other The existing Builder to copy.
*/
private Builder(guru.mmp.avro.event.Event.Builder other) {
super(other);
if (isValidValue(fields()[0], other.id)) {
this.id = data().deepCopy(fields()[0].schema(), other.id);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.type)) {
this.type = data().deepCopy(fields()[1].schema(), other.type);
fieldSetFlags()[1] = true;
}
if (isValidValue(fields()[2], other.version)) {
this.version = data().deepCopy(fields()[2].schema(), other.version);
fieldSetFlags()[2] = true;
}
if (isValidValue(fields()[3], other.reference)) {
this.reference = data().deepCopy(fields()[3].schema(), other.reference);
fieldSetFlags()[3] = true;
}
if (isValidValue(fields()[4], other.system)) {
this.system = data().deepCopy(fields()[4].schema(), other.system);
fieldSetFlags()[4] = true;
}
if (isValidValue(fields()[5], other.timestamp)) {
this.timestamp = data().deepCopy(fields()[5].schema(), other.timestamp);
fieldSetFlags()[5] = true;
}
if (isValidValue(fields()[6], other.data)) {
this.data = data().deepCopy(fields()[6].schema(), other.data);
fieldSetFlags()[6] = true;
}
}
/**
* Creates a Builder by copying an existing Event instance
* @param other The existing instance to copy.
*/
private Builder(guru.mmp.avro.event.Event other) {
super(SCHEMA$);
if (isValidValue(fields()[0], other.id)) {
this.id = data().deepCopy(fields()[0].schema(), other.id);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.type)) {
this.type = data().deepCopy(fields()[1].schema(), other.type);
fieldSetFlags()[1] = true;
}
if (isValidValue(fields()[2], other.version)) {
this.version = data().deepCopy(fields()[2].schema(), other.version);
fieldSetFlags()[2] = true;
}
if (isValidValue(fields()[3], other.reference)) {
this.reference = data().deepCopy(fields()[3].schema(), other.reference);
fieldSetFlags()[3] = true;
}
if (isValidValue(fields()[4], other.system)) {
this.system = data().deepCopy(fields()[4].schema(), other.system);
fieldSetFlags()[4] = true;
}
if (isValidValue(fields()[5], other.timestamp)) {
this.timestamp = data().deepCopy(fields()[5].schema(), other.timestamp);
fieldSetFlags()[5] = true;
}
if (isValidValue(fields()[6], other.data)) {
this.data = data().deepCopy(fields()[6].schema(), other.data);
fieldSetFlags()[6] = true;
}
}
/**
* Gets the value of the 'id' field.
* @return The value.
*/
public java.lang.CharSequence getId() {
return id;
}
/**
* Sets the value of the 'id' field.
* @param value The value of 'id'.
* @return This builder.
*/
public guru.mmp.avro.event.Event.Builder setId(java.lang.CharSequence value) {
validate(fields()[0], value);
this.id = value;
fieldSetFlags()[0] = true;
return this;
}
/**
* Checks whether the 'id' field has been set.
* @return True if the 'id' field has been set, false otherwise.
*/
public boolean hasId() {
return fieldSetFlags()[0];
}
/**
* Clears the value of the 'id' field.
* @return This builder.
*/
public guru.mmp.avro.event.Event.Builder clearId() {
id = null;
fieldSetFlags()[0] = false;
return this;
}
/**
* Gets the value of the 'type' field.
* @return The value.
*/
public java.lang.CharSequence getType() {
return type;
}
/**
* Sets the value of the 'type' field.
* @param value The value of 'type'.
* @return This builder.
*/
public guru.mmp.avro.event.Event.Builder setType(java.lang.CharSequence value) {
validate(fields()[1], value);
this.type = value;
fieldSetFlags()[1] = true;
return this;
}
/**
* Checks whether the 'type' field has been set.
* @return True if the 'type' field has been set, false otherwise.
*/
public boolean hasType() {
return fieldSetFlags()[1];
}
/**
* Clears the value of the 'type' field.
* @return This builder.
*/
public guru.mmp.avro.event.Event.Builder clearType() {
type = null;
fieldSetFlags()[1] = false;
return this;
}
/**
* Gets the value of the 'version' field.
* @return The value.
*/
public java.lang.Integer getVersion() {
return version;
}
/**
* Sets the value of the 'version' field.
* @param value The value of 'version'.
* @return This builder.
*/
public guru.mmp.avro.event.Event.Builder setVersion(int value) {
validate(fields()[2], value);
this.version = value;
fieldSetFlags()[2] = true;
return this;
}
/**
* Checks whether the 'version' field has been set.
* @return True if the 'version' field has been set, false otherwise.
*/
public boolean hasVersion() {
return fieldSetFlags()[2];
}
/**
* Clears the value of the 'version' field.
* @return This builder.
*/
public guru.mmp.avro.event.Event.Builder clearVersion() {
fieldSetFlags()[2] = false;
return this;
}
/**
* Gets the value of the 'reference' field.
* @return The value.
*/
public java.lang.CharSequence getReference() {
return reference;
}
/**
* Sets the value of the 'reference' field.
* @param value The value of 'reference'.
* @return This builder.
*/
public guru.mmp.avro.event.Event.Builder setReference(java.lang.CharSequence value) {
validate(fields()[3], value);
this.reference = value;
fieldSetFlags()[3] = true;
return this;
}
/**
* Checks whether the 'reference' field has been set.
* @return True if the 'reference' field has been set, false otherwise.
*/
public boolean hasReference() {
return fieldSetFlags()[3];
}
/**
* Clears the value of the 'reference' field.
* @return This builder.
*/
public guru.mmp.avro.event.Event.Builder clearReference() {
reference = null;
fieldSetFlags()[3] = false;
return this;
}
/**
* Gets the value of the 'system' field.
* @return The value.
*/
public java.lang.CharSequence getSystem() {
return system;
}
/**
* Sets the value of the 'system' field.
* @param value The value of 'system'.
* @return This builder.
*/
public guru.mmp.avro.event.Event.Builder setSystem(java.lang.CharSequence value) {
validate(fields()[4], value);
this.system = value;
fieldSetFlags()[4] = true;
return this;
}
/**
* Checks whether the 'system' field has been set.
* @return True if the 'system' field has been set, false otherwise.
*/
public boolean hasSystem() {
return fieldSetFlags()[4];
}
/**
* Clears the value of the 'system' field.
* @return This builder.
*/
public guru.mmp.avro.event.Event.Builder clearSystem() {
system = null;
fieldSetFlags()[4] = false;
return this;
}
/**
* Gets the value of the 'timestamp' field.
* @return The value.
*/
public java.lang.Long getTimestamp() {
return timestamp;
}
/**
* Sets the value of the 'timestamp' field.
* @param value The value of 'timestamp'.
* @return This builder.
*/
public guru.mmp.avro.event.Event.Builder setTimestamp(long value) {
validate(fields()[5], value);
this.timestamp = value;
fieldSetFlags()[5] = true;
return this;
}
/**
* Checks whether the 'timestamp' field has been set.
* @return True if the 'timestamp' field has been set, false otherwise.
*/
public boolean hasTimestamp() {
return fieldSetFlags()[5];
}
/**
* Clears the value of the 'timestamp' field.
* @return This builder.
*/
public guru.mmp.avro.event.Event.Builder clearTimestamp() {
fieldSetFlags()[5] = false;
return this;
}
/**
* Gets the value of the 'data' field.
* @return The value.
*/
public java.nio.ByteBuffer getData() {
return data;
}
/**
* Sets the value of the 'data' field.
* @param value The value of 'data'.
* @return This builder.
*/
public guru.mmp.avro.event.Event.Builder setData(java.nio.ByteBuffer value) {
validate(fields()[6], value);
this.data = value;
fieldSetFlags()[6] = true;
return this;
}
/**
* Checks whether the 'data' field has been set.
* @return True if the 'data' field has been set, false otherwise.
*/
public boolean hasData() {
return fieldSetFlags()[6];
}
/**
* Clears the value of the 'data' field.
* @return This builder.
*/
public guru.mmp.avro.event.Event.Builder clearData() {
data = null;
fieldSetFlags()[6] = false;
return this;
}
@Override
@SuppressWarnings("unchecked")
public Event build() {
try {
Event record = new Event();
record.id = fieldSetFlags()[0] ? this.id : (java.lang.CharSequence) defaultValue(fields()[0]);
record.type = fieldSetFlags()[1] ? this.type : (java.lang.CharSequence) defaultValue(fields()[1]);
record.version = fieldSetFlags()[2] ? this.version : (java.lang.Integer) defaultValue(fields()[2]);
record.reference = fieldSetFlags()[3] ? this.reference : (java.lang.CharSequence) defaultValue(fields()[3]);
record.system = fieldSetFlags()[4] ? this.system : (java.lang.CharSequence) defaultValue(fields()[4]);
record.timestamp = fieldSetFlags()[5] ? this.timestamp : (java.lang.Long) defaultValue(fields()[5]);
record.data = fieldSetFlags()[6] ? this.data : (java.nio.ByteBuffer) defaultValue(fields()[6]);
return record;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumWriter<Event>
WRITER$ = (org.apache.avro.io.DatumWriter<Event>)MODEL$.createDatumWriter(SCHEMA$);
@Override public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumReader<Event>
READER$ = (org.apache.avro.io.DatumReader<Event>)MODEL$.createDatumReader(SCHEMA$);
@Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
}
|
mengyangbai/leetcode | game/jumpgame.py | <reponame>mengyangbai/leetcode
class Solution:
def jump(self, nums: [int]) -> int:
if len(nums) == 1:
return 0
steps, limit, next_step = 0,0,0
for i in range(len(nums)):
next_step = max(next_step,i+nums[i])
if i == limit:
steps+=1
limit = next_step
if limit >= len(nums) - 1:
return steps
return steps
class BestSolution:
def jump(self, nums: [int]) -> int:
length = len(nums)
target = length-1
steps, far, i = 0, target, target
if nums.count(1) == length: # all 1's = steping
return length - 1
while i > 0: # moving cursor from target back to 0
for j in range(0, i+1):
# find the farthest one step that can reach target
# scan until position 0
if j+nums[j] >= i:
far = j # the first j fulfills this is the farthest
break
steps += 1
i = far
return steps |
hxcorp/DongTai-agent-java | dongtai-agent/src/main/java/io/dongtai/iast/agent/monitor/collector/impl/MemUsageCollector.java | <filename>dongtai-agent/src/main/java/io/dongtai/iast/agent/monitor/collector/impl/MemUsageCollector.java
package io.dongtai.iast.agent.monitor.collector.impl;
import io.dongtai.iast.common.entity.performance.PerformanceMetrics;
import io.dongtai.iast.common.entity.performance.metrics.MemoryUsageMetrics;
import io.dongtai.iast.common.enums.MetricsKey;
import java.lang.management.ManagementFactory;
/**
* 堆内存使用率收集器
*
* @author chenyi
* @date 2022/2/28
*/
public class MemUsageCollector extends AbstractPerformanceCollector {
@Override
public PerformanceMetrics getMetrics() {
MemoryUsageMetrics metricsValue = MemoryUsageMetrics.clone(ManagementFactory.getMemoryMXBean().getHeapMemoryUsage());
return buildMetricsData(MetricsKey.MEM_USAGE, metricsValue);
}
}
|
DevulTj/DayZOfflineMode | SourceCode/scripts/3_Game/Systems/Inventory/Cargo.c | /**@class Cargo
* @brief represents grid like storage for entities
**/
class Cargo : Managed
{
/// width of the cargo
proto native int GetWidth ();
/// height of the cargo
proto native int GetHeight ();
/// number of items in cargo
proto native int GetItemCount ();
/// get item at specific index
proto native EntityAI GetItem (int index);
/// get item at coordinates (row, col)
proto native EntityAI FindEntityInCargoOn (int row, int col);
/// return index of item in cargo (or -1 if not found)
proto native int FindEntityInCargo (EntityAI e);
proto native bool CanMoveEntityInCargoEx (EntityAI e, int row, int col); /// can move from current location in cargo to new one
proto native bool CanSwapEntityInCargo (EntityAI oldItem, EntityAI newItem);
/// get cargo owning entity
proto native EntityAI GetParent ();
proto void GetItemSize (int index, out int w, out int h);
proto void GetItemPos (int index, out int x, out int y);
private void Cargo();
private void ~Cargo();
};
|
pascalberger/breeze.js.samples | net/ngNorthwind/src/client/app/customers/customerDataservice.js | (function () {
'use strict';
angular
.module('app.core')
.service('customerDataservice', CustomerDataservice);
CustomerDataservice.$inject = ['$injector', 'config'];
/* @ngInject */
function CustomerDataservice($injector, config) {
var ds = config.useBreeze ? 'customerDataservice-bz' : 'customerDataservice-mem';
return $injector.get(ds);
}
})(); |
morrismukiri/uwazi | app/react/Forms/components/MultiDate.js | <gh_stars>0
import PropTypes from 'prop-types';
import React, {Component} from 'react';
import DatePicker from './DatePicker';
export default class MultiDate extends Component {
constructor(props) {
super(props);
let values = this.props.value && this.props.value.length ? this.props.value : [null];
this.state = {values};
}
onChange(index, value) {
let values = this.state.values.slice();
values[index] = value;
this.setState({values});
this.props.onChange(values);
}
add(e) {
e.preventDefault();
let values = this.state.values.slice();
values.push(null);
this.setState({values});
}
remove(index, e) {
e.preventDefault();
let values = this.state.values.slice();
values.splice(index, 1);
this.setState({values});
this.props.onChange(values);
}
render() {
return <div className="multidate">
{(() => {
return this.state.values.map((value, index) => {
return <div key={index} className="multidate-item">
<DatePicker locale={this.props.locale} format={this.props.format} onChange={this.onChange.bind(this, index)} value={value}/>
<button className="react-datepicker__delete-icon" onClick={this.remove.bind(this, index)}></button>
</div>;
});
})()}
<button className="btn btn-success add" onClick={this.add.bind(this)}>
<i className="fa fa-plus"></i>
<span>Add date</span>
</button>
</div>;
}
}
MultiDate.propTypes = {
value: PropTypes.array,
onChange: PropTypes.func,
locale: PropTypes.string,
format: PropTypes.string
};
|
SummaLabs/DLS | app/backend/core/dataset/input.py | <filename>app/backend/core/dataset/input.py<gh_stars>10-100
from itertools import islice
import csv, sys
import copy
import abc
import numpy as np
import json
import os
class Schema(object):
def __init__(self, columns, csv_file_path=None, train_csv_file_path=None, validation_scv_file_path=None, header=False, delimiter=','):
self._columns = columns
self._csv_file_path = csv_file_path
self._train_csv_file_path = train_csv_file_path
self._validation_scv_file_path = validation_scv_file_path
self._header = header
self._delimiter = delimiter
@classmethod
def from_csv(cls, csv_path, test_size=70, header=False, delimiter=','):
columns = cls._build_from_csv(csv_file_path=csv_path, header=header, delimiter=delimiter)
return Schema(columns=columns, csv_file_path=csv_path, header=header, delimiter=delimiter)
@classmethod
def from_train_and_test_csv(cls, train_csv_path, validation_scv_file_path, header=False, delimiter=','):
train_csv_columns = cls._build_from_csv(csv_file_path=train_csv_path, header=header, delimiter=delimiter)
test_scv_columns = cls._build_from_csv(csv_file_path=validation_scv_file_path, header=header, delimiter=delimiter)
if not (len(train_csv_columns) == len(test_scv_columns)):
raise Exception('Train and test file has different columns number')
for idx, column in enumerate(train_csv_columns):
if column.name != test_scv_columns[idx].name:
raise Exception('Column names or order in train and test datasets are not equals')
return Schema(columns=train_csv_columns, train_csv_file_path=train_csv_path, validation_scv_file_path=validation_scv_file_path, header=header, delimiter=delimiter)
@classmethod
def _build_from_csv(cls, csv_file_path, header, delimiter):
delimiter = delimiter.strip()
if len(delimiter) < 0 or len(delimiter) > 1:
raise Exception('Invalid delimiter [%s]' % delimiter)
header_row = [col.strip() for col in cls.read_n_rows(csv_file_path, delimiter, 1)[0]]
if header:
duplicates = set([x for x in header_row if header_row.count(x) > 1])
if len(duplicates) > 0:
raise Exception("Should be no duplicates in CSV header: " + ", ".join([col for col in duplicates]))
columns = [Column(name=item, columns_indexes=[index]) for index, item in enumerate(header_row)]
else:
columns = [Column(name='col_' + str(index), columns_indexes=[index]) for index in range(0, len(header_row))]
return columns
@classmethod
def read_n_rows(cls, csv_file_path, delimiter, rows_number):
rows = []
with open(csv_file_path, 'rb') as f:
reader = csv.reader(f, delimiter=str(delimiter))
try:
for row in islice(reader, 0, rows_number):
row = [e.strip() for e in row]
rows.append(row)
except csv.Error as e:
sys.exit('Broken line: file %s, line %d: %s' % (csv_file_path, reader.line_num, e))
return rows
def __setitem__(self, old_name, new_name):
columns = [c.name for c in self._columns]
if old_name != new_name and columns.count(new_name) > 0:
raise Exception("Should be no duplicates in columns: " + new_name)
for column in self._columns:
if column.name == old_name:
column.name = new_name.strip()
@property
def csv_file_path(self):
return self._csv_file_path
@property
def train_csv_file_path(self):
return self._train_csv_file_path
@property
def validation_scv_file_path(self):
return self._validation_scv_file_path
@property
def header(self):
return self._header
@property
def delimiter(self):
return self._delimiter
@property
def columns(self):
return self._columns
def update_columns(self, columns):
self._columns = columns
@columns.setter
def columns(self, columns):
l = len(columns)
if (l > len(self._columns)) or (l < len(self._columns)):
raise Exception("Passed columns number: %d is not compatible with Schema current columns number: %d"
% (l, len(self._columns)))
duplicates = set([x for x in columns if columns.count(x) > 1])
if len(duplicates) > 0:
raise Exception("Should be no duplicates in columns: " + ", ".join([col for col in duplicates]))
for index, item in enumerate(columns):
self._columns[index].name = item.strip()
def drop_column(self, column_name):
for index, column in enumerate(copy.deepcopy(self._columns)):
if column.name == column_name:
self._columns.remove(self._columns[index])
def merge_columns(self, new_column_name, columns_to_merge):
if not isinstance(columns_to_merge, list):
raise TypeError("Arg columns_to_merge should be list")
columns_indexes = []
for column in copy.deepcopy(self._columns):
if column.name in columns_to_merge:
columns_indexes.extend(column.columns_indexes)
self.drop_column(column.name)
self._columns.append(Column(new_column_name, columns_indexes))
def merge_columns_in_range(self, new_column_name, range=()):
if not isinstance(range, tuple):
raise TypeError("Arg range should be Tuple")
if range[0] >= range[1]:
raise Exception("Start index of the range can't be higher or equal than end index")
if range[0] < 0 or range[1] >= len(self._columns):
raise Exception("Range is out of length of schema, last schema index: %d" % (len(self._columns) - 1))
columns_indexes = []
for index, column in enumerate(copy.deepcopy(self._columns)):
if range[0] <= index <= range[1]:
columns_indexes.extend(column.columns_indexes)
self.drop_column(column.name)
self._columns.append(Column(new_column_name, columns_indexes))
def print_columns(self):
print ", ".join([col.name for col in self._columns])
def print_data(self):
print "First 10 records:"
csv_file_path = self.csv_file_path if self._csv_file_path is not None else self._train_csv_file_path
for index, row in enumerate(self.read_n_rows(csv_file_path, self._delimiter, 10)):
if not (index == 0 and self.header == True):
print row
class Input(object):
def __init__(self, schema=None):
if schema is not None:
if not isinstance(schema, Schema):
raise TypeError("Pass Schema instance as an argument")
else:
self._input_schema = schema
self._csv_file_path = schema.csv_file_path
self._train_csv_file_path = schema.train_csv_file_path
self._validation_scv_file_path = schema.validation_scv_file_path
self._header = schema.header
self._delimiter = schema.delimiter
self._delimiter = schema.delimiter
self._columns = []
@property
def csv_file_path(self):
return self._csv_file_path
@csv_file_path.setter
def csv_file_path(self, csv_file_path):
self._csv_file_path = csv_file_path
@property
def train_csv_file_path(self):
return self._train_csv_file_path
@train_csv_file_path.setter
def train_csv_file_path(self, train_csv_file_path):
self._train_csv_file_path = train_csv_file_path
@property
def validation_scv_file_path(self):
return self._validation_scv_file_path
@validation_scv_file_path.setter
def validation_scv_file_path(self, validation_scv_file_path):
self._validation_scv_file_path = validation_scv_file_path
@property
def header(self):
return self._header
@header.setter
def header(self, header):
self._header = header
@property
def delimiter(self):
return self._delimiter
@delimiter.setter
def delimiter(self, delimiter):
self._delimiter = delimiter
@property
def columns(self):
return self._columns
@columns.setter
def columns(self, columns):
self._columns = columns
def add_numeric_column(self, column_name):
index, column = self._find_column_in_schema(column_name)
self.columns.append(NumericColumn.from_column(column))
def add_categorical_column(self, column_name):
index, column = self._find_column_in_schema(column_name)
self.columns.append(CategoricalColumn.from_column(column))
def add_vector_column(self, column_name):
index, column = self._find_column_in_schema(column_name)
self.columns.append(VectorColumn.from_column(column))
def add_column(self, column_name, input_column):
index, column = self._find_column_in_schema(column_name)
input_column.csv_file_path(os.path.dirname(self.csv_file_path))
input_column.name = column_name
input_column.columns_indexes = column.columns_indexes
self.columns.append(input_column)
def _find_column_in_schema(self, column_name):
for index, schema_column in enumerate(self._input_schema.columns):
if schema_column.name == column_name:
return index, schema_column
raise Exception("No column with name %s in schema." % column_name)
@classmethod
def from_schema(dls, schema):
input = Input()
if 'csv_file_path' in schema:
input.csv_file_path = schema['csv_file_path']
if 'train_csv_file_path' in schema:
input.train_csv_file_path = schema['train_csv_file_path']
if 'validation_scv_file_path' in schema:
input.validation_scv_file_path = schema['validation_scv_file_path']
if 'header' in schema:
input.header = schema['header']
if 'delimiter' in schema:
input.delimiter = str(schema['delimiter'])
from img2d import Img2DColumn
columns = []
for column_schema in schema['columns']:
column_type = str(column_schema['type'])
if column_type == Column.Type.NUMERIC:
columns.append(NumericColumn.from_schema(column_schema))
elif column_type == Column.Type.VECTOR:
columns.append(VectorColumn.from_schema(column_schema))
elif column_type == Column.Type.CATEGORICAL:
columns.append(CategoricalColumn.from_schema(column_schema))
elif column_type == Column.Type.IMG_2D:
img2d = Img2DColumn.from_schema(column_schema)
if hasattr(input, 'csv_file_path'):
img2d.csv_file_path(os.path.dirname(input.csv_file_path))
else:
img2d.csv_file_path(os.path.dirname(input.train_csv_file_path))
columns.append(img2d)
else:
raise TypeError("Unsupported column type: %s" % column_type)
input.columns = columns
return input
def serialize(self):
return {'columns': [column.schema for column in self._columns]}
class Column(object):
def __init__(self, name=None, columns_indexes=None, type=None, reader=None, ser_de=None, metadata=None, shape=None):
if not (name is None or isinstance(name, str)):
raise Exception("Name field should be string.")
if not (columns_indexes is None or isinstance(columns_indexes, list)):
raise Exception("Columns indexes field should be list.")
if not (type is None or isinstance(type, str)):
raise Exception("Type field should be string.")
self._name = name
# CSV corresponding columns indexes
self._columns_indexes = columns_indexes
self._type = type
self._reader = reader
self._ser_de = ser_de
self._metadata = metadata
self._shape = None
class Type:
NUMERIC = "NUMERIC"
VECTOR = "VECTOR"
CATEGORICAL = "CATEGORICAL"
IMG_2D = 'IMG_2D'
IMG_3D = 'IMG_3D'
@property
def shape(self):
return self._shape
@shape.setter
def shape(self, shape):
self._shape = shape
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
@property
def columns_indexes(self):
return self._columns_indexes
@columns_indexes.setter
def columns_indexes(self, columns_indexes):
self._columns_indexes = columns_indexes
@property
def type(self):
return self._type
@type.setter
def type(self, type):
self._type = type
@property
def reader(self):
return self._reader
@reader.setter
def reader(self, reader):
self._reader = reader
@property
def ser_de(self):
return self._ser_de
@ser_de.setter
def ser_de(self, ser_de):
self._ser_de = ser_de
@property
def metadata(self):
return self._metadata
@metadata.setter
def metadata(self, metadata):
self._metadata = metadata
@classmethod
def from_column(cls, column):
return globals()[cls.__name__](column.name, column.columns_indexes)
@property
def schema(self):
schema = {'name': self.name, 'type': self.type}
if self._metadata is not None:
schema['metadata'] = self._metadata.serialize()
return schema
def process_on_write(self, record):
data = self.reader.read(record)
return self.ser_de.serialize(data)
def process_on_read(self, record):
return self._ser_de.deserialize(record[self._name])
class ComplexColumn(Column):
def __init__(self, name=None, type=None, columns_indexes=None, ser_de=None, reader=None, metadata=None,
pre_transforms=[], post_transforms=[]):
if not (pre_transforms is None or isinstance(pre_transforms, list)):
raise Exception("pre_transforms field should be list.")
if not (post_transforms is None or isinstance(post_transforms, list)):
raise Exception("post_transforms field should be list.")
super(ComplexColumn, self).__init__(name=name, type=type, columns_indexes=columns_indexes, ser_de=ser_de,
reader=reader, metadata=metadata)
self._pre_transforms = pre_transforms
self._post_transforms = post_transforms
@property
def pre_transforms(self):
return self._pre_transforms
@pre_transforms.setter
def pre_transforms(self, pre_transforms):
self._pre_transforms = pre_transforms
@property
def post_transforms(self):
return self._post_transforms
@post_transforms.setter
def post_transforms(self, post_transforms):
self._post_transforms = post_transforms
@property
def schema(self):
schema = super(ComplexColumn, self).schema
pre_transforms = []
for transform in self.pre_transforms:
pre_transforms.append(transform.schema)
schema['pre_transforms'] = pre_transforms
post_transforms = []
for transform in self.post_transforms:
post_transforms.append(transform.schema)
schema['post_transforms'] = post_transforms
return schema
def process_on_write(self, record):
data = self.reader.read(record)
if self._metadata is not None:
self._metadata.aggregate(data)
for transform in self._pre_transforms:
data = transform.apply(data)
return self.ser_de.serialize(data)
def process_on_read(self, record):
value = self._ser_de.deserialize(record[self._name])
for transform in self._post_transforms:
value = transform.apply(value)
return value
class ColumnTransform(object):
def __init__(self):
pass
@staticmethod
def type():
pass
def apply(self, data):
pass
@property
@abc.abstractmethod
def serialize(self):
pass
class ColumnReader(object):
def __init__(self, column):
self._column = column
@abc.abstractmethod
def read(self, csv_row):
pass
class ColumnSerDe(object):
@abc.abstractmethod
def serialize(self, data):
pass
@abc.abstractmethod
def deserialize(self, data):
pass
class ColumnMetadata(object):
def aggregate(self, data):
pass
def path(self, path):
# Path to save metadata if required
pass
def serialize(self):
pass
@classmethod
def deserialize(cls, schema):
pass
def merge(self, metadata):
pass
class NumericColumn(Column):
def __init__(self, name=None, columns_indexes=None):
super(NumericColumn, self).__init__(name, columns_indexes, Column.Type.NUMERIC,
NumericColumn.Reader(self), NumericColumn.SerDe(self))
@classmethod
def from_schema(cls, column_schema):
name = str(column_schema['name'])
index = None
if 'index' in column_schema:
index = column_schema['index']
return NumericColumn(name=name, columns_indexes=index)
class Reader(ColumnReader):
def read(self, csv_row):
return csv_row[self._column.columns_indexes[0]]
class SerDe(ColumnSerDe):
def __init__(self, column):
self._column = column
def serialize(self, data):
return float(data)
def deserialize(self, data):
return float(data)
class VectorColumn(Column):
def __init__(self, name=None, columns_indexes=None):
super(VectorColumn, self).__init__(name, columns_indexes, Column.Type.VECTOR,
VectorColumn.Reader(self), VectorColumn.SerDe(self))
@classmethod
def from_schema(cls, column_schema):
name = str(column_schema['name'])
index = None
if 'index' in column_schema:
index = column_schema['index']
return VectorColumn(name=name, columns_indexes=index)
class Reader(ColumnReader):
def read(self, csv_row):
return [float(csv_row[i]) for i in self._column.columns_indexes]
class SerDe(ColumnSerDe):
def __init__(self, column):
self._column = column
def serialize(self, data):
return np.array(data).tostring()
def deserialize(self, data):
return np.frombuffer(data, dtype=np.float64)
class CategoricalColumn(Column):
def __init__(self, name=None, columns_indexes=None, metadata=None):
super(CategoricalColumn, self).__init__(name=name,
columns_indexes=columns_indexes,
type=Column.Type.CATEGORICAL,
reader=CategoricalColumn.Reader(self),
ser_de=CategoricalColumn.SerDe(self),
metadata=metadata)
if self._metadata is None:
self._metadata = CategoricalColumnMetadata()
@property
def schema(self):
schema = super(CategoricalColumn, self).schema
schema['metadata'] = self.metadata.serialize()
return schema
@classmethod
def from_schema(cls, column_schema):
name = str(column_schema['name'])
index = None
if 'index' in column_schema:
index = column_schema['index']
if 'metadata' in column_schema:
metadata = CategoricalColumnMetadata.deserialize(column_schema['metadata'])
else:
metadata = None
return CategoricalColumn(name=name, columns_indexes=index, metadata=metadata)
class Reader(ColumnReader):
def read(self, csv_row):
cat_val = csv_row[self._column.columns_indexes[0]]
return self._column.metadata.categories.index(cat_val)
class SerDe(ColumnSerDe):
def __init__(self, column):
self._column = column
def serialize(self, data):
return int(data)
def deserialize(self, data):
#FIXME: performance degradation is possible
cat_val = int(data)
cat_num = len(self._column.metadata.categories)
ret = np.zeros(cat_num)
ret[cat_val] = 1
return ret
class CategoricalColumnMetadata(ColumnMetadata):
def __init__(self, categories=None, categories_count=None):
self._categories = set()
if categories is not None:
self._categories = set(categories)
self._categories_count = {}
if categories_count is not None:
self._categories_count = categories_count
@property
def categories(self):
return list(self._categories)
@property
def categories_count(self):
return self._categories_count
def aggregate(self, category):
self._categories.add(category)
self._categories_count[category] = self._categories_count.get(category, 0) + 1
def serialize(self):
dumps = json.dumps(self._categories_count)
return {'categories': self.categories, 'categories_count': dumps}
@classmethod
def deserialize(cls, schema):
categories_count = {}
for key, value in json.loads(schema['categories_count']).iteritems():
categories_count[str(key)] = int(value)
return CategoricalColumnMetadata(schema['categories'], categories_count) |
Ascend/pytorch | test/test_npu/test_network_ops/test_full_like.py | <reponame>Ascend/pytorch<filename>test/test_npu/test_network_ops/test_full_like.py
# Copyright (c) 2020, Huawei Technologies.All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# 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.
import torch
import numpy as np
import sys
from common_utils import TestCase, run_tests
from common_device_type import dtypes, instantiate_device_type_tests
from util_test import create_common_tensor
class TestFullLike(TestCase):
def generate_single_data(self,min_d, max_d, shape, dtype):
input1 = np.random.uniform(min_d, max_d, shape).astype(dtype)
npu_input1 = torch.from_numpy(input1)
return npu_input1
def cpu_op_exec(self,input1, input2):
output = torch.full_like(input1,input2)
#modify from torch.tensor to numpy.ndarray
output = output.numpy()
return output
def npu_op_exec(self,input1, input2):
input1 = input1.to("npu")
# input2 = input2.to("npu")
output = torch.full_like(input1,input2)
output = output.to("cpu")
output = output.numpy()
return output
def test_full_like_float16(self,device):
npu_input1=self.generate_single_data(0,100,(4,3),np.float16)
npu_input2=np.random.randint(0,100)
cpu_output=self.cpu_op_exec(npu_input1,npu_input2)
npu_output=self.npu_op_exec(npu_input1,npu_input2)
self.assertRtolEqual(cpu_output, npu_output)
def test_full_like_float32(self,device):
npu_input1=self.generate_single_data(0,100,(4,3),np.float32)
npu_input2=np.random.randint(0,100)
cpu_output=self.cpu_op_exec(npu_input1,npu_input2)
npu_output=self.npu_op_exec(npu_input1,npu_input2)
self.assertRtolEqual(cpu_output, npu_output)
def test_full_like_int32(self,device):
npu_input1=self.generate_single_data(0,100,(4,3),np.int32)
npu_input2=np.random.randint(0,100)
cpu_output=self.cpu_op_exec(npu_input1,npu_input2)
npu_output=self.npu_op_exec(npu_input1,npu_input2)
self.assertRtolEqual(cpu_output, npu_output)
def test_full_like_float_float16(self,device):
npu_input1=self.generate_single_data(0,100,(4,3),np.float16)
npu_input2=np.random.uniform(0,100)
cpu_output=self.cpu_op_exec(npu_input1,npu_input2)
npu_output=self.npu_op_exec(npu_input1,npu_input2)
self.assertRtolEqual(cpu_output, npu_output)
def test_full_like_float_float32(self,device):
npu_input1=self.generate_single_data(0,100,(4,3),np.float32)
npu_input2=np.random.uniform(0,100)
cpu_output=self.cpu_op_exec(npu_input1,npu_input2)
npu_output=self.npu_op_exec(npu_input1,npu_input2)
self.assertRtolEqual(cpu_output, npu_output)
def test_full_like_float_int32(self,device):
npu_input1=self.generate_single_data(0,100,(4,3),np.int32)
npu_input2=np.random.uniform(0,100)
cpu_output=self.cpu_op_exec(npu_input1,npu_input2)
npu_output=self.npu_op_exec(npu_input1,npu_input2)
self.assertRtolEqual(cpu_output, npu_output)
instantiate_device_type_tests(TestFullLike, globals(), except_for='cpu')
if __name__ == '__main__':
run_tests() |
pcrews/dcos-metrics | collectors/node/cpu_test.go | // Copyright 2016 Mesosphere, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package node
import (
"reflect"
"runtime"
"testing"
"time"
"github.com/shirou/gopsutil/cpu"
. "github.com/smartystreets/goconvey/convey"
)
var (
mockCPUMetric = cpuCoresMetric{
cpuCores: 4,
cpuTotal: float64(12.50),
cpuUser: float64(9.60),
cpuSystem: float64(2.90),
cpuIdle: float64(87.40),
cpuWait: float64(0.10),
timestamp: "2009-11-10T23:00:00Z",
}
)
func TestCPUGetDatapoints(t *testing.T) {
mockNc := nodeCollector{}
dps, err := mockCPUMetric.getDatapoints()
if err != nil {
t.Errorf("Expected no errors getting datapoints from mockCPU, got %s", err.Error())
}
if len(dps) != 6 {
t.Error("Expected 6 CPU metric datapoints, got", len(mockNc.datapoints))
}
}
func TestCalculatePcts(t *testing.T) {
lastTimes := cpu.TimesStat{
CPU: "cpu-total",
User: 20564.8,
System: 5355.2,
Idle: 3866.2,
Nice: 1141.0,
Iowait: 161.4,
Irq: 0.0,
Softirq: 138.8,
Steal: 0.0,
Guest: 0.0,
GuestNice: 0.0,
Stolen: 0.0,
}
currentTimes := cpu.TimesStat{
CPU: "cpu-total",
User: 20675.6,
System: 5388.1,
Idle: 39568.8,
Nice: 1141.0,
Iowait: 164.5,
Irq: 0.0,
Softirq: 139.2,
Steal: 0.0,
Guest: 0.0,
GuestNice: 0.0,
Stolen: 0.0,
}
Convey("When calculating CPU state percentages", t, func() {
pcts := calculatePcts(lastTimes, currentTimes)
Convey("Percentages should be calculated to two decimal places", func() {
So(pcts.User, ShouldEqual, 0.31)
So(pcts.System, ShouldEqual, 0.09)
So(pcts.Idle, ShouldEqual, 99.59)
So(pcts.Iowait, ShouldEqual, 0.01)
})
Convey("No percentages should be negative", func() {
v := reflect.ValueOf(pcts)
for i := 0; i < v.NumField(); i++ {
if v.Field(i).Kind() == reflect.String {
continue
}
So(v.Field(i).Interface(), ShouldBeGreaterThanOrEqualTo, 0)
}
})
Convey("Negative percentages should be coerced to 0", func() {
lowCurrentTimes := currentTimes
lowCurrentTimes.User = 20000.0
lowPcts := calculatePcts(lastTimes, lowCurrentTimes)
So(lowPcts.User, ShouldEqual, 0)
})
})
}
func TestFormatPct(t *testing.T) {
Convey("When formatting float64 values to two decimal places", t, func() {
Convey("Should work on all numbers", func() {
testCases := []struct {
input float64
expected float64
}{
{-123.456, 0.00},
{123.456, 123.46},
{0, 0.00},
{-1, 0.00},
{100.00000, 100.00},
{100, 100.00},
}
for _, tc := range testCases {
So(formatPct(tc.input, 100), ShouldEqual, tc.expected)
}
})
Convey("Should ignore attempts to divide by 0", func() {
So(formatPct(0.01, 0), ShouldEqual, 1)
})
})
}
func TestInit(t *testing.T) {
Convey("When initializing the node metrics collector", t, func() {
Convey("Should automatically set lastCPU times", func() {
if runtime.GOOS == "windows" {
// CPU not available on Windows, so using System instead
So(lastCPU.times.System, ShouldNotEqual, "")
} else {
So(lastCPU.times.CPU, ShouldNotEqual, "")
}
})
})
}
func TestGetCPUTimes(t *testing.T) {
Convey("When getting CPU times", t, func() {
Convey("Should return both the current times and last times (so that percentages can be calculated)", func() {
time.Sleep(1 * time.Second)
cur, last, err := getCPUTimes()
if err != nil {
t.Fatal(err)
}
So(cur.User, ShouldBeGreaterThanOrEqualTo, last.User)
So(cur.Idle, ShouldBeGreaterThanOrEqualTo, last.Idle)
})
})
}
|
VirgilSecurity/virgil-sdk-go | crypto/wrapper/foundation/asn1_writer.go | <reponame>VirgilSecurity/virgil-sdk-go
package foundation
import "C"
import unsafe "unsafe"
/*
* Provides interface to the ASN.1 writer.
* Note, elements are written starting from the buffer ending.
* Note, that all "write" methods move writing position backward.
*/
type Asn1Writer interface {
context
/*
* Reset all internal states and prepare to new ASN.1 writing operations.
*/
Reset(out []byte, outLen uint)
/*
* Finalize writing and forbid further operations.
*
* Note, that ASN.1 structure is always written to the buffer end, and
* if argument "do not adjust" is false, then data is moved to the
* beginning, otherwise - data is left at the buffer end.
*
* Returns length of the written bytes.
*/
Finish(doNotAdjust bool) uint
/*
* Returns pointer to the inner buffer.
*/
Bytes() unsafe.Pointer
/*
* Returns total inner buffer length.
*/
Len() uint
/*
* Returns how many bytes were already written to the ASN.1 structure.
*/
WrittenLen() uint
/*
* Returns how many bytes are available for writing.
*/
UnwrittenLen() uint
/*
* Return true if status is not "success".
*/
HasError() bool
/*
* Return error code.
*/
Status() error
/*
* Move writing position backward for the given length.
* Return current writing position.
*/
Reserve(len uint) unsafe.Pointer
/*
* Write ASN.1 tag.
* Return count of written bytes.
*/
WriteTag(tag int32) uint
/*
* Write context-specific ASN.1 tag.
* Return count of written bytes.
*/
WriteContextTag(tag int32, len uint) uint
/*
* Write length of the following data.
* Return count of written bytes.
*/
WriteLen(len uint) uint
/*
* Write ASN.1 type: INTEGER.
* Return count of written bytes.
*/
WriteInt(value int32) uint
/*
* Write ASN.1 type: INTEGER.
* Return count of written bytes.
*/
WriteInt8(value int8) uint
/*
* Write ASN.1 type: INTEGER.
* Return count of written bytes.
*/
WriteInt16(value int16) uint
/*
* Write ASN.1 type: INTEGER.
* Return count of written bytes.
*/
WriteInt32(value int32) uint
/*
* Write ASN.1 type: INTEGER.
* Return count of written bytes.
*/
WriteInt64(value int64) uint
/*
* Write ASN.1 type: INTEGER.
* Return count of written bytes.
*/
WriteUint(value uint32) uint
/*
* Write ASN.1 type: INTEGER.
* Return count of written bytes.
*/
WriteUint8(value uint8) uint
/*
* Write ASN.1 type: INTEGER.
* Return count of written bytes.
*/
WriteUint16(value uint16) uint
/*
* Write ASN.1 type: INTEGER.
* Return count of written bytes.
*/
WriteUint32(value uint32) uint
/*
* Write ASN.1 type: INTEGER.
* Return count of written bytes.
*/
WriteUint64(value uint64) uint
/*
* Write ASN.1 type: BOOLEAN.
* Return count of written bytes.
*/
WriteBool(value bool) uint
/*
* Write ASN.1 type: NULL.
*/
WriteNull() uint
/*
* Write ASN.1 type: OCTET STRING.
* Return count of written bytes.
*/
WriteOctetStr(value []byte) uint
/*
* Write ASN.1 type: BIT STRING with all zero unused bits.
*
* Return count of written bytes.
*/
WriteOctetStrAsBitstring(value []byte) uint
/*
* Write raw data directly to the ASN.1 structure.
* Return count of written bytes.
* Note, use this method carefully.
*/
WriteData(data []byte) uint
/*
* Write ASN.1 type: UTF8String.
* Return count of written bytes.
*/
WriteUtf8Str(value []byte) uint
/*
* Write ASN.1 type: OID.
* Return count of written bytes.
*/
WriteOid(value []byte) uint
/*
* Mark previously written data of given length as ASN.1 type: SEQUENCE.
* Return count of written bytes.
*/
WriteSequence(len uint) uint
/*
* Mark previously written data of given length as ASN.1 type: SET.
* Return count of written bytes.
*/
WriteSet(len uint) uint
/*
* Release underlying C context.
*/
Delete()
}
|
LandRegistry/maintain-frontend | maintain_frontend/search/search_by_reference.py | from flask import render_template, current_app, request, url_for, redirect, g
from maintain_frontend.constants.permissions import Permissions
from maintain_frontend.decorators import requires_permission
from maintain_frontend.search.validation.reference_validator import ReferenceValidator
from maintain_frontend.services.search_by_reference import SearchByReference
from maintain_frontend.models import LocalLandChargeItem
from maintain_frontend.services.charge_id_services import calc_display_id
from operator import attrgetter
def register_routes(bp):
bp.add_url_rule('/search/reference', view_func=get_search_by_reference, methods=['GET'])
bp.add_url_rule('/search/reference', view_func=post_search_by_reference, methods=['POST'])
@requires_permission([Permissions.browse_llc])
def get_search_by_reference():
current_app.logger.info("Search by reference page requested")
return render_template('search-by-reference.html', submit_url=url_for("search.post_search_by_reference"))
@requires_permission([Permissions.browse_llc])
def post_search_by_reference():
search_reference = request.form.get('search-reference').strip()
current_app.logger.info("Running validation")
validation_errors = ReferenceValidator.validate(search_reference)
if validation_errors.errors:
current_app.logger.warning("Validation errors occurred")
return render_template('search-by-reference.html',
validation_errors=validation_errors.errors,
validation_summary_heading=validation_errors.summary_heading_text,
submit_url=url_for("search.post_search_by_reference")), 400
search_by_reference_processor = SearchByReference(current_app.config, current_app.logger)
response = search_by_reference_processor.process(search_reference.upper())
if response["status_code"] == 200:
charge_items = list(map(lambda charge: LocalLandChargeItem.from_json(charge["item"]), response["results"]))
if len(charge_items) == 1:
return redirect(url_for('view_land_charge.view_land_charge',
local_land_charge=calc_display_id(charge_items[0].local_land_charge)))
else:
charges_by_type = sorted(charge_items, key=attrgetter('charge_type'))
matching_authority = list(filter(
lambda charge_item: charge_item.originating_authority == g.session.user.organisation, charges_by_type))
other_charges = list(filter(
lambda charge_item: charge_item.originating_authority != g.session.user.organisation, charges_by_type))
charge_items = matching_authority + other_charges
else:
charge_items = None
return render_template('search-by-reference.html', submit_url=url_for("search.post_search_by_reference"),
charge_items=charge_items)
|
HaeSe0ng/SWPP | front/src/components/User/Auth/SignIn/SignInForm.test.js | import React from 'react';
import { mount } from 'enzyme';
import { act } from '@testing-library/react';
import SignInForm from './SignInForm';
describe('<SignInForm />', () => {
let signInForm;
let mockClickSignInHandler;
let mockClickSignUpHandler;
let mockChangeEmailHandler;
let mockChangePasswordHandler;
const mockSignInState = {
email: '',
password: '',
};
beforeEach(() => {
mockClickSignInHandler = jest.fn();
mockClickSignUpHandler = jest.fn();
mockChangeEmailHandler = jest.fn();
mockChangePasswordHandler = jest.fn();
signInForm = (
<SignInForm
email={mockSignInState.email}
password={<PASSWORD>}
onEmailChange={mockChangeEmailHandler}
onPasswordChange={mockChangePasswordHandler}
clickSignIn={mockClickSignInHandler}
clickSignUp={mockClickSignUpHandler}
/>
);
});
it('should render without errors', () => {
const component = mount(signInForm);
const wrapper = component.find('.SignInForm');
expect(wrapper.length).toBe(1);
});
it('should call clickSignUp() on click SignUp button', async () => {
const component = mount(signInForm);
const wrapper = component.find('.SignUpButton');
await new Promise(resolve => setTimeout(resolve, 100));
wrapper.at(0).simulate('click');
await new Promise(resolve => setTimeout(resolve, 100));
expect(mockClickSignUpHandler).toHaveBeenCalled();
});
it('should call onEmailChange() on email change', async () => {
const component = mount(signInForm);
const wrapper = component.find('Input');
await new Promise(resolve => setTimeout(resolve, 100));
await act(async () => {
wrapper.at(0).prop('onChange')({
target: { name: 'email', value: 'a' },
});
await new Promise(resolve => setTimeout(resolve, 100));
});
expect(mockChangeEmailHandler).toHaveBeenCalled();
});
it('should call onPasswordChange() on email change', async () => {
const component = mount(signInForm);
const wrapper = component.find('Input');
await new Promise(resolve => setTimeout(resolve, 100));
await act(async () => {
wrapper.at(1).prop('onChange')({
target: { name: 'password', value: 'a' },
});
await new Promise(resolve => setTimeout(resolve, 100));
});
expect(mockChangePasswordHandler).toHaveBeenCalled();
});
});
|
MireiaDiaz/XiSearch | src/main/java/rappsilber/applications/TargetPeakOccurence.java | <filename>src/main/java/rappsilber/applications/TargetPeakOccurence.java
/*
* Copyright 2016 <NAME> <<EMAIL>>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package rappsilber.applications;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.text.ParseException;
import java.util.TreeSet;
import rappsilber.ms.ToleranceUnit;
import rappsilber.ms.dataAccess.SpectraAccess;
import rappsilber.ms.dataAccess.msm.AbstractMSMAccess;
import rappsilber.ms.spectra.Spectra;
import rappsilber.ms.spectra.SpectraPeak;
/**
*
* @author <NAME> <<EMAIL>>
*/
public class TargetPeakOccurence {
// static double[] m_TargetPeaks = new double[]{156.14,
//184.13,
//269.22,
//297.22,
//267.21,
//305.22,
//307.24,
//255.21,
//240.16,
//270.23,
//222.15,
//268.21,
//340.22,
//150.11,
//201.16,
//185.14,
//215.18,
//224.17,
//380.26,
//335.24,
//305.23,
//139.08,
//241.19,
//170.12,
//335.23,
//269.23,
//256.21,
//134.1,
//352.26,
//165.06,
//189.13,
//201.19,
//253.19,
//123.09,
//283.2,
//363.75,
//153.62,
//139.07,
//240.18,
//207.15,
//184.14,
//364.85,
//294.82,
//239.18,
//254.2,
//342.7
//};
//static double[] m_TargetPeaks = new double[]{165.06,201.19,267.17,305.22,306.23,326.25,333.22,378.24,385.14,176.11}
static double[] m_TargetPeaks = new double[]{
120.0875,
120.578,
134.084,
139.075,
153.1145,
156.102,
157.086,
165.06,
170.138,
175.622,
176.11,
184.1355,
198.1354125175,
201.19,
222.149,
239.175,
240.156,
267.168,
305.22,
305.229,
306.23,
326.25,
333.22,
339.276,
350.244,
367.271,
378.24,
385.14,
395.263,
};
static TreeSet<Double> m_TargetSet;
static {
m_TargetSet = new TreeSet<Double>();
for (double d: m_TargetPeaks)
m_TargetSet.add(d);
}
public double[] getPeaks(Spectra s, TreeSet<Double> TargetPeaks) {
double[] peaks = new double[TargetPeaks.size()];
int p = 0;
for (double d : TargetPeaks) {
SpectraPeak sp = s.getPeakAt(d);
if (sp == null) {
peaks[p++] = 0;
} else
peaks[p++] = 1;
}
return peaks;
}
public void run(PrintStream out, SpectraAccess sa, TreeSet<Double> TargetPeaks) {
out.print("Run, Scan");
for (Double d : TargetPeaks) {
out.print("," + d);
}
out.println();
while (sa.hasNext()) {
Spectra s = sa.next();
out.print(s.getRun() + "," + s.getScanNumber());
for (double d : getPeaks(s, TargetPeaks)) {
out.print("," + d);
}
out.println();
}
}
public static void main(String[] argv) throws FileNotFoundException, IOException, ParseException {
ToleranceUnit t = new ToleranceUnit(0.005, "da");
//SpectraAccess sa = AbstractMSMAccess.getMSMIterator("/home/lfischer/people/Helena/M090625_crosslinked_matched.msm", t, 1);
//SpectraAccess sa = AbstractMSMAccess.getMSMIterator("/home/lfischer/people/Juri/IndicatorPeaks/all.msm", t, 1);
SpectraAccess sa = AbstractMSMAccess.getMSMIterator("/home/lfischer/people/Juri/IndicatorPeaks/XLinkedSynthetic_and_Yeast.msm", t, 1, null);
//PrintStream out = new PrintStream("/home/lfischer/people/Juri/IndicatorPeaks/XLinkdSynth.csv");
PrintStream out = new PrintStream("/home/lfischer/people/Juri/IndicatorPeaks/XLinkedSynthetic_and_Yeast_peaks.csv");
new TargetPeakOccurence().run(out, sa, m_TargetSet);
}
}
|
nrbrigmon/et_reboot | client/src/utils/_buildingMathModule.js | <filename>client/src/utils/_buildingMathModule.js
import * as _ from 'lodash';
let landUses = {
streets: 0, //b4
landscaping: 0, //b5
buildingNParking: 0, //b6
totalLotSize: 0 //b7
};
let maxBuildingEnvelope = {
squareFootage: 0, //b10
buildingFootprint: 0, //b11
residentialUnderbuild: 0//b12
};
//if underground or internal parking only - no suface/structured
let parkingOptionA = {
residentialMaxSf: 0,
residentialSpacesPoss: 0,
retailMaxSf: 0,
retailSpacesPoss: 0,
officeMaxSf: 0,
officeSpacesPoss: 0,
industrialMaxSf: 0,
industrialSpacesPoss: 0,
publicMaxSf: 0,
publicSpacesPoss: 0,
educationalMaxSf: 0,
educationalSpacesPoss: 0,
hotelMaxSf: 0,
hotelSpacesPoss: 0,
commercialParkingMaxSf: 0,
commercialParkingSpacesPoss: 0,
internalParkingMaxSf: 0,
internalParkingSpacesPoss: 0,
totalMaxSf:0,
totalSpacesPoss: 0,
lessInternalParking: 0
}
let parkingOptionA_Aids = {
maxParkingRequired: 0, //b29
undergroundParkingProvided: 0, //b30
internalParkingProvided: 0, //b31
surplusOrDeficit: 0, //b32
externalSpacesPer1000: 0, //b35
maxSpacesUnderground: 0, //b36
adjustedSpacesUnderground: 0, //b37
remainderExternalSpacesRequired: 0, //b38
totalParkBuildFootprint: 0, //b41
internalSfEnvelope: 0, //b42
adjustmentIfOverEnvelope: 0, //b43
internalFootprint: 0, //b44
adjustmentIfOverFootprint: 0, //b45
aboveGradeParking: 0 //b46
}
//end parkingOptionA
//If Underground or Internal Parking Only AND additional Surface/Structured Parking Required
let parkingOptionB = {
residentialMaxSf: 0, //b51
residentialSpacesPoss: 0, //c51
residentialMaxSfPerc: 0, //d51
retailMaxSf: 0, //b52
retailSpacesPoss: 0, //c52
retailMaxSfPerc: 0, //d52
officeMaxSf: 0, //b53
officeSpacesPoss: 0, //c53
officeMaxSfPerc: 0, //d53
industrialMaxSf: 0, //b54
industrialSpacesPoss: 0, //c54
industrialMaxSfPerc: 0, //d54
publicMaxSf: 0, //b55
publicSpacesPoss: 0, //c55
publicMaxSfPerc: 0, //d55
educationalMaxSf: 0, //b56
educationalSpacesPoss: 0, //c56
educationalMaxSfPerc: 0, //d56
hotelMaxSf: 0, //b57
hotelSpacesPoss: 0, //c57
hotelMaxSfPerc: 0, //d57
commercialParkingMaxSf: 0, //b58
commercialParkingSpacesPoss: 0, //c58
commercialParkingMaxSfPerc: 0, //d58
internalParkingMaxSf: 0, //b59
internalParkingSpacesPoss: 0, //c59
internalParkingMaxSfPerc: 0, //d59
totalMaxSf:0, //b60
totalSpaces:0, //c60
lessInternalParking: 0, //c61
buildingFootprint: 0, //b64
lanscapeFootprint: 0, //b65
parkingFootprint: 0, //b66
unusedFootprint: 0 //b67
};
//end parkingOptionB
//If Surface/Structured Parking
let parkingOptionC = {
parkingMaxA: 0, //b71
parkingMaxA_2: 1000, //c71
parkingMaxB: 0, //b72
parkingMaxB_2: 0, //c72
buildingAvailable: 0, //b73
parkingAvailable: 0, //b74
parkingAvailable_2: 0, //c74
aboveGrade: 0, //b75
aboveGradeFootprint: 0, //b76
buildingFootprintNeeded: 0, //b77
adjustedTotalBuilding: 0, //b78
aboveGradeParking: 0, //b79
unusedSpace: 0, //b80
adjustedMaxBuilding: 0, //b81
buildingFootprint: 0, //b84
lanscapeFootprint: 0, //b85
parkingFootprint: 0, //b86
unusedFootprint: 0 //b87
}
//Square Footage by Use (if surface/structured parking)
let parkingOptionC_Aid1 = {
residentialSf: 0,
residentialSpaces: 0,
retailSf: 0,
retailSpaces: 0,
officeSf: 0,
officeSpaces: 0,
industrialSf: 0,
industrialSpaces: 0,
publicSf: 0,
publicSpaces: 0,
educationalSf: 0,
educationalSpaces: 0,
hotelSf: 0,
hotelSpaces: 0,
commercialParkingSf: 0,
commercialParkingSpaces: 0,
internalParkingSf: 0,
internalParkingSpaces: 0,
totalSf: 0,
totalSpaces: 0,
lessInternalParking: 0
}
//Square Footage by Use (without Underbuild)
let parkingOptionC_Aid2= {
residentialSf: 0,
residentialSpaces: 0,
retailSf: 0,
retailSpaces: 0,
officeSf: 0,
officeSpaces: 0,
industrialSf: 0,
industrialSpaces: 0,
publicSf: 0,
publicSpaces: 0,
educationalSf: 0,
educationalSpaces: 0,
hotelSf: 0,
hotelSpaces: 0,
commercialParkingSf: 0,
commercialParkingSpaces: 0,
internalParkingSf: 0,
internalParkingSpaces: 0,
totalSf: 0,
totalSpaces: 0,
lessInternalParking: 0
}
//Square Footage by Use (with Underbuild)
let parkingOptionC_Aid3 = {
residentialSf: 0,
residentialSpaces: 0,
retailSf: 0,
retailSpaces: 0,
officeSf: 0,
officeSpaces: 0,
industrialSf: 0,
industrialSpaces: 0,
publicSf: 0,
publicSpaces: 0,
educationalSf: 0,
educationalSpaces: 0,
hotelSf: 0,
hotelSpaces: 0,
commercialParkingSf: 0,
commercialParkingSpaces: 0,
internalParkingSf: 0,
internalParkingSpaces: 0,
totalSf: 0,
totalSpaces: 0,
lessInternalParking: 0
}
//Square Footage by Use (Adjusted)
let parkingOptionC_Aid4 = {
residentialSf: 0,
residentialSpaces: 0,
retailSf: 0,
retailSpaces: 0,
officeSf: 0,
officeSpaces: 0,
industrialSf: 0,
industrialSpaces: 0,
publicSf: 0,
publicSpaces: 0,
educationalSf: 0,
educationalSpaces: 0,
hotelSf: 0,
hotelSpaces: 0,
commercialParkingSf: 0,
commercialParkingSpaces: 0,
internalParkingSf: 0,
internalParkingSpaces: 0,
totalSf: 0,
totalSpaces: 0,
lessInternalParking: 0
}
//Adjustment Factors
let parkingOptionC_Aid5 = {
unusedFootprint: 0,
bldgFootprint: 0,
bldgParkingFootprint: 0,
additionalArea: 0,
additionalFootprint: 0,
additionalParking: 0,
adjustedVolume: 0,
adjustedSpaces: 0
}
//end parkingOptionC
// Site Summary
// Pre-Underbuild
let preUnderbuild = {
buildingFootprint: 0,
lanscapeFootprint: 0,
parkingFootprint: 0,
unusedFootprint: 0
}
// Post-Underbuild
let postUnderbuild = {
buildingFootprint: 0,
lanscapeFootprint: 0,
parkingFootprint: 0,
unusedFootprint: 0
}
// Adjusted
let adjustedSummary = {
buildingFootprint: 0, //b164
lanscapeFootprint: 0,
parkingFootprint: 0,
unusedFootprint: 0
}
let adjustedSpaces = {
surface: 0,
underground: 0,
commercialParking: 0,
internal: 0
}
let adjustedParkingSpaces = {
residentialRequired: 0,
retailRequired: 0,
officeRequired: 0,
industrialRequired: 0,
publicRequired: 0,
educationalRequired: 0,
hotelRequired: 0,
structuredProvided: 0,
undergroundProvided: 0,
commercialProvided: 0,
commercialRequired: 0,
internalProvided: 0,
totalProvided: 0,
totalRequired: 0,
totalExcess: 0
}
let adjustedParkingFootprint = {
surfaceArea: 0,
surfaceFootprint: 0,
undergroundArea: 0,
undergroundFootprint: 0
}
//end site summary
///rent calculator (will need to be moved to a state loaded file later)
/*
Below-Market Rent Target AMI Below-Market Unit Mix Percent of AMI Below-Market Rent
Market $60,000 - - -
Income-Restricted - 60% 80% $1,200
Low Income - 20% 60% $900
Very Low Income - 20% 40% $600
Calculated Below-Market Rent - 100% - $1,020
*/
let residentialUnitSizeEst = {
afford: 975,
affordPerc: .2,
bed1: 2000,
bed1Perc: .4,
bed2: 1200,
bed2Perc: .2,
bed3: 975,
bed3Perc: 0,
bed4: 725,
bed4Perc: 0,
studio: 575,
studioPerc: .2
}
let residentialRentEstimator = {
avgMonthlyRentCalc: 1.63
}
/*
Residential Unit Size Estimator ◊ Avg. Unit Size (Net Square Feet) % of Units in Building Required Parking by Type ◊ # of Units by Type
Affordable 975 10% 1.2 5
4+ Bedroom 2,000 0% 2.1 -
3 Bedroom 1,200 0% 1.5 -
2 Bedroom 975 25% 1.2 12
1 Bedroom 725 45% 0.9 21
Studio 575 20% 0.6 9
Calculated Residential Unit Size 783 100% 0.9 42
Residential Rent Estimator ◊ $ / sf Unit Size Parking Cost / Mo Rent
Affordable $1.05 975 $- $1,020
4+ Bedroom $1.40 2,000 $- $2,800
3 Bedroom $1.50 1,200 $- $1,800
2 Bedroom $1.60 975 $- $1,560
1 Bedroom $1.70 725 $- $1,233
Studio $1.80 575 $- $1,035
Calculated Average Monthly Rent $1.63 783 $- $1,276
*/
let errorChecking = (answer) => {
return ( isNaN(answer) ? 0 : answer );
};
export const updateBuildingEnvelope = (physObj, basObj, advObj) => {
landUses["streets"] = physObj.siteArea*(1-physObj.siteNetToGross);
landUses["landscaping"] = physObj.siteArea*physObj.landscapingPerc;
landUses["buildingNParking"] = physObj.siteArea - landUses["landscaping"] - landUses["streets"];
landUses["totalLotSize"] = landUses["buildingNParking"] + landUses["landscaping"] + landUses["streets"]; //b7
// console.log(landUses);
// console.log(landUses["buildingNParking"], physObj.buildingHeight)
maxBuildingEnvelope['squareFootage'] = landUses["buildingNParking"] * physObj.buildingHeight;
maxBuildingEnvelope['buildingFootprint'] = errorChecking(maxBuildingEnvelope['squareFootage'] / physObj.buildingHeight);
maxBuildingEnvelope['residentialUnderbuild'] = ((physObj.residentialType === 'Multifamily') ? advObj.residentialRentalPerc : 1);
//If Underground or Internal Parking Only - No Surface/Structured
parkingOptionA["internalParkingMaxSf"] = physObj.internalParkingLvls*maxBuildingEnvelope['buildingFootprint'];
let maxMinusInternal = maxBuildingEnvelope['squareFootage'] - parkingOptionA["internalParkingMaxSf"];
parkingOptionA["residentialMaxSf"] = (maxMinusInternal)*physObj["residentialUsePerc"];
parkingOptionA["retailMaxSf"] = (maxMinusInternal)*physObj["retailUsePerc"];
parkingOptionA["officeMaxSf"] = (maxMinusInternal)*physObj["officeUsePerc"];
parkingOptionA["industrialMaxSf"] = (maxMinusInternal)*physObj["industrialUsePerc"];
parkingOptionA["publicMaxSf"] = (maxMinusInternal)*physObj["publicUsePerc"];
parkingOptionA["educationalMaxSf"] = (maxMinusInternal)*physObj["educationUsePerc"];
parkingOptionA["hotelMaxSf"] = (maxMinusInternal)*physObj["hotelUsePerc"];
parkingOptionA["commercialParkingMaxSf"] = (maxMinusInternal)*physObj["parkingUsePerc"];
parkingOptionA["totalMaxSf"] = physObj["residentialUsePerc"] + physObj["retailUsePerc"] + physObj["officeUsePerc"] + physObj["industrialUsePerc"] + physObj["publicUsePerc"] + physObj["educationUsePerc"] + physObj["hotelUsePerc"] + physObj["parkingUsePerc"];
parkingOptionA["residentialSpacesPoss"] = errorChecking(((physObj["residentialUnitSize"] === 0) ? 0 : ((parkingOptionA["residentialMaxSf"]/(physObj["residentialUnitSize"] / maxBuildingEnvelope['residentialUnderbuild'] ))*physObj["residentialParkPerUnit"]) ))
parkingOptionA["retailSpacesPoss"] = errorChecking(parkingOptionA["retailMaxSf"] / physObj["retailParkPerArea"])
parkingOptionA["officeSpacesPoss"] = errorChecking(parkingOptionA["officeMaxSf"] / physObj["officeParkPerArea"])
parkingOptionA["industrialSpacesPoss"] = errorChecking(parkingOptionA["industrialMaxSf"] / physObj["industrialParkPerArea"])
parkingOptionA["publicSpacesPoss"] = errorChecking(parkingOptionA["publicMaxSf"] / physObj["publicParkPerArea"])
parkingOptionA["educationalSpacesPoss"] = errorChecking(parkingOptionA["educationalMaxSf"] / physObj["educationParkPerArea"])
parkingOptionA["hotelSpacesPoss"] = errorChecking(((physObj["hotelAreaPerRoom"] === 0) ? 0 : ( (parkingOptionA["hotelMaxSf"] /(physObj["hotelAreaPerRoom"]/advObj["hotelRentalPerc"]))*physObj["hotelParkPerRoom"]) ))
parkingOptionA["commercialParkingSpacesPoss"] = errorChecking(parkingOptionA["commercialParkingMaxSf"] / physObj["parkingAreaPerSf"])
parkingOptionA["internalParkingSpacesPoss"] = errorChecking(parkingOptionA["internalParkingMaxSf"] / physObj["parkingAreaPerSf"])
parkingOptionA["totalSpacesPoss"] = parkingOptionA["residentialSpacesPoss"] + parkingOptionA["retailSpacesPoss"] + parkingOptionA["officeSpacesPoss"] + parkingOptionA["industrialSpacesPoss"] + parkingOptionA["publicSpacesPoss"] + parkingOptionA["educationalSpacesPoss"] + parkingOptionA["hotelSpacesPoss"] + parkingOptionA["commercialParkingSpacesPoss"] + parkingOptionA["internalParkingSpacesPoss"];
parkingOptionA["lessInternalParking"] = parkingOptionA["internalParkingSpacesPoss"] - parkingOptionA["residentialSpacesPoss"] + parkingOptionA["retailSpacesPoss"] + parkingOptionA["officeSpacesPoss"] + parkingOptionA["industrialSpacesPoss"] + parkingOptionA["publicSpacesPoss"] + parkingOptionA["educationalSpacesPoss"] + parkingOptionA["hotelSpacesPoss"];
parkingOptionA_Aids["maxParkingRequired"] = parkingOptionA["residentialSpacesPoss"] + parkingOptionA["retailSpacesPoss"] + parkingOptionA["officeSpacesPoss"] + parkingOptionA["industrialSpacesPoss"] + parkingOptionA["publicSpacesPoss"] + parkingOptionA["educationalSpacesPoss"] + parkingOptionA["hotelSpacesPoss"];
parkingOptionA_Aids["undergroundParkingProvided"] = errorChecking((
( physObj["undergroundParkingLvls"] > 0 && physObj["mechanicalParkingb76"] === "Yes") ? (physObj["siteArea"]*physObj["undergroundParkingLvls"])/125 : ( (physObj["undergroundParkingLvls"] > 0) ? (physObj["siteArea"]*physObj["undergroundParkingLvls"])/physObj["parkingAreaPerSf"] : 0)
) );
parkingOptionA_Aids["internalParkingProvided"] = parkingOptionA["internalParkingSpacesPoss"];
parkingOptionA_Aids["surplusOrDeficit"] = parkingOptionA_Aids["undergroundParkingProvided"] + parkingOptionA_Aids["internalParkingProvided"] - parkingOptionA_Aids["maxParkingRequired"];
parkingOptionA_Aids["externalSpacesPer1000"] = errorChecking(parkingOptionA["lessInternalParking"] / (parkingOptionA["totalMaxSf"] / 1000));
parkingOptionA_Aids["maxSpacesUnderground"] = errorChecking((landUses["totalLotSize"]/physObj["parkingAreaPerSf"])*physObj["undergroundParkingLvls"]);
parkingOptionA_Aids["adjustedSpacesUnderground"] = ((parkingOptionA["lessInternalParking"] < parkingOptionA_Aids["maxSpacesUnderground"]) ? parkingOptionA["lessInternalParking"] : parkingOptionA_Aids["maxSpacesUnderground"]);
parkingOptionA_Aids["remainderExternalSpacesRequired"] = ( (parkingOptionA_Aids["externalSpacesPer1000"] < 0) ? 0: parkingOptionA_Aids["externalSpacesPer1000"]);
parkingOptionA_Aids["totalParkBuildFootprint"] = landUses["buildingNParking"];
parkingOptionA_Aids["internalSfEnvelope"] = (parkingOptionA_Aids["externalSpacesPer1000"] === 0) ? 0 : ((1000/parkingOptionA_Aids["externalSpacesPer1000"])*parkingOptionA_Aids["adjustedSpacesUnderground"]);
parkingOptionA_Aids["adjustmentIfOverEnvelope"] = ( (parkingOptionA_Aids["internalSfEnvelope"]>maxBuildingEnvelope['squareFootage']) ? maxBuildingEnvelope['squareFootage'] :parkingOptionA_Aids["internalSfEnvelope"])
parkingOptionA_Aids["internalFootprint"] = errorChecking(parkingOptionA_Aids["adjustmentIfOverEnvelope"] / physObj["buildingHeight"]);
parkingOptionA_Aids["adjustmentIfOverFootprint"] = ( (parkingOptionA_Aids["internalFootprint"]>parkingOptionA_Aids["totalParkBuildFootprint"]) ? parkingOptionA_Aids["totalParkBuildFootprint"] : parkingOptionA_Aids["internalFootprint"]);
parkingOptionA_Aids["aboveGradeParking"] = parkingOptionA_Aids["totalParkBuildFootprint"]-parkingOptionA_Aids["adjustmentIfOverFootprint"];
//If Underground or Internal Parking Only AND additional Surface/Structured Parking Required
parkingOptionB["internalParkingMaxSfPerc"] = errorChecking((
(physObj["internalParkingLvls"] === 0) ? 0 : 1/(physObj["buildingHeight"]/physObj["internalParkingLvls"])
));
parkingOptionB["residentialMaxSfPerc"] = (1-parkingOptionB["internalParkingMaxSfPerc"])*physObj["residentialUsePerc"];
parkingOptionB["retailMaxSfPerc"] = (1-parkingOptionB["internalParkingMaxSfPerc"])*physObj["retailUsePerc"];
parkingOptionB["officeMaxSfPerc"] = (1-parkingOptionB["internalParkingMaxSfPerc"])*physObj["officeUsePerc"];
parkingOptionB["industrialMaxSfPerc"] = (1-parkingOptionB["internalParkingMaxSfPerc"])*physObj["industrialUsePerc"];
parkingOptionB["publicMaxSfPerc"] = (1-parkingOptionB["internalParkingMaxSfPerc"])*physObj["publicUsePerc"];
parkingOptionB["educationalMaxSfPerc"] = (1-parkingOptionB["internalParkingMaxSfPerc"])*physObj["educationUsePerc"];
parkingOptionB["hotelMaxSfPerc"] = (1-parkingOptionB["internalParkingMaxSfPerc"])*physObj["hotelUsePerc"];
parkingOptionB["commercialParkingMaxSfPerc"] = (1-parkingOptionB["internalParkingMaxSfPerc"])*physObj["parkingUsePerc"];
let optionBHelper = parkingOptionA_Aids["undergroundParkingProvided"] + parkingOptionA_Aids["internalParkingProvided"];
let optionBHelper2 = parkingOptionA_Aids["adjustmentIfOverEnvelope"];
parkingOptionB["internalParkingMaxSf"] = (parkingOptionA_Aids["maxParkingRequired"]>=optionBHelper ? (optionBHelper2*["internalParkingMaxSfPerc"]) : parkingOptionA["internalParkingMaxSf"]);
parkingOptionB["residentialMaxSf"] = (parkingOptionA_Aids["maxParkingRequired"]>=optionBHelper ? (optionBHelper2*parkingOptionB["residentialMaxSfPerc"]) : parkingOptionA["residentialMaxSfPerc"]);
parkingOptionB["retailMaxSf"] = (parkingOptionA_Aids["maxParkingRequired"]>=optionBHelper ? (optionBHelper2*parkingOptionB["retailMaxSfPerc"]) : parkingOptionA["retailMaxSfPerc"]);
parkingOptionB["officeMaxSf"] = (parkingOptionA_Aids["maxParkingRequired"]>=optionBHelper ? (optionBHelper2*parkingOptionB["officeMaxSfPerc"]) : parkingOptionA["officeMaxSfPerc"]);
parkingOptionB["industrialMaxSf"] = (parkingOptionA_Aids["maxParkingRequired"]>=optionBHelper ? (optionBHelper2*parkingOptionB["industrialMaxSfPerc"]) : parkingOptionA["industrialMaxSfPerc"]);
parkingOptionB["publicMaxSf"] = (parkingOptionA_Aids["maxParkingRequired"]>=optionBHelper ? (optionBHelper2*parkingOptionB["publicMaxSfPerc"]) : parkingOptionA["publicMaxSfPerc"]);
parkingOptionB["educationalMaxSf"] = (parkingOptionA_Aids["maxParkingRequired"]>=optionBHelper ? (optionBHelper2*parkingOptionB["educationalMaxSfPerc"]) : parkingOptionB["educationalMaxSfPerc"]);
parkingOptionB["hotelMaxSf"] = (parkingOptionA_Aids["maxParkingRequired"]>=optionBHelper ? (optionBHelper2*parkingOptionB["hotelMaxSfPerc"]) : parkingOptionA["hotelMaxSfPerc"]);
parkingOptionB["commercialParkingMaxSf"] = (parkingOptionA_Aids["maxParkingRequired"]>=optionBHelper ? (optionBHelper2*parkingOptionB["commercialParkingMaxSfPerc"]) : parkingOptionA["commercialParkingMaxSfPerc"]);
parkingOptionB["totalMaxSf"] = parkingOptionB["internalParkingMaxSf"] + parkingOptionB["residentialMaxSf"] + parkingOptionB["retailMaxSf"] + parkingOptionB["officeMaxSf"] + parkingOptionB["industrialMaxSf"] + parkingOptionB["publicMaxSf"] + parkingOptionB["educationalMaxSf"] + parkingOptionB["hotelMaxSf"] + parkingOptionB["commercialParkingMaxSf"];
parkingOptionB["internalParkingSpacesPoss"] = errorChecking(parkingOptionB["internalParkingMaxSf"]/physObj["parkingAreaPerSf"]);
parkingOptionB["residentialSpacesPoss"] = errorChecking((
(physObj["residentialUnitSize"]===0) ? 0 : (parkingOptionB["residentialMaxSf"]/(physObj["residentialUnitSize"]/maxBuildingEnvelope["residentialUnderbuild"]))*physObj["residentialParkPerUnit"]
))
parkingOptionB["retailSpacesPoss"] = errorChecking((parkingOptionB["retailMaxSf"]/1000)*physObj["retailParkPerArea"])
parkingOptionB["officeSpacesPoss"] = errorChecking((parkingOptionB["officeMaxSf"]/1000)*physObj["officeParkPerArea"])
parkingOptionB["industrialSpacesPoss"] = errorChecking((parkingOptionB["industrialMaxSf"]/1000)*physObj["industrialParkPerArea"])
parkingOptionB["publicSpacesPoss"] = errorChecking((parkingOptionB["publicMaxSf"]/1000)*physObj["publicParkPerArea"])
parkingOptionB["educationalSpacesPoss"] = errorChecking((parkingOptionB["educationalMaxSf"]/1000)*physObj["educationParkPerArea"])
parkingOptionB["hotelSpacesPoss"] = errorChecking((physObj["hotelAreaPerRoom"] === 0 ? 0 :(parkingOptionB["hotelMaxSf"]/(physObj["hotelAreaPerRoom"]/advObj["hotelRentalPerc"]))*physObj["hotelParkPerRoom"]));
parkingOptionB["commercialParkingSpacesPoss"] = errorChecking((parkingOptionB["commercialParkingMaxSf"]/1000)*physObj["retailParkPerArea"])
parkingOptionB["totalSpaces"] = parkingOptionB["residentialSpacesPoss"] + parkingOptionB["retailSpacesPoss"] + parkingOptionB["officeSpacesPoss"] + parkingOptionB["industrialSpacesPoss"] + parkingOptionB["publicSpacesPoss"] + parkingOptionB["educationalSpacesPoss"] + parkingOptionB["hotelSpacesPoss"] + parkingOptionB["commercialParkingSpacesPoss"];
parkingOptionB["lessInternalParking"] = parkingOptionB["totalSpaces"] - parkingOptionB["commercialParkingSpacesPoss"] - parkingOptionB["internalParkingSpacesPoss"];
parkingOptionB["buildingFootprint"] = errorChecking(parkingOptionA_Aids["adjustmentIfOverEnvelope"]/physObj["buildingHeight"]);
parkingOptionB["lanscapeFootprint"] = landUses["landscaping"];
parkingOptionB["parkingFootprint"] = 0;
parkingOptionB["unusedFootprint"] = landUses["totalLotSize"] - parkingOptionB["parkingFootprint"]+parkingOptionB["lanscapeFootprint"]+parkingOptionB["buildingFootprint"];
//end parkingOptionB
//If Surface/Structured Parking
parkingOptionC["parkingMaxA"] = parkingOptionA_Aids["adjustedSpacesUnderground"]*physObj["parkingAreaPerSf"];
parkingOptionC["parkingMaxB"] = errorChecking(( (physObj["surfaceParkingLvls"]===0) ? 0 : (parkingOptionC["parkingMaxA"]/physObj["surfaceParkingLvls"]) ));
parkingOptionC["parkingMaxB_2"] = errorChecking((1000/physObj["buildingHeight"]));
parkingOptionC["buildingAvailable"] = errorChecking(parkingOptionA_Aids["aboveGradeParking"]/(parkingOptionC["parkingMaxB"]+parkingOptionC["parkingMaxB_2"]));
parkingOptionC["parkingAvailable"] = parkingOptionC["parkingMaxB"]*parkingOptionC["buildingAvailable"];
parkingOptionC["parkingAvailable_2"] = parkingOptionC["parkingMaxB_2"]*parkingOptionC["buildingAvailable"];
parkingOptionC["aboveGrade"] = (( physObj["surfaceParkingLvls"]>0 || (physObj["surfaceParkingLvls"]+physObj["undergroundParkingLvls"]+physObj["internalParkingLvls"]) === 0) ? 1 : 0);
parkingOptionC["aboveGradeFootprint"] = (parkingOptionC["aboveGrade"] === 1) ? parkingOptionC["parkingAvailable"] : 0;
parkingOptionC["buildingFootprintNeeded"] = ( parkingOptionC["aboveGrade"] === 1) ? parkingOptionC["parkingAvailable"] : 0;
parkingOptionC["adjustedTotalBuilding"] = (parkingOptionC["aboveGrade"] === 1) ? (parkingOptionC["aboveGrade"]+parkingOptionC["buildingFootprintNeeded"]) : parkingOptionC["aboveGrade"];
// parkingOptionC["aboveGradeParking"] = parkingOptionC["aboveGradeFootprint"];
parkingOptionC["unusedSpace"] = landUses["buildingNParking"]-(parkingOptionC["adjustedTotalBuilding"]+parkingOptionC["aboveGradeParking"]);
parkingOptionC["adjustedMaxBuilding"] = parkingOptionC["adjustedTotalBuilding"]*physObj["buildingHeight"]
parkingOptionC["buildingFootprint"] = parkingOptionC["adjustedTotalBuilding"];
parkingOptionC["lanscapeFootprint"] = landUses["landscaping"];
parkingOptionC["parkingFootprint"] = parkingOptionC["aboveGradeFootprint"];
parkingOptionC["unusedFootprint"] = parkingOptionC["unusedSpace"];
parkingOptionC_Aid1["internalParkingSf"] = errorChecking((parkingOptionC["adjustedMaxBuilding"]/physObj["buildingHeight"])*physObj["internalParkingLvls"]);
let optionCHelper = parkingOptionC["adjustedMaxBuilding"]-parkingOptionC_Aid1["internalParkingSf"];
let optionCHelper2 = parkingOptionC["aboveGrade"];
let optionCHelper3 = parkingOptionA_Aids["surplusOrDeficit"];
//Square Footage by Use (if surface/structured parking)
parkingOptionC_Aid1["residentialSf"] = (optionCHelper)*physObj["residentialUsePerc"];
parkingOptionC_Aid1["retailSf"] = (optionCHelper)*physObj["retailUsePerc"];
parkingOptionC_Aid1["officeSf"] = (optionCHelper)*physObj["officeUsePerc"];
parkingOptionC_Aid1["industrialSf"] = (optionCHelper)*physObj["industrialUsePerc"];
parkingOptionC_Aid1["publicSf"] = (optionCHelper)*physObj["publicUsePerc"];
parkingOptionC_Aid1["educationalSf"] =(optionCHelper)*physObj["educationUsePerc"];
parkingOptionC_Aid1["hotelSf"] = (optionCHelper)*physObj["hotelUsePerc"];
parkingOptionC_Aid1["commercialParkingSf"] = (optionCHelper)*physObj["parkingUsePerc"];
parkingOptionC_Aid1["totalSf"] = parkingOptionC_Aid1["internalParkingSf"] + parkingOptionC_Aid1["residentialSf"] + parkingOptionC_Aid1["retailSf"] + parkingOptionC_Aid1["officeSf"] + parkingOptionC_Aid1["industrialSf"] + parkingOptionC_Aid1["publicSf"] + parkingOptionC_Aid1["educationalSf"] + parkingOptionC_Aid1["hotelSf"] + parkingOptionC_Aid1["commercialParkingSf"];
parkingOptionC_Aid1["internalParkingSpaces"] = errorChecking(parkingOptionC_Aid1["internalParkingSf"]/physObj["parkingAreaPerSf"]);
parkingOptionC_Aid1["residentialSpaces"] = errorChecking((physObj["residentialUnitSize"]=== 0) ? 0 : (parkingOptionC_Aid1["residentialSf"]/(physObj["residentialUnitSize"]/maxBuildingEnvelope['residentialUnderbuild']))*physObj["residentialParkPerUnit"]);
parkingOptionC_Aid1["retailSpaces"] = errorChecking((parkingOptionC_Aid1["retailSf"]/1000)*physObj["retailParkPerArea"]);
parkingOptionC_Aid1["officeSpaces"] = errorChecking((parkingOptionC_Aid1["officeSf"]/1000)*physObj["officeParkPerArea"]);
parkingOptionC_Aid1["industrialSpaces"] = errorChecking((parkingOptionC_Aid1["industrialSf"]/1000)*physObj["industrialParkPerArea"]);
parkingOptionC_Aid1["publicSpaces"] = errorChecking((parkingOptionC_Aid1["publicSf"]/1000)*physObj["publicParkPerArea"]);
parkingOptionC_Aid1["educationalSpaces"] = errorChecking((parkingOptionC_Aid1["educationalSf"]/1000)*physObj["educationParkPerArea"])
parkingOptionC_Aid1["hotelSpaces"] = errorChecking((
(physObj["hotelAreaPerRoom"]===0) ? 0 : (parkingOptionC_Aid1["hotelSf"]/(physObj["hotelAreaPerRoom"]/advObj["hotelRentalPerc"]))*physObj["hotelParkPerRoom"]
));
parkingOptionC_Aid1["commercialParkingSpaces"] = errorChecking(parkingOptionC_Aid1["commercialParkingSf"]/physObj["parkingAreaPerSf"])
parkingOptionC_Aid1["totalSpaces"] = parkingOptionC_Aid1["residentialSpaces"] + parkingOptionC_Aid1["retailSpaces"] + parkingOptionC_Aid1["officeSpaces"] + parkingOptionC_Aid1["industrialSpaces"] + parkingOptionC_Aid1["publicSpaces"] + parkingOptionC_Aid1["educationalSpaces"] + parkingOptionC_Aid1["hotelSpaces"] + parkingOptionC_Aid1["commercialParkingSpaces"] + parkingOptionC_Aid1["internalParkingSpaces"];
parkingOptionC_Aid1["lessInternalParking"] = parkingOptionC_Aid1["totalSpaces"] - parkingOptionC_Aid1["internalParkingSpaces"] - parkingOptionC_Aid1["commercialParkingSpaces"];
//Square Footage by Use (without Underbuild)
parkingOptionC_Aid2["residentialSf"] = (optionCHelper2 >0) ? parkingOptionC_Aid1["residentialSf"] : parkingOptionB["residentialMaxSf"]
parkingOptionC_Aid2["residentialSpaces"] = (optionCHelper3 >=0) ? parkingOptionA["residentialSpacesPoss"] : parkingOptionC_Aid1["residentialSpaces"];
parkingOptionC_Aid2["retailSf"] = (optionCHelper2 >0) ? parkingOptionC_Aid1["retailSf"] : parkingOptionB["retailMaxSf"];
parkingOptionC_Aid2["retailSpaces"] = (optionCHelper3 >=0) ? parkingOptionA["retailSpacesPoss"] : parkingOptionC_Aid1["retailSpaces"];
parkingOptionC_Aid2["officeSf"] = (optionCHelper2 >0) ? parkingOptionC_Aid1["officeSf"] : parkingOptionB["officeMaxSf"];
parkingOptionC_Aid2["officeSpaces"] = (optionCHelper3 >=0) ? parkingOptionA["officeSpacesPoss"] : parkingOptionC_Aid1["officeSpaces"];
parkingOptionC_Aid2["industrialSf"] = (optionCHelper2 >0) ? parkingOptionC_Aid1["industrialSf"] : parkingOptionB["industrialMaxSf"];
parkingOptionC_Aid2["industrialSpaces"] = (optionCHelper3 >=0) ? parkingOptionA["industrialSpacesPoss"] : parkingOptionC_Aid1["industrialSpaces"];
parkingOptionC_Aid2["publicSf"] = (optionCHelper2 >0) ? parkingOptionC_Aid1["publicSf"] : parkingOptionB["publicMaxSf"];
parkingOptionC_Aid2["publicSpaces"] = (optionCHelper3 >=0) ? parkingOptionA["publicSpacesPoss"] : parkingOptionC_Aid1["publicSpaces"];
parkingOptionC_Aid2["educationalSf"] = (optionCHelper2 >0) ? parkingOptionC_Aid1["educationalSf"] : parkingOptionB["educationalMaxSf"];
parkingOptionC_Aid2["educationalSpaces"] = (optionCHelper3 >=0) ? parkingOptionA["educationalSpacesPoss"] : parkingOptionC_Aid1["educationalSpaces"];
parkingOptionC_Aid2["hotelSf"] = (optionCHelper2 >0) ? parkingOptionC_Aid1["hotelSf"] : parkingOptionB["hotelMaxSf"];
parkingOptionC_Aid2["hotelSpaces"] = (optionCHelper3 >=0) ? parkingOptionA["hotelSpacesPoss"] : parkingOptionC_Aid1["hotelSpaces"];
parkingOptionC_Aid2["commercialParkingSf"] = (optionCHelper2 >0) ? parkingOptionC_Aid1["commercialParkingSf"] : parkingOptionB["commercialParkingMaxSf"];
parkingOptionC_Aid2["commercialParkingSpaces"] = (optionCHelper3 >=0) ? parkingOptionA["commercialParkingSpacesPoss"] : parkingOptionC_Aid1["commercialParkingSpaces"];
parkingOptionC_Aid2["internalParkingSf"] = (optionCHelper2 >0) ? parkingOptionC_Aid1["internalParkingSf"] : parkingOptionB["internalParkingMaxSf"];
parkingOptionC_Aid2["internalParkingSpaces"] = (optionCHelper3 >=0) ? parkingOptionA["internalParkingSpacesPoss"] : parkingOptionC_Aid1["internalParkingSpaces"];
parkingOptionC_Aid2["totalSf"] = parkingOptionC_Aid2["residentialSf"] + parkingOptionC_Aid2["retailSf"] + parkingOptionC_Aid2["officeSf"] + parkingOptionC_Aid2["industrialSf"] + parkingOptionC_Aid2["publicSf"] + parkingOptionC_Aid2["educationalSf"] + parkingOptionC_Aid2["hotelSf"] + parkingOptionC_Aid2["commercialParkingSf"] + parkingOptionC_Aid2["internalParkingSf"];
//Square Footage by Use (with Underbuild)
parkingOptionC_Aid3["residentialSf"] = parkingOptionC_Aid2["residentialSf"]*physObj["underbuildPerc"];
parkingOptionC_Aid3["residentialSpaces"] = parkingOptionC_Aid2["residentialSpaces"]*physObj["underbuildPerc"];
parkingOptionC_Aid3["retailSf"] = parkingOptionC_Aid2["retailSf"]*physObj["underbuildPerc"];
parkingOptionC_Aid3["retailSpaces"] = parkingOptionC_Aid2["retailSpaces"] *physObj["underbuildPerc"];
parkingOptionC_Aid3["officeSf"] = parkingOptionC_Aid2["officeSf"]*physObj["underbuildPerc"];
parkingOptionC_Aid3["officeSpaces"] = parkingOptionC_Aid2["officeSpaces"]*physObj["underbuildPerc"];
parkingOptionC_Aid3["industrialSf"] = parkingOptionC_Aid2["industrialSf"]*physObj["underbuildPerc"];
parkingOptionC_Aid3["industrialSpaces"] = parkingOptionC_Aid2["industrialSpaces"]*physObj["underbuildPerc"];
parkingOptionC_Aid3["publicSf"] = parkingOptionC_Aid2["publicSf"]*physObj["underbuildPerc"];
parkingOptionC_Aid3["publicSpaces"] = parkingOptionC_Aid2["publicSpaces"]*physObj["underbuildPerc"];
parkingOptionC_Aid3["educationalSf"] = parkingOptionC_Aid2["educationalSf"]*physObj["underbuildPerc"];
parkingOptionC_Aid3["educationalSpaces"] = parkingOptionC_Aid2["educationalSpaces"]*physObj["underbuildPerc"];
parkingOptionC_Aid3["hotelSf"] = parkingOptionC_Aid2["hotelSf"] *physObj["underbuildPerc"];
parkingOptionC_Aid3["hotelSpaces"] = parkingOptionC_Aid2["hotelSpaces"]*physObj["underbuildPerc"];
parkingOptionC_Aid3["commercialParkingSf"] = parkingOptionC_Aid2["commercialParkingSf"] *physObj["underbuildPerc"];
parkingOptionC_Aid3["commercialParkingSpaces"] = parkingOptionC_Aid2["commercialParkingSpaces"] *physObj["underbuildPerc"];
parkingOptionC_Aid3["internalParkingSf"] = parkingOptionC_Aid2["internalParkingSf"]*physObj["underbuildPerc"];
parkingOptionC_Aid3["internalParkingSpaces"] = errorChecking(parkingOptionC_Aid3["internalParkingSf"]/physObj["parkingAreaPerSf"]);
parkingOptionC_Aid3["totalSf"] = parkingOptionC_Aid3["residentialSf"] + parkingOptionC_Aid3["retailSf"] + parkingOptionC_Aid3["officeSf"] + parkingOptionC_Aid3["industrialSf"] + parkingOptionC_Aid3["publicSf"] + parkingOptionC_Aid3["educationalSf"] + parkingOptionC_Aid3["hotelSf"] + parkingOptionC_Aid3["commercialParkingSf"] + parkingOptionC_Aid3["internalParkingSf"];
parkingOptionC_Aid3["totalSpaces"] = parkingOptionC_Aid3["residentialSpaces"] + parkingOptionC_Aid3["retailSpaces"] + parkingOptionC_Aid3["officeSpaces"] + parkingOptionC_Aid3["industrialSpaces"] + parkingOptionC_Aid3["publicSpaces"] + parkingOptionC_Aid3["educationalSpaces"] + parkingOptionC_Aid3["hotelSpaces"];
// Site Summary
// Pre-Underbuild
preUnderbuild["buildingFootprint"] = (optionCHelper2>0) ? parkingOptionC["buildingFootprint"] : parkingOptionB["buildingFootprint"]; //b151
preUnderbuild["lanscapeFootprint"] = (optionCHelper2>0) ? parkingOptionC["lanscapeFootprint"] : parkingOptionB["lanscapeFootprint"]; //b152
preUnderbuild["parkingFootprint"] = (optionCHelper2>0) ? parkingOptionC["parkingFootprint"] : parkingOptionB["parkingFootprint"]; //b153
preUnderbuild["unusedFootprint"] = (optionCHelper2>0) ? parkingOptionC["unusedFootprint"] : parkingOptionB["unusedFootprint"]; //b154
//Adjustment Factors
parkingOptionC_Aid5["unusedFootprint"] = preUnderbuild["unusedFootprint"]; //b127
parkingOptionC_Aid5["bldgFootprint"] = errorChecking(1000/physObj["buildingHeight"]/physObj["underbuildPerc"]); //b128
parkingOptionC_Aid5["bldgParkingFootprint"] = parkingOptionC_Aid5["bldgFootprint"]+parkingOptionC["parkingMaxB"] //b129
parkingOptionC_Aid5["additionalArea"] = errorChecking(1000*parkingOptionC_Aid5["unusedFootprint"]/parkingOptionC_Aid5["bldgParkingFootprint"]) //b130
parkingOptionC_Aid5["additionalFootprint"] = errorChecking(parkingOptionC_Aid5["bldgFootprint"]*(parkingOptionC_Aid5["additionalArea"]/1000)) //b131
parkingOptionC_Aid5["additionalParking"] = errorChecking(parkingOptionC["parkingMaxB"]*parkingOptionC_Aid5["additionalArea"]/1000) //b132
parkingOptionC_Aid5["adjustedVolume"] = parkingOptionC_Aid3["totalSf"]+parkingOptionC_Aid5["additionalArea"] //b133
parkingOptionC_Aid5["adjustedSpaces"] = errorChecking(parkingOptionC_Aid3["totalSpaces"]+(parkingOptionC_Aid5["additionalParking"]/physObj["parkingAreaPerSf"])) //b134
let optionCHelper4 = errorChecking(parkingOptionC_Aid5["adjustedVolume"]/parkingOptionC_Aid3["totalSf"]);
//Square Footage by Use (Adjusted)
parkingOptionC_Aid4["residentialSf"] = parkingOptionC_Aid3["residentialSf"]*(optionCHelper4) //b138
parkingOptionC_Aid4["residentialSpaces"] = parkingOptionC_Aid3["residentialSpaces"]*(optionCHelper4) //c138
parkingOptionC_Aid4["retailSf"] = parkingOptionC_Aid3["retailSf"]*(optionCHelper4) //b139
parkingOptionC_Aid4["retailSpaces"] = parkingOptionC_Aid3["retailSpaces"]*(optionCHelper4)
parkingOptionC_Aid4["officeSf"] = parkingOptionC_Aid3["officeSf"]*(optionCHelper4) //b140
parkingOptionC_Aid4["officeSpaces"] = parkingOptionC_Aid3["officeSpaces"]*(optionCHelper4)
parkingOptionC_Aid4["industrialSf"] = parkingOptionC_Aid3["industrialSf"]*(optionCHelper4) //b141
parkingOptionC_Aid4["industrialSpaces"] = parkingOptionC_Aid3["industrialSpaces"]*(optionCHelper4)
parkingOptionC_Aid4["publicSf"] = parkingOptionC_Aid3["publicSf"]*(optionCHelper4) //b142
parkingOptionC_Aid4["publicSpaces"] = parkingOptionC_Aid3["publicSpaces"]*(optionCHelper4)
parkingOptionC_Aid4["educationalSf"] = parkingOptionC_Aid3["educationalSf"]*(optionCHelper4) //b143
parkingOptionC_Aid4["educationalSpaces"] = parkingOptionC_Aid3["educationalSpaces"]*(optionCHelper4)
parkingOptionC_Aid4["hotelSf"] = parkingOptionC_Aid3["hotelSf"]*(optionCHelper4) //b144
parkingOptionC_Aid4["hotelSpaces"] = parkingOptionC_Aid3["hotelSpaces"]*(optionCHelper4)
parkingOptionC_Aid4["commercialParkingSf"] = parkingOptionC_Aid3["commercialParkingSf"]*(optionCHelper4) //b145
parkingOptionC_Aid4["commercialParkingSpaces"] = parkingOptionC_Aid3["commercialParkingSpaces"]*(optionCHelper4)
parkingOptionC_Aid4["internalParkingSf"] = parkingOptionC_Aid3["internalParkingSf"]*(optionCHelper4)
parkingOptionC_Aid4["internalParkingSpaces"] = parkingOptionC_Aid3["internalParkingSpaces"]*(optionCHelper4)
parkingOptionC_Aid4["totalSf"] = parkingOptionC_Aid4["residentialSf"] + parkingOptionC_Aid4["retailSf"] + parkingOptionC_Aid4["officeSf"] + parkingOptionC_Aid4["industrialSf"] + parkingOptionC_Aid4["publicSf"] + parkingOptionC_Aid4["educationalSf"] + parkingOptionC_Aid4["hotelSf"] + parkingOptionC_Aid4["commercialParkingSf"] + parkingOptionC_Aid4["internalParkingSf"];
parkingOptionC_Aid4["totalSpaces"] = parkingOptionC_Aid4["residentialSpaces"] + parkingOptionC_Aid4["officeSpaces"] + parkingOptionC_Aid4["retailSpaces"] + parkingOptionC_Aid4["industrialSpaces"] + parkingOptionC_Aid4["publicSpaces"] + parkingOptionC_Aid4["educationalSpaces"] + parkingOptionC_Aid4["hotelSpaces"];
//end parkingOptionC
// Site Summary
// Post-Underbuild
postUnderbuild["buildingFootprint"] = preUnderbuild["buildingFootprint"] //b158
postUnderbuild["lanscapeFootprint"] = preUnderbuild["lanscapeFootprint"] //b159
postUnderbuild["parkingFootprint"] = preUnderbuild["parkingFootprint"]*physObj["underbuildPerc"] //b160
postUnderbuild["unusedFootprint"] = physObj["siteArea"]-(postUnderbuild["buildingFootprint"]+postUnderbuild["lanscapeFootprint"]+postUnderbuild["parkingFootprint"])-landUses["streets"] //b161
// Adjusted
adjustedSummary["buildingFootprint"] = postUnderbuild["buildingFootprint"] + parkingOptionC_Aid5["additionalFootprint"] //b164
adjustedSummary["lanscapeFootprint"] = postUnderbuild["lanscapeFootprint"] //b165
adjustedSummary["parkingFootprint"] = parkingOptionC_Aid5["additionalParking"]+postUnderbuild["parkingFootprint"] //b166
adjustedSummary["unusedFootprint"] = 0; //b167
let optionCHelper5 = parkingOptionC_Aid4["residentialSpaces"] + parkingOptionC_Aid4["retailSpaces"] + parkingOptionC_Aid4["officeSpaces"] + parkingOptionC_Aid4["industrialSpaces"] + parkingOptionC_Aid4["publicSpaces"] + parkingOptionC_Aid4["educationalSpaces"] + parkingOptionC_Aid4["hotelSpaces"];
//Parking Space Adjustments
adjustedParkingSpaces["residentialRequired"] = parkingOptionC_Aid4["residentialSpaces"]
adjustedParkingSpaces["retailRequired"] = parkingOptionC_Aid4["retailSpaces"]
adjustedParkingSpaces["officeRequired"] = parkingOptionC_Aid4["officeSpaces"]
adjustedParkingSpaces["industrialRequired"] = parkingOptionC_Aid4["industrialSpaces"]
adjustedParkingSpaces["publicRequired"] = parkingOptionC_Aid4["publicSpaces"]
adjustedParkingSpaces["educationalRequired"] = parkingOptionC_Aid4["educationalSpaces"]
adjustedParkingSpaces["hotelRequired"] = parkingOptionC_Aid4["hotelSpaces"]
adjustedParkingSpaces["structuredProvided"] = errorChecking((parkingOptionC["aboveGrade"]>0) ? ((adjustedSummary["parkingFootprint"]*physObj["surfaceParkingLvls"])/physObj["parkingAreaPerSf"]) : 0 );
adjustedParkingSpaces["undergroundProvided"] = parkingOptionA_Aids["undergroundParkingProvided"]
adjustedParkingSpaces["commercialProvided"] = parkingOptionC_Aid4["commercialParkingSpaces"]
adjustedParkingSpaces["commercialRequired"] = parkingOptionC_Aid4["commercialParkingSpaces"]
adjustedParkingSpaces["internalProvided"] = parkingOptionC_Aid4["internalParkingSpaces"]
adjustedParkingSpaces["totalProvided"] = adjustedParkingSpaces["structuredProvided"] + adjustedParkingSpaces["undergroundProvided"] + adjustedParkingSpaces["internalProvided"];
adjustedParkingSpaces["totalRequired"] = (physObj["undergroundParkingLvls"]+physObj["surfaceParkingLvls"]+physObj["internalParkingLvls"] === 0) ? 0 : optionCHelper5
adjustedParkingSpaces["totalExcess"] = adjustedParkingSpaces["totalProvided"]-adjustedParkingSpaces["totalRequired"]
adjustedSpaces["underground"] = ((parkingOptionA_Aids["undergroundParkingProvided"] - adjustedParkingSpaces["totalExcess"]) > 0) ? (parkingOptionA_Aids["undergroundParkingProvided"] - adjustedParkingSpaces["totalExcess"] ) : 0 //b171
adjustedSpaces["commercialParking"] = parkingOptionC_Aid4["commercialParkingSpaces"] //b172
adjustedSpaces["internal"] = parkingOptionC_Aid4["internalParkingSpaces"] //b173
adjustedSpaces["surface"] = (adjustedParkingSpaces["totalRequired"]>(adjustedSpaces["underground"] + adjustedSpaces["internal"])) ? (adjustedParkingSpaces["totalRequired"]-(adjustedSpaces["underground"] + adjustedSpaces["internal"])) : 0 //b170
adjustedParkingFootprint["surfaceArea"] = adjustedSpaces["surface"]*physObj["parkingAreaPerSf"] //b192
adjustedParkingFootprint["surfaceFootprint"] = errorChecking((adjustedParkingFootprint["surfaceArea"] < physObj["parkingAreaPerSf"]) ? 0 : (adjustedParkingFootprint["surfaceArea"] / physObj["surfaceParkingLvls"]))
adjustedParkingFootprint["undergroundArea"] = 0; //b193
adjustedParkingFootprint["undergroundFootprint"] = errorChecking((adjustedSpaces["underground"]*physObj["parkingAreaPerSf"])/landUses["totalLotSize"]) //c193
updateDevelopmentCosts( physObj, basObj, advObj );
}
export const updateMathModule = (obj) => {
let physObj = _.mapValues(obj.physicalInfo, function(o) { return ( isNaN(o) ? o : Number(o) ) });
let basObj = _.mapValues(obj.basicFinInfo, function(o) { return ( isNaN(o) ? o : Number(o) ) });
let advObj = _.mapValues(obj.advFinInfo, function(o) { return ( isNaN(o) ? o : Number(o) ) });
// console.log(physObj);
updateBuildingEnvelope( physObj, basObj, advObj );
// updateDevelopmentCosts( physObj, basObj, advObj );
// updateMixedUseSummary( physObj, basObj, advObj );
// updatePhysicalOutputs(physObj, basObj, advObj );
}
export const buildingLotCoverage = (siteArea) => {
// console.log(adjustedSummary['buildingFootprint']);
let finalLotCoverage = errorChecking(adjustedSummary['buildingFootprint'] / siteArea);
return finalLotCoverage;
};
export const landscapeLotCoverage = (siteArea) => {
let finalLandscapeCoverage = errorChecking(adjustedSummary["lanscapeFootprint"]/siteArea);
return finalLandscapeCoverage;
};
export const parkingLotCoverage = (siteArea) => {
let finalParkingCoverage = errorChecking(adjustedSummary["parkingFootprint"]/siteArea);
return finalParkingCoverage;
};
let grossSfTotal = 0;
export const getFAR = (siteArea, advFinInfo) => {
let { retailRentalPerc, officeRentalPerc, industrialRentalPerc, publicRentalPerc, educationRentalPerc, hotelRentalPerc, parkingRentalPerc } = advFinInfo;
// console.log(parkingOptionC_Aid4);
// console.log(maxBuildingEnvelope["residentialUnderbuild"]);
// console.log(retailRentalPerc, officeRentalPerc, industrialRentalPerc, publicRentalPerc, educationRentalPerc, hotelRentalPerc, parkingRentalPerc);
grossSfTotal =
(parkingOptionC_Aid4["residentialSf"]*maxBuildingEnvelope["residentialUnderbuild"]) +
(parkingOptionC_Aid4["retailSf"]*retailRentalPerc) +
(parkingOptionC_Aid4["officeSf"]*officeRentalPerc) +
(parkingOptionC_Aid4["industrialSf"]*industrialRentalPerc) +
(parkingOptionC_Aid4["publicSf"]*publicRentalPerc) +
(parkingOptionC_Aid4["educationalSf"]*educationRentalPerc) +
(parkingOptionC_Aid4["hotelSf"]*hotelRentalPerc) +
(parkingOptionC_Aid4["commercialParkingSf"]*parkingRentalPerc) +
(adjustedParkingFootprint["surfaceArea"]-adjustedParkingFootprint["surfaceFootprint"]);
// console.log("grossSfTotal ", grossSfTotal)
// console.log("siteArea ", siteArea)
return errorChecking(grossSfTotal/siteArea);
}
export const getTotalSf = ( ) => {
return grossSfTotal;
}
export const getResidentialSfMix = () => {
return errorChecking(parkingOptionC_Aid4["residentialSf"]/grossSfTotal);
}
export const getRetailSfMix = () => {
return errorChecking(parkingOptionC_Aid4["retailSf"]/grossSfTotal);
}
export const getOfficeSfMix = () => {
return errorChecking(parkingOptionC_Aid4["officeSf"]/grossSfTotal);
}
export const getIndustrialSfMix = () => {
return errorChecking(parkingOptionC_Aid4["industrialSf"]/grossSfTotal);
}
export const getPublicSfMix = () => {
return errorChecking(parkingOptionC_Aid4["publicSf"]/grossSfTotal);
}
export const getEducationalSfMix = () => {
return errorChecking(parkingOptionC_Aid4["educationalSf"]/grossSfTotal);
}
export const getHotelSfMix = () => {
return errorChecking(parkingOptionC_Aid4["hotelSf"]/grossSfTotal);
}
export const getCommercialParkingSfMix = () => {
return errorChecking(parkingOptionC_Aid4["commercialParkingSf"]/grossSfTotal);
}
export const getInternalParkingSfMix = () => {
return errorChecking((adjustedParkingFootprint["surfaceArea"]-adjustedParkingFootprint["surfaceFootprint"]+parkingOptionC_Aid4["internalParkingSf"])/grossSfTotal);
}
export const getResidentialNetUnit = (residentialUnitSize) => {
let c28 = parkingOptionC_Aid4["residentialSf"]*maxBuildingEnvelope["residentialUnderbuild"];
let d28 = errorChecking((residentialUnitSize === 0) ? 0 : c28/residentialUnitSize);
return ( (c28 === 0) ? 0 : c28/d28 );
}
export const getResidentialGrossUnit = (residentialUnitSize) => {
let b28 = parkingOptionC_Aid4["residentialSf"];
let c28 = parkingOptionC_Aid4["residentialSf"]*maxBuildingEnvelope["residentialUnderbuild"];
let d28 = (residentialUnitSize === 0) ? 0 : c28/residentialUnitSize;
return ( (b28 === 0) ? 0 :b28/d28)
}
export const getResidentialDwellUnit = (physicalInfo, advFinInfo) => {
let { siteArea, residentialUnitSize, hotelAreaPerRoom, parkingAreaPerEmp } = physicalInfo;
let { hotelRentalPerc, parkingRentalPerc } = advFinInfo;
let c28 = parkingOptionC_Aid4["residentialSf"]*maxBuildingEnvelope["residentialUnderbuild"];
let c34 = parkingOptionC_Aid4["hotelSf"]*hotelRentalPerc;
let c35 = parkingOptionC_Aid4["commercialParkingSf"]*parkingRentalPerc;
let siteAreaAcre = siteArea / 43560;
let total = errorChecking(
(((residentialUnitSize === 0) ? 0 : c28/residentialUnitSize) / siteAreaAcre) +
(((hotelAreaPerRoom === 0) ? 0 : c34/residentialUnitSize) / siteAreaAcre) +
(((parkingAreaPerEmp === 0) ? 0 : c35/residentialUnitSize) / siteAreaAcre) );
return total;
}
export const getHouseholdAffordability = (physicalInfo, basicFinInfo) => {
let { occupancyType } = physicalInfo;
let { monthlyRentPerSf } = basicFinInfo;
let perc = (occupancyType === 'Renter' ?
// ($'Input Calculators'.B59 === monthlyRentPerSf ? $'Input Calculators'.C42 : 0)
(residentialRentEstimator["avgMonthlyRentCalc"] === monthlyRentPerSf ? residentialUnitSizeEst["affordPerc"] : 0)
: 0);
return perc;
}
export const getHouseholdEstIncome = (physicalInfo, basicFinInfo) =>{
let { monthlyRentPerSf, salesPricePerSf } = basicFinInfo;
let { occupancyType, residentialUnitSize } = physicalInfo;
if (occupancyType === 'Renter' ){
return getResidentialNetUnit(residentialUnitSize)*monthlyRentPerSf*12*3;
} else if (occupancyType === 'Owner' ){
return getResidentialNetUnit(residentialUnitSize)*salesPricePerSf*0.006*12*3;
} else {
return ( (getResidentialNetUnit(residentialUnitSize)*monthlyRentPerSf*12*3) + (getResidentialNetUnit(residentialUnitSize)*salesPricePerSf*0.006*12*3))/2
}
}
export const getJobsPerSf = (physicalInfo) => {
let { siteArea, retailAreaPerEmp, officeAreaPerEmp, industrialAreaPerEmp, publicAreaPerEmp, educationAreaPerEmp, hotelAreaPerEmp, parkingAreaPerEmp } = physicalInfo;
// console.log(hotelAreaPerEmp)
// console.log(parkingOptionC_Aid4["industrialSf"])
// console.log(siteArea)
let g29 = (retailAreaPerEmp === 0 ? 0 : (parkingOptionC_Aid4["retailSf"]/retailAreaPerEmp)/siteArea);
let g30 = (officeAreaPerEmp === 0 ? 0 : (parkingOptionC_Aid4["officeSf"]/officeAreaPerEmp)/siteArea);
let g31 = (industrialAreaPerEmp === 0 ? 0 : (parkingOptionC_Aid4["industrialSf"]/industrialAreaPerEmp)/siteArea);
let g32 = (publicAreaPerEmp === 0 ? 0 : (parkingOptionC_Aid4["publicSf"]/publicAreaPerEmp)/siteArea);
let g33 = (educationAreaPerEmp === 0 ? 0 : (parkingOptionC_Aid4["educationalSf"]/educationAreaPerEmp)/siteArea);
let g34 = (hotelAreaPerEmp === 0 ? 0 : (parkingOptionC_Aid4["hotelSf"]/hotelAreaPerEmp)/siteArea);
let g35 = (parkingAreaPerEmp === 0 ? 0 : (parkingOptionC_Aid4["commercialParkingSf"]/parkingAreaPerEmp)/siteArea);
// console.log(g31)
let jpa = g29+g30+g31+g32+g33+g34+g35;
// console.log(jpa)
return jpa;
}
export const getHotelEmpPerSf = (physicalInfo, advFinInfo) => {
let { hotelAreaPerRoom } = physicalInfo;
let { hotelRentalPerc } = advFinInfo;
return ( hotelAreaPerRoom === 0 ? 0 : (parkingOptionC_Aid4["hotelSf"]*hotelRentalPerc)/hotelAreaPerRoom);
}
export const getHotelNetPerSf = (physicalInfo, advFinInfo) => {
let { hotelAreaPerRoom } = physicalInfo;
let { hotelRentalPerc } = advFinInfo;
let c34 = parkingOptionC_Aid4["hotelSf"]*hotelRentalPerc;
let d34 = (hotelAreaPerRoom === 0) ? 0 : c34/hotelAreaPerRoom;
if ( c34 === 0 ){
return 0;
} else {
return (c34 / d34);
}
}
export const getHotelGrossPerSf = (physicalInfo, advFinInfo) => {
let { hotelAreaPerRoom } = physicalInfo;
let { hotelRentalPerc } = advFinInfo;
let c34 = parkingOptionC_Aid4["hotelSf"]*hotelRentalPerc;
let d34 = (hotelAreaPerRoom === 0) ? 0 : c34/hotelAreaPerRoom;
if ( parkingOptionC_Aid4["hotelSf"] === 0 ){
return 0;
} else {
return (parkingOptionC_Aid4["hotelSf"] / d34);
}
}
export const getParkingSpaces = () => {
return parkingOptionC_Aid4["totalSpaces"];
}
export const getParkingSf = (physicalInfo) =>{
let { parkingAreaPerSf } = physicalInfo;
return parkingOptionC_Aid4["totalSpaces"]*parkingAreaPerSf;
}
export const getInternalStructureParkingSf = () => {
// console.log(adjustedParkingFootprint["surfaceArea"],adjustedParkingFootprint["surfaceFootprint"],parkingOptionC_Aid4["internalParkingSf"]);
let b36 = adjustedParkingFootprint["surfaceArea"]-adjustedParkingFootprint["surfaceFootprint"];
let b37 = parkingOptionC_Aid4["internalParkingSf"];
// console.log(b36+b37)
return b36+b37;
}
let siteLevelOutputs = {
buildingFootprintSf: 0,
landscapingFootprintSf: 0,
parkingByBuildingSf: 0,
netToGrossReductionSf: 0,
useableBuildingTotalSf: 0,
buildingFootprintPerc: 0,
landscapingFootprintPerc: 0,
parkingByBuildingPerc: 0,
netToGrossReductionPerc: 0
}
let totalGrossSf = {
residential: 0,
retail: 0,
office: 0,
industrial: 0,
public: 0,
educational: 0,
hotel: 0,
commercialParking: 0,
structuredParking: 0,
internalParking: 0,
total: 0
}
let totalNetSf = {
residential: 0,
retail: 0,
office: 0,
industrial: 0,
public: 0,
educational: 0,
hotel: 0,
commercialParking: 0,
structuredParking: 0,
internalParking: 0,
total: 0
}
let totalDwellingOrHotelUnits = {
residential: 0,
hotel: 0,
commercialParking: 0,
total: 0
}
let totalJobsByLandUse = {
retail: 0,
office: 0,
industrial: 0,
public: 0,
educational: 0,
hotel: 0,
commercialParking: 0,
total: 0
}
let parkingSpacesByLandUse = {
residentialSpaces: 0,
retailSpaces: 0,
officeSpaces: 0,
industrialSpaces: 0,
publicSpaces: 0,
educationalSpaces: 0,
hotelSpaces: 0,
commercialParkingSpaces: 0,
totalSpaces: 0,
residentialSf: 0,
retailSf: 0,
officeSf: 0,
industrialSf: 0,
publicSf: 0,
educationalSf: 0,
hotelSf: 0,
commercialParkingSf: 0,
totalSf: 0
}
let parkingSpacesByType = {
surface: 0,
structure: 0,
underground: 0,
commercial: 0,
internal: 0
}
export const updatePhysicalOutputs = ( physicalInfo, basicFinInfo, advFinInfo ) => {
let { siteArea, siteNetToGross } = physicalInfo;
siteLevelOutputs["buildingFootprintSf"] = adjustedSummary["buildingFootprint"];
siteLevelOutputs["landscapingFootprintSf"] = adjustedSummary["lanscapeFootprint"];
siteLevelOutputs["parkingByBuildingSf"] = adjustedSummary["parkingFootprint"];
siteLevelOutputs["netToGrossReductionSf"] = siteArea*(1 - siteNetToGross);
let siteTotal = siteLevelOutputs["buildingFootprintSf"] + siteLevelOutputs["landscapingFootprintSf"] + siteLevelOutputs["parkingByBuildingSf"] + siteLevelOutputs["netToGrossReductionSf"];
siteLevelOutputs["buildingFootprintPerc"] = errorChecking(siteLevelOutputs["buildingFootprintSf"]/siteTotal);
siteLevelOutputs["landscapingFootprintPerc"] = errorChecking(siteLevelOutputs["landscapingFootprintSf"]/siteTotal);
siteLevelOutputs["parkingByBuildingPerc"] = errorChecking(siteLevelOutputs["parkingByBuildingSf"]/siteTotal);
siteLevelOutputs["netToGrossReductionPerc"] = errorChecking(siteLevelOutputs["netToGrossReductionSf"]/siteTotal);
totalGrossSf["residential"] = parkingOptionC_Aid4["residentialSf"];
totalGrossSf["retail"] = parkingOptionC_Aid4["retailSf"];
totalGrossSf["office"] = parkingOptionC_Aid4["officeSf"];
totalGrossSf["industrial"] = parkingOptionC_Aid4["industrialSf"];
totalGrossSf["public"] = parkingOptionC_Aid4["publicSf"];
totalGrossSf["educational"] = parkingOptionC_Aid4["educationalSf"];
totalGrossSf["hotel"] = parkingOptionC_Aid4["hotelSf"];
totalGrossSf["commercialParking"] = parkingOptionC_Aid4["commercialParkingSf"];
totalGrossSf["structuredParking"] = adjustedParkingFootprint["surfaceArea"] - adjustedParkingFootprint["surfaceFootprint"];
totalGrossSf["internalParking"] = parkingOptionC_Aid4["internalParkingSf"];
let { retailRentalPerc, officeRentalPerc, industrialRentalPerc,
publicRentalPerc, educationRentalPerc, hotelRentalPerc, parkingRentalPerc } = advFinInfo;
totalNetSf["residential"] = totalGrossSf["residential"]*maxBuildingEnvelope["residentialUnderbuild"];
totalNetSf["retail"] = totalGrossSf["retail"]*retailRentalPerc;
totalNetSf["office"] = totalGrossSf["office"]*officeRentalPerc;
totalNetSf["industrial"] = totalGrossSf["industrial"]*industrialRentalPerc;
totalNetSf["public"] = totalGrossSf["public"]*publicRentalPerc;
totalNetSf["educational"] = totalGrossSf["educational"]*educationRentalPerc;
totalNetSf["hotel"] = totalGrossSf["hotel"]*hotelRentalPerc;
totalNetSf["commercialParking"] = totalGrossSf["commercialParking"]*parkingRentalPerc;
totalNetSf["structuredParking"] = totalGrossSf["structuredParking"];
totalNetSf["internalParking"] = totalGrossSf["internalParking"];
let { residentialUnitSize, hotelAreaPerRoom, parkingAreaPerEmp,
retailAreaPerEmp, officeAreaPerEmp, industrialAreaPerEmp, publicAreaPerEmp,
educationAreaPerEmp, hotelAreaPerEmp, parkingAreaPerSf } = physicalInfo;
totalDwellingOrHotelUnits["residential"] = errorChecking((residentialUnitSize === 0 ? 0 : totalNetSf["residential"]/residentialUnitSize));
totalDwellingOrHotelUnits["hotel"] = errorChecking((hotelAreaPerRoom === 0 ? 0 : totalNetSf["hotel"]/hotelAreaPerRoom));
totalDwellingOrHotelUnits["commercialParking"] = errorChecking((parkingAreaPerEmp === 0 ? 0 : totalNetSf["commercialParking"]/parkingAreaPerEmp));
totalDwellingOrHotelUnits["total"] = totalDwellingOrHotelUnits["residential"]+totalDwellingOrHotelUnits["hotel"]+totalDwellingOrHotelUnits["commercialParking"];
totalJobsByLandUse["retail"] = errorChecking((retailAreaPerEmp === 0 ? 0 : totalGrossSf["retail"]/retailAreaPerEmp));
totalJobsByLandUse["office"] = errorChecking((officeAreaPerEmp === 0 ? 0 : totalGrossSf["office"]/officeAreaPerEmp));
totalJobsByLandUse["industrial"] = errorChecking((industrialAreaPerEmp === 0 ? 0 : totalGrossSf["industrial"]/industrialAreaPerEmp));
totalJobsByLandUse["public"] = errorChecking((publicAreaPerEmp === 0 ? 0 : totalGrossSf["public"]/publicAreaPerEmp));
totalJobsByLandUse["educational"] = errorChecking((educationAreaPerEmp === 0 ? 0 : totalGrossSf["educational"]/educationAreaPerEmp));
totalJobsByLandUse["hotel"] = errorChecking((hotelAreaPerEmp === 0 ? 0 : totalGrossSf["hotel"]/hotelAreaPerEmp));
totalJobsByLandUse["commercialParking"] = errorChecking((parkingAreaPerEmp === 0 ? 0 : totalGrossSf["commercialParking"]/parkingAreaPerEmp));
totalJobsByLandUse["total"] = totalJobsByLandUse["retail"] +totalJobsByLandUse["office"]+totalJobsByLandUse["industrial"]+totalJobsByLandUse["public"]+totalJobsByLandUse["educational"] +totalJobsByLandUse["hotel"]+totalJobsByLandUse["commercialParking"]
let b36 = adjustedParkingFootprint["surfaceArea"]-adjustedParkingFootprint["surfaceFootprint"];
let z3 = errorChecking(adjustedSpaces["surface"]*adjustedParkingFootprint["surfaceFootprint"]/adjustedParkingFootprint["surfaceArea"]);
let z2 = errorChecking(adjustedSpaces["surface"]*b36/adjustedParkingFootprint["surfaceArea"]);
parkingSpacesByType["surface"] = ( z3 === 0 ? 0 : z3);
parkingSpacesByType["structure"] = ( z2 === 0 ? 0 : z2);
parkingSpacesByType["underground"] = adjustedSpaces["underground"]
parkingSpacesByType["commercial"] = adjustedSpaces["commercialParking"]
parkingSpacesByType["internal"] = adjustedSpaces["internal"]
parkingSpacesByLandUse["residentialSpaces"] = parkingOptionC_Aid4["residentialSpaces"];
parkingSpacesByLandUse["retailSpaces"] = parkingOptionC_Aid4["retailSpaces"];
parkingSpacesByLandUse["officeSpaces"] = parkingOptionC_Aid4["officeSpaces"];
parkingSpacesByLandUse["industrialSpaces"] = parkingOptionC_Aid4["industrialSpaces"];
parkingSpacesByLandUse["publicSpaces"] = parkingOptionC_Aid4["publicSpaces"];
parkingSpacesByLandUse["educationalSpaces"] = parkingOptionC_Aid4["educationalSpaces"];
parkingSpacesByLandUse["hotelSpaces"] = parkingOptionC_Aid4["hotelSpaces"];
parkingSpacesByLandUse["commercialParkingSpaces"] = parkingOptionC_Aid4["commercialParkingSpaces"];
parkingSpacesByLandUse["totalSpaces"] = parkingSpacesByLandUse["residentialSpaces"] + parkingSpacesByLandUse["retailSpaces"] + parkingSpacesByLandUse["officeSpaces"] + parkingSpacesByLandUse["industrialSpaces"] + parkingSpacesByLandUse["publicSpaces"] + parkingSpacesByLandUse["educationalSpaces"] + parkingSpacesByLandUse["hotelSpaces"] + parkingSpacesByLandUse["commercialParkingSpaces"]
parkingSpacesByLandUse["residentialSf"] = parkingAreaPerSf*parkingSpacesByLandUse["residentialSpaces"]
parkingSpacesByLandUse["retailSf"] = parkingAreaPerSf*parkingSpacesByLandUse["retailSpaces"]
parkingSpacesByLandUse["officeSf"] = parkingAreaPerSf*parkingSpacesByLandUse["officeSpaces"]
parkingSpacesByLandUse["industrialSf"] = parkingAreaPerSf*parkingSpacesByLandUse["industrialSpaces"]
parkingSpacesByLandUse["publicSf"] = parkingAreaPerSf*parkingSpacesByLandUse["publicSpaces"]
parkingSpacesByLandUse["educationalSf"] = parkingAreaPerSf*parkingSpacesByLandUse["educationalSpaces"]
parkingSpacesByLandUse["hotelSf"] = parkingAreaPerSf*parkingSpacesByLandUse["hotelSpaces"]
parkingSpacesByLandUse["commercialParkingSf"] = parkingAreaPerSf*parkingSpacesByLandUse["commercialParkingSpaces"]
parkingSpacesByLandUse["totalSf"] = parkingSpacesByLandUse["residentialSf"] + parkingSpacesByLandUse["retailSf"] + parkingSpacesByLandUse["officeSf"] + parkingSpacesByLandUse["industrialSf"] + parkingSpacesByLandUse["publicSf"] + parkingSpacesByLandUse["educationalSf"] + parkingSpacesByLandUse["hotelSf"] + parkingSpacesByLandUse["commercialParkingSf"];
// console.log('update physical outputs done...')
}
// PROJECT DEVELOPMENT COSTS
// Pre Development Costs
let preDevelopmentCosts = {
dueDiligence: 0,
landCarry: 0,
landEntitlement: 0,
professionalFees: 0,
rawLand: 0
}
// Development Costs
let developmentCosts = {
demolition: 0,
siteDevelopment: 0,
brownfieldRemediation: 0,
residentialConstruction: 0,
retailConstruction: 0,
officeConstruction: 0,
industrialConstruction: 0,
publicConstruction: 0,
educationConstruction: 0,
hotelConstruction: 0,
additionalInfrastructure: 0,
parkingConstruction: 0,
waterQualityControls: 0,
impactFees: 0,
buildingPermits: 0,
insuranceDuringConstruction: 0,
taxesDuringConstruction: 0
}
// Developer Fee
// Contingency
let develpomentFees = {
developer: 0,
contigency: 0
}
let developmentTotals = {
buildingConstruction: 0,
parkingConstruction: 0,
totalProjectCosts: 0
}
let costAllocation = {
residential: {
devAndLand: 0,
parking: 0,
total: 0
},
retail: {
devAndLand: 0,
parking: 0,
total: 0
},
office: {
devAndLand: 0,
parking: 0,
total: 0
},
industrial: {
devAndLand: 0,
parking: 0,
total: 0
},
public: {
devAndLand: 0,
parking: 0,
total: 0
},
educational: {
devAndLand: 0,
parking: 0,
total: 0
},
hotel: {
devAndLand: 0,
parking: 0,
total: 0
},
parking: {
devAndLand: 0,
parking: 0,
total: 0
},
percent : {
residential: 0,
retail: 0,
office: 0,
industrial: 0,
public: 0,
educational: 0,
hotel: 0,
parking: 0,
},
grand: {
total: 0
}
}
export const updateDevelopmentCosts = (physicalInfo, basicFinInfo, advFinInfo) => {
let { devBrownfieldRemediationCosts, devDemolitionCosts, devSiteDevelopmentCosts, devAdditionalInfraEnhancement, additonalImpactFees } = advFinInfo;
let { siteArea } = physicalInfo;
let { residentialConCosts, retailConCosts, officeConCosts, industrialConCosts, publicConCosts, educationConCosts, hotelConCosts, parkingConCosts } = basicFinInfo;
developmentCosts["demolition"] = -1 * devDemolitionCosts; //=-$'Advanced Financial'.B45
developmentCosts["siteDevelopment"] = -1 * (siteArea*devSiteDevelopmentCosts);
developmentCosts["brownfieldRemediation"] = -1 * (devBrownfieldRemediationCosts*siteArea) //=-$'Advanced Financial'.B47*$'Physical Inputs'.B26
developmentCosts["residentialConstruction"] = -1 * (residentialConCosts* parkingOptionC_Aid4["residentialSpaces"]);
developmentCosts["retailConstruction"] = -1 * (retailConCosts* parkingOptionC_Aid4["retailSpaces"])
developmentCosts["officeConstruction"] = -1 * (officeConCosts* parkingOptionC_Aid4["officeSpaces"])
developmentCosts["industrialConstruction"] = -1 * (industrialConCosts* parkingOptionC_Aid4["industrialSpaces"])
developmentCosts["publicConstruction"] = -1 * (publicConCosts* parkingOptionC_Aid4["publicSpaces"])
developmentCosts["educationConstruction"] = -1 * (educationConCosts* parkingOptionC_Aid4["educationalSpaces"])
developmentCosts["hotelConstruction"] = -1 * (hotelConCosts* parkingOptionC_Aid4["hotelSpaces"])
developmentCosts["additionalInfrastructure"] = -1 * devAdditionalInfraEnhancement;
let { surfaceParkingCostSpace, landImpCostsPerSf } = basicFinInfo;
developmentCosts["parkingConstruction"] = (-1 * surfaceParkingCostSpace*parkingSpacesByType["surface"]) +
(-1 * basicFinInfo["structureParkingCostSpace"]*parkingSpacesByType["structure"]) +
(-1 * basicFinInfo["undergroundParkingCostSpace"]*parkingSpacesByType["underground"]) +
(-1 * basicFinInfo["internalParkingCostSpace"]*parkingSpacesByType["commercial"]) +
(-1 * basicFinInfo["parkingConCosts"]*parkingSpacesByType["internal"]);
let totalDevelopmentCosts = developmentCosts["demolition"] + developmentCosts["siteDevelopment"] + developmentCosts["brownfieldRemediation"] + developmentCosts["residentialConstruction"] + developmentCosts["retailConstruction"] + developmentCosts["officeConstruction"] + developmentCosts["industrialConstruction"] + developmentCosts["publicConstruction"] + developmentCosts["educationConstruction"] + developmentCosts["hotelConstruction"] + developmentCosts["additionalInfrastructure"] + developmentCosts["parkingConstruction"]
let { impactFeesPerUnit, impactFeesPerJob, impactFeesPerSf, buildingPermitFees, preDevDueDiligence,
taxesDuringConstruction, insuranceDuringConstruction, developerFee, contingency } = advFinInfo;
developmentCosts["waterQualityControls"] = 0; //=-$'Green Infrastructure'.C68
let impactFeeHelp = totalGrossSf["retail"] + totalGrossSf["office"] + totalGrossSf["industrial"] + totalGrossSf["public"] + totalGrossSf["educational"] + totalGrossSf["hotel"]
developmentCosts["impactFees"] = (-1 * additonalImpactFees) +
(-1 * (impactFeesPerUnit*totalDwellingOrHotelUnits["total"])) +
(-1 * (impactFeesPerJob*totalJobsByLandUse["total"])) +
(-1 * (impactFeesPerSf*impactFeeHelp));
developmentCosts["buildingPermits"] = buildingPermitFees;
developmentCosts["taxesDuringConstruction"] = -1 * (taxesDuringConstruction*landImpCostsPerSf)
preDevelopmentCosts["dueDiligence"] = preDevDueDiligence;
preDevelopmentCosts["rawLand"] = -1 * landImpCostsPerSf;
preDevelopmentCosts["landCarry"] = advFinInfo.preDevLandCarry * preDevelopmentCosts["rawLand"];
preDevelopmentCosts["landEntitlement"] = advFinInfo.preDevLandEntitlement * preDevelopmentCosts["rawLand"];
preDevelopmentCosts["professionalFees"] = advFinInfo.preDevProfessionalFees*totalDevelopmentCosts
let totalPreDevelopmentCosts = preDevelopmentCosts["dueDiligence"] + preDevelopmentCosts["rawLand"] + preDevelopmentCosts["landCarry"] + preDevelopmentCosts["landEntitlement"] + preDevelopmentCosts["professionalFees"]
developmentCosts["insuranceDuringConstruction"] = insuranceDuringConstruction*(totalPreDevelopmentCosts+totalDevelopmentCosts);
let totalIndirectCosts = developmentCosts["impactFees"] + developmentCosts["buildingPermits"] + developmentCosts["taxesDuringConstruction"] + developmentCosts["insuranceDuringConstruction"];
develpomentFees["developer"] = developerFee*(totalIndirectCosts+totalDevelopmentCosts);
develpomentFees["contigency"] = contingency*(totalDevelopmentCosts);
developmentTotals["buildingConstruction"] = totalDevelopmentCosts - developmentCosts["parkingConstruction"];
developmentTotals["parkingConstruction"] = developmentCosts["parkingConstruction"];
developmentTotals["totalProjectCosts"] = totalDevelopmentCosts + totalPreDevelopmentCosts + totalIndirectCosts;
let { sitresidentialUsePerc,
retailUsePerc,
officeUsePerc,
industrialUsePerc,
publicUsePerc,
educationUsePerc,
hotelUsePerc,
parkingUsePerceArea } = physicalInfo;
let costAllocationVar = totalIndirectCosts + develpomentFees["developer"] + develpomentFees["contigency"] + developmentCosts["waterQualityControls"] + developmentCosts["additionalInfrastructure"]
costAllocation["residential"]["devAndLand"] = developmentCosts["residentialConstruction"] + (costAllocationVar*sitresidentialUsePerc)
costAllocation["retail"]["devAndLand"] = developmentCosts["retailConstruction"] + (costAllocationVar*retailUsePerc)
costAllocation["office"]["devAndLand"] = developmentCosts["officeConstruction"] + (costAllocationVar*officeUsePerc)
costAllocation["industrial"]["devAndLand"] = developmentCosts["industrialConstruction"] + (costAllocationVar*industrialUsePerc)
costAllocation["public"]["devAndLand"] = developmentCosts["publicConstruction"] + (costAllocationVar*publicUsePerc)
costAllocation["educational"]["devAndLand"] = developmentCosts["educationConstruction"] + (costAllocationVar*educationUsePerc)
costAllocation["hotel"]["devAndLand"] = developmentCosts["hotelConstruction"] + (costAllocationVar*hotelUsePerc)
costAllocation["parking"]["devAndLand"] = developmentCosts["additionalInfrastructure"] + (costAllocationVar*parkingUsePerceArea)
let costAllocationVar2 = parkingOptionC_Aid4["residentialSpaces"] + parkingOptionC_Aid4["retailSpaces"] + parkingOptionC_Aid4["officeSpaces"] + parkingOptionC_Aid4["industrialSpaces"] + parkingOptionC_Aid4["publicSpaces"] + parkingOptionC_Aid4["educationalSpaces"] + parkingOptionC_Aid4["hotelSpaces"];
let costAllocationVar3 = developmentCosts["parkingConstruction"] - (-1 * parkingOptionC_Aid4["commercialParkingSpaces"] * parkingConCosts)
function getParkingCostAllocation(x){
let solution = (costAllocationVar3)*( x /costAllocationVar2);
return ( solution === null ? 0 : solution);
}
costAllocation["residential"]["parking"] = getParkingCostAllocation(parkingOptionC_Aid4["residentialSpaces"]);
costAllocation["retail"]["parking"] = getParkingCostAllocation(parkingOptionC_Aid4["retailSpaces"])
costAllocation["office"]["parking"] = getParkingCostAllocation(parkingOptionC_Aid4["officeSpaces"])
costAllocation["industrial"]["parking"] = getParkingCostAllocation(parkingOptionC_Aid4["industrialSpaces"])
costAllocation["public"]["parking"] = getParkingCostAllocation(parkingOptionC_Aid4["publicSpaces"])
costAllocation["educational"]["parking"] = getParkingCostAllocation(parkingOptionC_Aid4["educationalSpaces"])
costAllocation["hotel"]["parking"] = getParkingCostAllocation(parkingOptionC_Aid4["hotelSpaces"])
costAllocation["parking"]["parking"] = (-1 * parkingOptionC_Aid4["commercialParkingSpaces"] * parkingConCosts)
costAllocation["residential"]["total"] = costAllocation["residential"]["devAndLand"] + costAllocation["residential"]["parking"];
costAllocation["retail"]["total"] = costAllocation["retail"]["devAndLand"] + costAllocation["retail"]["parking"];
costAllocation["office"]["total"] = costAllocation["office"]["devAndLand"] + costAllocation["office"]["parking"];
costAllocation["industrial"]["total"] = costAllocation["industrial"]["devAndLand"] + costAllocation["industrial"]["parking"];
costAllocation["public"]["total"] = costAllocation["public"]["devAndLand"] + costAllocation["public"]["parking"];
costAllocation["educational"]["total"] = costAllocation["educational"]["devAndLand"] + costAllocation["educational"]["parking"];
costAllocation["hotel"]["total"] = costAllocation["hotel"]["devAndLand"] + costAllocation["hotel"]["parking"];
costAllocation["parking"]["total"] = costAllocation["parking"]["devAndLand"] + costAllocation["parking"]["parking"];
costAllocation["grand"]["total"] = costAllocation["residential"]["total"] + costAllocation["retail"]["total"] + costAllocation["office"]["total"] + costAllocation["industrial"]["total"] + costAllocation["public"]["total"] + costAllocation["educational"]["total"] + costAllocation["hotel"]["total"] + costAllocation["parking"]["total"];
costAllocation["percent"]["residential"] = errorChecking(costAllocation["residential"]["total"]/costAllocation["grand"]["total"]);
costAllocation["percent"]["retail"] = errorChecking(costAllocation["retail"]["total"]/costAllocation["grand"]["total"]);
costAllocation["percent"]["office"] = errorChecking(costAllocation["office"]["total"]/costAllocation["grand"]["total"]);
costAllocation["percent"]["industrial"] = errorChecking(costAllocation["industrial"]["total"]/costAllocation["grand"]["total"]);
costAllocation["percent"]["public"] = errorChecking(costAllocation["public"]["total"]/costAllocation["grand"]["total"]);
costAllocation["percent"]["educational"] = errorChecking(costAllocation["educational"]["total"]/costAllocation["grand"]["total"]);
costAllocation["percent"]["hotel"] =errorChecking( costAllocation["hotel"]["total"]/costAllocation["grand"]["total"]);
costAllocation["percent"]["parking"] = errorChecking(costAllocation["parking"]["total"]/costAllocation["grand"]["total"]);
updateMixedUseSummary( physicalInfo, basicFinInfo, advFinInfo );
}
export const getParkingCostSf = () => {
return -1 * developmentTotals["parkingConstruction"];
}
export const getTotalPrjValue = () => {
let solution = -1 * developmentTotals["totalProjectCosts"]
return solution;
}
let residentialOwnerROI = {
// investment: {
// targetReturn,
// actualReturn,
// }
// publicLeveraging: {
// taxCredits,
// feeReductions,
// grants,
// }
baseline: {
projectCost: 0,
interimFinancing: 0,
developerEquity: 0,
residentialUnits: 0,
avgMarketPrice: 0,
netSaleProceeds: 0,
netProjectReturn: 0
},
performanceAssess: {
projectReturn: 0,
projectProfit: 0,
netProjectReturn: 0,
returnToEquity: 0,
projectNetProfit: 0
},
leveragedPerformance: {
publicLeveraging: 0,
adjustedProjectCost: 0,
developerEquity: 0,
netProjectReturn: 0,
projectRateReturn: 0,
projectProfit: 0,
returnToEquity: 0,
equityProfit: 0
},
propTax: {
projectMarketValue: 0,
projectAssessedValue: 0,
estimatedPropertyTaxes: 0
}
}
let residentialRenterROI = {
leveragingTools: {
taxCreditsNetToProject: 0,
feeReductions: 0,
grants: 0,
totalDevelopmentOffsets: 0,
netDevelopmentCosts: 0
},
netOperatingIncome: {
totalDevelopmentCosts: 0,
developmentCostsUnit: 0,
numberOfUnits: 0,
monthlyRent: 0,
totalProjectSize: 0,
otherIncome: 0,
lessVacancy: 0,
lessConcessions: 0,
lessOperatingCostsRent: 0,
lessOperatingCostsProject: 0
},
operatingStatement: {
lessPropertyTaxes: 0
}
}
let retailROI = {
netOperatingIncome: {
totalDevelopmentCosts: 0,
developmentCostsUnit: 0,
numberOfUnits: 0,
monthlyRent: 0,
totalProjectSize: 0,
otherIncome: 0,
lessVacancy: 0,
lessConcessions: 0,
lessOperatingCostsRent: 0,
lessOperatingCostsProject: 0
},
operatingStatement: {
lessPropertyTaxes: 0
}
}
let officeROI = {
netOperatingIncome: {
totalDevelopmentCosts: 0,
developmentCostsUnit: 0,
numberOfUnits: 0,
monthlyRent: 0,
totalProjectSize: 0,
otherIncome: 0,
lessVacancy: 0,
lessConcessions: 0,
lessOperatingCostsRent: 0,
lessOperatingCostsProject: 0
},
operatingStatement: {
lessPropertyTaxes: 0
}
}
let industrialROI = {
netOperatingIncome: {
totalDevelopmentCosts: 0,
developmentCostsUnit: 0,
numberOfUnits: 0,
monthlyRent: 0,
totalProjectSize: 0,
otherIncome: 0,
lessVacancy: 0,
lessConcessions: 0,
lessOperatingCostsRent: 0,
lessOperatingCostsProject: 0
},
operatingStatement: {
lessPropertyTaxes: 0
}
}
let hotelROI = {
leveragingTools: {
taxCreditsNetToProject: 0,
feeReductions: 0,
grants: 0,
totalDevelopmentOffsets: 0,
netDevelopmentCosts: 0
},
netOperatingIncome: {
totalDevelopmentCosts: 0,
developmentCostsUnit: 0,
numberOfUnits: 0,
monthlyRent: 0,
totalProjectSize: 0,
otherIncome: 0,
lessVacancy: 0,
lessConcessions: 0,
lessOperatingCostsRent: 0,
lessOperatingCostsProject: 0
},
operatingStatement: {
lessPropertyTaxes: 0
}
}
let commercialParking = {
netOperatingIncome: {
totalDevelopmentCosts: 0,
developmentCostsUnit: 0,
numberOfUnits: 0,
monthlyRent: 0,
totalProjectSize: 0,
otherIncome: 0,
lessVacancy: 0,
lessConcessions: 0,
lessOperatingCostsRent: 0,
lessOperatingCostsProject: 0
},
operatingStatement: {
lessPropertyTaxes: 0
}}
export const updateMixedUseSummary = (physicalInfo, basicFinInfo, advFinInfo) => {
let { occupancyType, residentialUnitSize } = physicalInfo;
let { salesPricePerSf, testSubsidy, monthlyRentPerSf, monthlyParkingCost } = basicFinInfo;
let { maxLTVOwner, projectReturnRateOwner, returnToEquityOwner, assessRatioTaxOwner, assessRatioTaxRenter, propTaxOwner,
propTaxRenter, assessRatioTaxRetail, propTaxOffice, assessRatioTaxOffice,
propTaxIndustrial, assessRatioTaxIndustrial, propTaxHotel, assessRatioTaxHotel, propTaxParking, assessRatioTaxParking } = advFinInfo;
//update residentialOwnerROI = {}
residentialOwnerROI["baseline"]["projectCost"] = (occupancyType === 'Owner' ? (-1*costAllocation["residential"]["total"]) : 0);
residentialOwnerROI["baseline"]["interimFinancing"] = (1-maxLTVOwner)*residentialOwnerROI["baseline"]["projectCost"];
residentialOwnerROI["baseline"]["developerEquity"] = residentialOwnerROI["baseline"]["projectCost"] - residentialOwnerROI["baseline"]["interimFinancing"];
residentialOwnerROI["baseline"]["residentialUnits"] = (occupancyType === 'Owner' ? totalDwellingOrHotelUnits["total"] : 0);
residentialOwnerROI["baseline"]["avgMarketPrice"] = residentialUnitSize*salesPricePerSf;
residentialOwnerROI["baseline"]["netSaleProceeds"] = residentialOwnerROI["baseline"]["avgMarketPrice"]*residentialOwnerROI["baseline"]["residentialUnits"] //=B17*B18
residentialOwnerROI["baseline"]["netProjectReturn"] = residentialOwnerROI["baseline"]["netSaleProceeds"]-residentialOwnerROI["baseline"]["projectCost"]; //=B19-B14
residentialOwnerROI["performanceAssess"]["projectReturn"] = residentialOwnerROI["baseline"]["netProjectReturn"];
residentialOwnerROI["performanceAssess"]["projectProfit"] = ( residentialOwnerROI["baseline"]["projectCost"] === 0 ? 0 : residentialOwnerROI["performanceAssess"]["projectReturn"]/residentialOwnerROI["baseline"]["projectCost"] )//=IF(B23=0,0,B24/B23)
residentialOwnerROI["performanceAssess"]["netProjectReturn"] = residentialOwnerROI["performanceAssess"]["projectReturn"] - (residentialOwnerROI["baseline"]["projectCost"]*projectReturnRateOwner) //=B24-(B14*B3)
residentialOwnerROI["performanceAssess"]["returnToEquity"] = (residentialOwnerROI["baseline"]["developerEquity"] === 0 ? 0 : residentialOwnerROI["performanceAssess"]["projectReturn"]/residentialOwnerROI["baseline"]["developerEquity"]);
residentialOwnerROI["performanceAssess"]["projectNetProfit"] = residentialOwnerROI["baseline"]["netSaleProceeds"] - (returnToEquityOwner*residentialOwnerROI["baseline"]["developerEquity"]); //=B27-(B4*B28)
let publicFunds = 0 //taxCredits+ feeReductions+ grants
residentialOwnerROI["leveragedPerformance"]["publicLeveraging"] = ( occupancyType === 'Renter' ? 0 : ( testSubsidy === 0 ? publicFunds : (testSubsidy*costAllocation["percent"]["residential"]) ))
residentialOwnerROI["leveragedPerformance"]["adjustedProjectCost"] = residentialOwnerROI["baseline"]["projectCost"] - residentialOwnerROI["leveragedPerformance"]["publicLeveraging"];
residentialOwnerROI["leveragedPerformance"]["developerEquity"] = (residentialOwnerROI["leveragedPerformance"]["adjustedProjectCost"]-residentialOwnerROI["baseline"]["interimFinancing"] < 0 ? 1 : residentialOwnerROI["leveragedPerformance"]["adjustedProjectCost"]-residentialOwnerROI["baseline"]["interimFinancing"])
residentialOwnerROI["leveragedPerformance"]["netProjectReturn"] = residentialOwnerROI["baseline"]["netSaleProceeds"]-residentialOwnerROI["leveragedPerformance"]["adjustedProjectCost"];
residentialOwnerROI["leveragedPerformance"]["projectRateReturn"] = errorChecking((residentialOwnerROI["leveragedPerformance"]["adjustedProjectCost"] === 0 ? 0 : residentialOwnerROI["leveragedPerformance"]["netProjectReturn"]/residentialOwnerROI["leveragedPerformance"]["adjustedProjectCost"]))
residentialOwnerROI["leveragedPerformance"]["projectProfit"] = residentialOwnerROI["leveragedPerformance"]["netProjectReturn"] - (residentialOwnerROI["leveragedPerformance"]["adjustedProjectCost"]*projectReturnRateOwner);
residentialOwnerROI["leveragedPerformance"]["returnToEquity"] = residentialOwnerROI["leveragedPerformance"]["netProjectReturn"]/residentialOwnerROI["leveragedPerformance"]["developerEquity"];
residentialOwnerROI["leveragedPerformance"]["equityProfit"] = residentialOwnerROI["leveragedPerformance"]["netProjectReturn"]-(residentialOwnerROI["leveragedPerformance"]["developerEquity"]*returnToEquityOwner);
//Year1
residentialOwnerROI["propTax"]["projectMarketValue"] = residentialOwnerROI["baseline"]["netSaleProceeds"];
residentialOwnerROI["propTax"]["projectAssessedValue"] = residentialOwnerROI["baseline"]["netSaleProceeds"]*assessRatioTaxOwner;
residentialOwnerROI["propTax"]["estimatedPropertyTaxes"] = residentialOwnerROI["propTax"]["projectAssessedValue"]*propTaxOwner;
//update residentialRenterROI = {}
residentialRenterROI["leveragingTools"]["taxCreditsNetToProject"] = testSubsidy; //gap-financing
residentialRenterROI["leveragingTools"]["feeReductions"] = testSubsidy; //gap-financing
residentialRenterROI["leveragingTools"]["grants"] = testSubsidy*costAllocation["percent"]["residential"]; //gap-financing=IF($'Basic Financial'.$B$33=0,D6,IF($'Physical Inputs'.B35="Renter",$'Basic Financial'.$B$33*$'Development Costs'.E40,0))
residentialRenterROI["leveragingTools"]["totalDevelopmentOffsets"] = residentialRenterROI["leveragingTools"]["taxCreditsNetToProject"]+residentialRenterROI["leveragingTools"]["feeReductions"]+residentialRenterROI["leveragingTools"]["grants"];
residentialRenterROI["netOperatingIncome"]["numberOfUnits"] = ( occupancyType === 'Renter' ? totalDwellingOrHotelUnits["residential"] : 0)
residentialRenterROI["netOperatingIncome"]["totalDevelopmentCosts"] = errorChecking(( occupancyType === 'Renter' ? (-1 * costAllocation["residential"]["total"] ) : 0) / residentialRenterROI["netOperatingIncome"]["numberOfUnits"])
residentialRenterROI["leveragingTools"]["netDevelopmentCosts"] = residentialRenterROI["netOperatingIncome"]["totalDevelopmentCosts"] - residentialRenterROI["leveragingTools"]["totalDevelopmentOffsets"]
let monthlyRentCalc = (monthlyRentPerSf*residentialUnitSize)+monthlyParkingCost;
residentialRenterROI["netOperatingIncome"]["monthlyRent"] = ( occupancyType === 'Renter' ? monthlyRentCalc : 0);
// residentialRenterROI["netOperatingIncome"]["lessOperatingCostsProject"] =
residentialRenterROI["netOperatingIncome"]["lessOperatingCostsRent"] = residentialRenterROI["netOperatingIncome"]["lessOperatingCostsProject"]*residentialRenterROI["netOperatingIncome"]["numberOfUnits"]
residentialRenterROI["operatingStatement"]["lessPropertyTaxes"] = residentialRenterROI["netOperatingIncome"]["totalDevelopmentCosts"]*propTaxRenter*assessRatioTaxRenter
//update retailROI = {}
retailROI["netOperatingIncome"]["totalDevelopmentCosts"] = -1 * costAllocation["retail"]["total"];
retailROI["operatingStatement"]["lessPropertyTaxes"] = retailROI["operatingStatement"]["totalDevelopmentCosts"] * propTaxRenter * assessRatioTaxRetail;
//update officeROI = {}
officeROI["netOperatingIncome"]["totalDevelopmentCosts"] = -1 * costAllocation["office"]["total"];
officeROI["operatingStatement"]["lessPropertyTaxes"] = officeROI["operatingStatement"]["totalDevelopmentCosts"] * propTaxOffice * assessRatioTaxOffice;
//update industrialROI = {}
industrialROI["netOperatingIncome"]["totalDevelopmentCosts"] = -1 * costAllocation["industrial"]["total"];
industrialROI["operatingStatement"]["lessPropertyTaxes"] = industrialROI["operatingStatement"]["totalDevelopmentCosts"] * propTaxIndustrial * assessRatioTaxIndustrial;
//update hotelROI = {}
hotelROI["netOperatingIncome"]["totalDevelopmentCosts"] = -1 * costAllocation["hotel"]["total"];
hotelROI["netOperatingIncome"]["netDevelopmentCosts"] = hotelROI["netOperatingIncome"]["totalDevelopmentCosts"] - hotelROI["leveragingTools"]["totalDevelopmentOffsets"];
hotelROI["operatingStatement"]["lessPropertyTaxes"] = hotelROI["operatingStatement"]["netDevelopmentCosts"] * propTaxHotel * assessRatioTaxHotel;
//update commercialParking = {}
commercialParking["netOperatingIncome"]["totalDevelopmentCosts"] = -1 * costAllocation["parking"]["total"];
commercialParking["operatingStatement"]["lessPropertyTaxes"] = commercialParking["operatingStatement"]["totalDevelopmentCosts"] * propTaxParking * assessRatioTaxParking;
updatePhysicalOutputs(physicalInfo, basicFinInfo, advFinInfo );
}
export const getPropTaxRevenueYr = () => {
let mixedUseSummaryC95 = commercialParking["operatingStatement"]["lessPropertyTaxes"]+retailROI["operatingStatement"]["lessPropertyTaxes"]+officeROI["operatingStatement"]["lessPropertyTaxes"]+industrialROI["operatingStatement"]["lessPropertyTaxes"]+hotelROI["operatingStatement"]["lessPropertyTaxes"]
//, =$'Mixed-Use Summary'.C95+$'Residential Owner'.E54,
return mixedUseSummaryC95 + residentialOwnerROI["propTax"]["estimatedPropertyTaxes"];
}
export const getTotalFees = () => {
let solution = -1 * developmentCosts["impactFees"]
return solution;
}
export const getSubsidy = (basicFinInfo) => {
let { testSubsidy } = basicFinInfo;
// let detailedSubsidy = =$'Mixed-Use Summary'.J17+$'Mixed-Use Summary'.H66+IF(OR(testSubsidy=0,testSubsidy=""),SUM($'Mixed-Use Summary'.C96:L100),0)
let detailedSubsidy = 0;
let solution = ( testSubsidy > 0 ? testSubsidy : detailedSubsidy)
return solution;
}
export const getRateOfReturn = () => {
//=$'Mixed-Use Summary'.O6,
//=IFERROR(L122,0)
//=IFERROR(IRR(B121:L121),0)
return 0;
}
export const getProjectReturn = () => {
//=$'Mixed-Use Summary'.U5,
return 0;
}
export const getYIntercept = () => {
//=INTERCEPT($'ROI Scenario'.B146:B147,$'ROI Scenario'.A146:A147),
return 0;
}
export const getSlope = () => {
//=LINEST($'ROI Scenario'.B146:B147,$'ROI Scenario'.A146:A147)
return 0;
}
|
bseayin/study_java_web | springbootJPA/src/main/java/com/xsz/entity/Student.java | package com.xsz.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="student")
public class Student {
//设置主键
@Id
@Column(length=30)
private String sId;
private String sName;
private String sSex;
private String sBirth;
public String getsId() {
return sId;
}
public void setsId(String sId) {
this.sId = sId;
}
public String getsName() {
return sName;
}
public void setsName(String sName) {
this.sName = sName;
}
public String getsSex() {
return sSex;
}
public void setsSex(String sSex) {
this.sSex = sSex;
}
public String getsBirth() {
return sBirth;
}
public void setsBirth(String sBirth) {
this.sBirth = sBirth;
}
}
|
jmchs-robotics/VSCode2021 | src/main/java/frc/robot/util/ThrowerLUT.java | package frc.robot.util;
import frc.robot.Constants.ThrowerPIDs;;
/**
* Contains the LUT for the thrower
*/
public class ThrowerLUT {
// if the vision coprocessor can't see the RFT, thrower should be set to this speed
public static double DEFAULT_RPM = 4550; // from testing 3/2, and estimating, hopefully scores at autonomous dist.
// Known distance to rpm values, determined from our testing
// first column is inches from the target as reported by the vision processor;
// second column is RPM that scores from that distance
// keep the table organized from closest to farthest
private static final double[][] LUT = {
// from testing 3/2 with 53 degrees hood angle = 37 degrees departure angle from horizontal
//And fresh Battery :)
{0, DEFAULT_RPM}, // Default RPM
//{?, 5480} //{300, 5480}
//{THOR, RPMS} //{old distance it read, RPMS}
{43, 5065}, //{239, 5065},
{49, 4825}, //{214, 4825},
{51, 4675}, //{197, 4675},
{58, 4600}, //{173, 4600},
{63, 4350}, //{149, 4350},
{66, 4300}, //{132, 4300}, //3/8 THOR: 69
/*
Testing Data Collected 3/9
distance from bumber: 99.5 123 149 178
distance from hopper: 123 151 175 206
back bumper: 180
thor: 67 56 53 48 55
*/
//distance for accuracy challenge: 45, 120, 180, 240
/* testing 2/29 with 53 degrees hood angle = 37 degrees departure angle from horizontal
// from
{125, 4200},
{143, 4400},
{163, 4625},
{192, 4650},
{217, 4800},
{232, 5000},
{266, 5150}
/*
// from testing 2/8 with 53 degrees hood angle = 37 degrees departure angle from horizontal
{24, 4600},
{48, 4800},
{72, 5100},
{84, 5400 },
{96, 5100},
{108, 5200},
{132, 4900},
{156, 4700},
{300, 5480}
/*
// from testing 2/8 with 43 degrees hood angle = 47 degrees departure angle from horizontal
{ 60, 3580},
{ 72, 3550},
{ 84, 3600},
{ 96, 3625},
{ 108, 3650},
{ 120, 3700},
{ 132, 3900},
{ 156, 4250},
{ 180, 4450},
{ 204, 4625},
{ 228, 4750},
{ 300, 5475}
*/
};
/**
* Use a LUT to map distance as given by the vision processor to RPMs.
* Linearly interpolate between known values in our table.
* @param inches the distance from the thrower to the goal
*/
public static double distanceToRPMs(double inches){
int index = LUT.length - 2; // Start at the highest meaningful index for a right-handed discrete derivative
while(inches < LUT[index][0] && index > 0){ index--; } // iterate down. Safe if the lowest index contains {0, DEFAULT_RPM}
// No need to check if we're off the deep end, because the worst that could happen
// is the motor gets set to full forward. This would replace the loop & following if-statement.
// the slope intercept formulas
// m = y2 - y1 / x2 - x1
// b = y - mx
// y = mx + b
double m = (LUT[index + 1][1] - LUT[index][1])
/ (LUT[index + 1][0] - LUT[index][0]);
double b = LUT[index][1] - (m * LUT[index][0]);
double y = (m * inches) + b;
return y;
}
private static final double[][] llLUT = {
// from testing 3/2 with 53 degrees hood angle = 37 degrees departure angle from horizontal
//And fresh Battery :)
{-15, 5500},
{-10, 5000},
{-5, 4000},
{0, DEFAULT_RPM}, // Default RPM
{5, 4000},
{10, 5000},
};
public static double llAngleToRPMs( double angle) {
int index = llLUT.length - 2; // Start at the highest meaningful index for a right-handed discrete derivative
while(angle < llLUT[index][0]){ index--; } // iterate down. Safe if the lowest index contains {0, DEFAULT_RPM}
// No need to check if we're off the deep end, because the worst that could happen
// is the motor gets set to full forward. This would replace the loop & following if-statement.
// the slope intercept formulas
// m = y2 - y1 / x2 - x1
// b = y - mx
// y = mx + b
double m = ( llLUT[index + 1][1] - llLUT[index][1])
/ ( llLUT[index + 1][0] - llLUT[index][0]);
double b = llLUT[index][1] - (m * llLUT[index][0]);
double y = (m * angle) + b;
return y;
}
}
|
dmytroshch/bfx-hf-algo | lib/twap/meta/declare_channels.js | 'use strict'
const hasTradeTarget = require('../util/has_trade_target')
const hasOBTarget = require('../util/has_ob_target')
/**
* Declares necessary data channels for price matching. The instance may
* require a `book` or `trades` channel depending on the execution parameters.
*
* Part of the `meta` handler section.
*
* @memberOf module:TWAP
* @param {object} instance - AO instance state
*/
const declareChannels = async (instance = {}) => {
const { h = {}, state = {} } = instance
const { args = {} } = state
const { symbol, priceTarget } = args
const { declareChannel } = h
if (hasTradeTarget(args)) {
await declareChannel(instance, 'trades', { symbol })
} else if (hasOBTarget(args)) {
await declareChannel(instance, 'book', {
symbol,
prec: 'R0',
len: '25'
})
} else {
throw new Error(`invalid price target ${priceTarget}`)
}
}
module.exports = declareChannels
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.