repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
helloqinglan/courtdriver | src/main/java/com/domoes/kafka/POJOTagValue.java | package com.domoes.kafka;
public class POJOTagValue {
private String tag;
private String value;
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
|
arfathpasha/auth2 | src/us/kbase/test/auth2/lib/RoleTest.java | package us.kbase.test.auth2.lib;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
import org.junit.Test;
import us.kbase.auth2.lib.Role;
public class RoleTest {
@Test
public void getters() throws Exception {
assertThat("incorrect id", Role.ROOT.getID(), is("Root"));
assertThat("incorrect desc", Role.ROOT.getDescription(), is("Root"));
assertThat("incorrect id", Role.CREATE_ADMIN.getID(), is("CreateAdmin"));
assertThat("incorrect desc", Role.CREATE_ADMIN.getDescription(),
is("Create administrator"));
assertThat("incorrect id", Role.ADMIN.getID(), is("Admin"));
assertThat("incorrect desc", Role.ADMIN.getDescription(), is("Administrator"));
assertThat("incorrect id", Role.SERV_TOKEN.getID(), is("ServToken"));
assertThat("incorrect desc", Role.SERV_TOKEN.getDescription(),
is("Create server tokens"));
assertThat("incorrect id", Role.DEV_TOKEN.getID(), is("DevToken"));
assertThat("incorrect desc", Role.DEV_TOKEN.getDescription(),
is("Create developer tokens"));
}
@Test
public void getRole() throws Exception {
try {
Role.getRole("foo");
fail("got bad role");
} catch (IllegalArgumentException e) {
assertThat("incorrect exception message", e.getMessage(), is("Invalid role id: foo"));
}
assertThat("incorrect role", Role.getRole("Root"), is(Role.ROOT));
assertThat("incorrect role", Role.getRole("CreateAdmin"), is(Role.CREATE_ADMIN));
assertThat("incorrect role", Role.getRole("Admin"), is(Role.ADMIN));
assertThat("incorrect role", Role.getRole("ServToken"), is(Role.SERV_TOKEN));
assertThat("incorrect role", Role.getRole("DevToken"), is(Role.DEV_TOKEN));
}
@Test
public void isRole() throws Exception {
assertThat("incorrect isRole()", Role.isRole(null), is(false));
assertThat("incorrect isRole()", Role.isRole(""), is(false));
assertThat("incorrect isRole()", Role.isRole("foo"), is(false));
assertThat("incorrect role", Role.isRole("Root"), is(true));
assertThat("incorrect role", Role.isRole("CreateAdmin"), is(true));
assertThat("incorrect role", Role.isRole("Admin"), is(true));
assertThat("incorrect role", Role.isRole("ServToken"), is(true));
assertThat("incorrect role", Role.isRole("DevToken"), is(true));
}
private Set<Role> set(Role...roles) {
return Arrays.stream(roles).collect(Collectors.toSet());
}
@Test
public void included() throws Exception {
assertThat("incorrect included()", Role.ROOT.included(), is(set(Role.ROOT)));
assertThat("incorrect included()", Role.CREATE_ADMIN.included(),
is(set(Role.CREATE_ADMIN)));
assertThat("incorrect included()", Role.ADMIN.included(),
is(set(Role.ADMIN, Role.SERV_TOKEN, Role.DEV_TOKEN)));
assertThat("incorrect included()", Role.SERV_TOKEN.included(),
is(set(Role.SERV_TOKEN, Role.DEV_TOKEN)));
assertThat("incorrect included()", Role.DEV_TOKEN.included(), is(set(Role.DEV_TOKEN)));
}
@Test
public void canGrant() throws Exception {
assertThat("incorrect canGrant()", Role.ROOT.canGrant(), is(set(Role.CREATE_ADMIN)));
assertThat("incorrect canGrant()", Role.CREATE_ADMIN.canGrant(),
is(set(Role.ADMIN)));
assertThat("incorrect canGrant()", Role.ADMIN.canGrant(),
is(set(Role.SERV_TOKEN, Role.DEV_TOKEN)));
assertThat("incorrect canGrant()", Role.SERV_TOKEN.canGrant(),
is(Collections.emptySet()));
assertThat("incorrect canGrant()", Role.DEV_TOKEN.canGrant(), is(Collections.emptySet()));
}
@Test
public void isAdmin() throws Exception {
assertThat("incorrect isAdmin()", Role.isAdmin(set(Role.ROOT)), is(true));
assertThat("incorrect isAdmin()", Role.isAdmin(set(Role.CREATE_ADMIN)), is(true));
assertThat("incorrect isAdmin()", Role.isAdmin(set(Role.ADMIN)), is(true));
assertThat("incorrect isAdmin()", Role.isAdmin(set(Role.SERV_TOKEN)), is(false));
assertThat("incorrect isAdmin()", Role.isAdmin(set(Role.DEV_TOKEN)), is(false));
assertThat("incorrect isAdmin()", Role.isAdmin(Collections.emptySet()), is(false));
assertThat("incorrect isAdmin()", Role.isAdmin(set(Role.SERV_TOKEN, Role.DEV_TOKEN)),
is(false));
assertThat("incorrect isAdmin()", Role.isAdmin(
set(Role.CREATE_ADMIN, Role.SERV_TOKEN, Role.DEV_TOKEN)), is(true));
}
@Test
public void isSatisfiedBy() throws Exception {
assertThat("incorrect isSatisfiedBy()", Role.SERV_TOKEN.isSatisfiedBy(
set(Role.ADMIN, Role.DEV_TOKEN)), is(true));
assertThat("incorrect isSatisfiedBy()", Role.SERV_TOKEN.isSatisfiedBy(
set(Role.CREATE_ADMIN, Role.ROOT)), is(false));
assertThat("incorrect isSatisfiedBy()", Role.CREATE_ADMIN.isSatisfiedBy(
set(Role.ADMIN, Role.ROOT)), is(false));
assertThat("incorrect isSatisfiedBy()", Role.CREATE_ADMIN.isSatisfiedBy(
set(Role.CREATE_ADMIN, Role.ROOT)), is(true));
assertThat("incorrect isSatisfiedBy()", Role.DEV_TOKEN.isSatisfiedBy(
set(Role.SERV_TOKEN)), is(true));
}
}
|
Cyynet/CreditSalesman | CreditSalesman/Classes/LeftMenu/View/ZHVersionModel.h | <filename>CreditSalesman/Classes/LeftMenu/View/ZHVersionModel.h
//
// ZHVersionModel.h
// ZHFinancialClient
//
// Created by zhph on 2017/4/25.
// Copyright © 2017年 正和. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface ZHVersionModel : NSObject
/*主键*/
@property(nonatomic,copy)NSString * ID;
/*版本名字*/
@property(nonatomic,copy)NSString * ver_name;
/*更新日期*/
@property(nonatomic,copy)NSString * update_date;
/*A:安卓;I:iOS*/
@property(nonatomic,copy)NSString * app_type;
/*版本号*/
@property(nonatomic,copy)NSString * ver_code;
/*大小*/
@property(nonatomic,copy)NSString * app_size;
/*苹果商店地址*/
@property(nonatomic,copy)NSString * appstore_url;
/*下载路径*/
@property(nonatomic,copy)NSString * url;
/*升级日志*/
@property(nonatomic,copy)NSString * ver_text;
@end
|
aml-org/als | als-lsp/shared/src/main/scala/org/mulesoft/lsp/feature/link/DocumentLinkClientCapabilities.scala | package org.mulesoft.lsp.feature.link
/**
* Capabilities specific to the `textDocument/documentLink`.
*
* @param dynamicRegistration Whether documentLink supports dynamic registration.
* @param tooltipSupport Whether the client support the `tooltip` property on `DocumentLink`.
*/
case class DocumentLinkClientCapabilities(dynamicRegistration: Option[Boolean], tooltipSupport: Option[Boolean])
|
wupengFEX/mip-extensions-platform | mip-wygx-webp/mip-wygx-webp.js | /**
* @file mip-wygx-webp 组件
* @author qiu_rj
*/
define(function (require) {
'use strict';
var util = require('util');
var customElement = require('customElement').create();
var lazyCookie = {
setCookie: function () {
var exdate = new Date();
exdate.setDate(exdate.getDate() + 30);
document.cookie = 'lyWebp=true;expires=' + exdate.toGMTString();
},
getCookie: function (name) {
var arr;
var reg = new RegExp('(^| )' + name + '=([^\;]*)(\;|$)');
if (arr === document.cookie.match(reg)) {
return unescape(arr[2]);
} else {
return null;
}
}
};
var hasWebp = (function () {
// if support webp
var cwebp = document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp');
var isSupportWebp = !![].map && cwebp === 0;
if (!isSupportWebp) {
return false;
}
// if has webp cookie
if (lazyCookie.getCookie('lyWebp')) {
return true;
}
// or
lazyCookie.setCookie();
return true;
})();
function getImageUrl(ele) {
var newsrc;
var src = ele.getAttribute('src');
var webpUrl = ele.getAttribute('webp-src');
// 替换webp图片, cache处理
newsrc = (webpUrl !== '' || hasWebp) ? util.makeCacheUrl(webpUrl, 'img') : util.makeCacheUrl(src, 'img');
return newsrc;
}
function imgLoadError(ele, img) {
var src = ele.getAttribute('src');
// 监听图片不能加载事件
img.addEventListener('error', function () {
img.src = src;
});
// 解除图片绑定
img.removeEventListener('error', imgLoadError);
}
/**
* 第一次进入可视区回调,只会执行一次
*/
customElement.prototype.firstInviewCallback = function () {
var child = this.element.querySelector('img');
if (child) {
return;
}
var Img = new Image();
this.applyFillContent(Img, true);
var ele = this.element;
var src = getImageUrl(ele);
Img.src = src;
if (ele.getAttribute('alt')) {
Img.setAttribute('alt', ele.getAttribute('alt'));
}
ele.appendChild(Img);
imgLoadError(ele, Img);
};
return customElement;
});
|
yangdsh/ottertune | server/website/script/fixture_generators/knob_settings/oracle/create_knob_settings.py | <filename>server/website/script/fixture_generators/knob_settings/oracle/create_knob_settings.py
#
# OtterTune - create_knob_settings.py
#
# Copyright (c) 2017-18, Carnegie Mellon University Database Group
#
import csv
import json
import shutil
from operator import itemgetter
# Oracle Type:
# 1 - Boolean
# 2 - String
# 3 - Integer
# 4 - Parameter file
# 5 - Reserved
# 6 - Big integer
# Ottertune Type:
# STRING = 1
# INTEGER = 2
# REAL = 3
# BOOL = 4
# ENUM = 5
# TIMESTAMP = 6
# KnobResourceType
# MEMORY = 1
# CPU = 2
# STORAGE = 3
# OTHER = 4
# miss:
# OPTIMIZER_MODE
# cursor_sharing
EXTRA_KNOBS = {
'_pga_max_size': {
'default': 200000000,
'resource': 1,
'unit': 1,
},
'_smm_max_size': {
'default': 100000,
'resource': 1,
'unit': 1,
},
'_smm_px_max_size': {
'default': 300000,
'resource': 1,
'unit': 1,
},
'_optimizer_use_feedback': {
'default': True,
'minval': None,
'maxval': None,
'vartype': 4,
},
'ioseektim': {
'default': 10,
'minval': 1,
'maxval': 10,
},
'iotfrspeed': {
'default': 4096,
'minval': 4096,
'maxval': 190000,
},
'_enable_numa_optimization': {
'default': False,
'minval': None,
'maxval': None,
'vartype': 4,
},
'_enable_numa_support': {
'default': False,
'minval': None,
'maxval': None,
'vartype': 4,
},
'_unnest_subquery': {
'default': True,
'minval': None,
'maxval': None,
'vartype': 4,
},
}
def add_fields(fields_list, version):
for name, custom_fields in EXTRA_KNOBS.items():
new_field = dict(
name=('global.' + name).lower(),
scope='global',
dbms=version,
category='',
enumvals=None,
context='',
unit=3, # other
tunable=False,
description='',
summary='',
vartype=2, # integer
minval=0,
maxval=2000000000,
default=500000,
)
new_field.update(custom_fields)
fields_list.append(new_field)
def set_field(fields):
if fields['name'].upper() == 'MEMORY_TARGET':
fields['tunable'] = False
fields['minval'] = 0
fields['maxval'] = 33000000000 # 33G
fields['default'] = 0
fields['resource'] = 1
fields['unit'] = 1
if fields['name'].upper() == 'MEMORY_MAX_TARGET':
fields['tunable'] = False
fields['minval'] = 0
fields['maxval'] = 33000000000 # 33G
fields['default'] = 0
fields['resource'] = 1
fields['unit'] = 1
if fields['name'].upper() == 'SGA_TARGET':
fields['tunable'] = False
fields['minval'] = 0
fields['maxval'] = 33000000000 # 33G
fields['default'] = 0
fields['resource'] = 1
fields['unit'] = 1
if fields['name'].upper() == 'SGA_MAX_SIZE':
fields['tunable'] = False
fields['minval'] = 0
fields['maxval'] = 33000000000 # 33G
fields['default'] = 0
fields['resource'] = 1
fields['unit'] = 1
if fields['name'].upper() == 'DB_CACHE_SIZE':
fields['tunable'] = True
fields['minval'] = 0
fields['maxval'] = 25000000000 # 24G
fields['default'] = 4000000000 # 4G
fields['resource'] = 1
fields['unit'] = 1
if fields['name'].upper() == 'SHARED_POOL_SIZE':
fields['tunable'] = True
fields['minval'] = 0
fields['maxval'] = 4000000000 # 4G
fields['default'] = 1000000000 # 1G
fields['resource'] = 1
fields['unit'] = 1
if fields['name'].upper() == 'SHARED_POOL_RESERVED_SIZE':
fields['tunable'] = True
fields['minval'] = 0
fields['maxval'] = 4000000000 # 4G
fields['default'] = 1000000000 # 1G
fields['resource'] = 1
fields['unit'] = 1
if fields['name'].upper() == 'SHARED_IO_POOL_SIZE':
fields['tunable'] = False
fields['minval'] = 0
fields['maxval'] = 4000000000 # 4G
fields['default'] = 1000000000 # 1G
fields['resource'] = 1
fields['unit'] = 1
if fields['name'].upper() == 'STREAMS_POOL_SIZE':
fields['tunable'] = True
fields['minval'] = 0
fields['maxval'] = 4000000000 # 4G
fields['default'] = 20000000 # 20M
fields['resource'] = 1
fields['unit'] = 1
if fields['name'].upper() == 'LOG_BUFFER':
fields['tunable'] = True
fields['minval'] = 0
fields['maxval'] = 2000000000 # 2GB
fields['default'] = 50000000 # 50M
fields['resource'] = 1
fields['unit'] = 1
if fields['name'].upper() == 'DB_KEEP_CACHE_SIZE':
fields['tunable'] = False
fields['minval'] = 0
fields['maxval'] = 2000000000 # 2GB
fields['default'] = 500000000 # 500M
fields['resource'] = 1
fields['unit'] = 1
if fields['name'].lower() == 'db_32k_cache_size':
fields['tunable'] = False
fields['minval'] = 0
fields['maxval'] = 2000000000 # 2GB
fields['default'] = 500000000 # 500M
fields['resource'] = 1
fields['unit'] = 1
if fields['name'].upper() == 'DB_RECYCLE_CACHE_SIZE':
fields['tunable'] = False
fields['minval'] = 0
fields['maxval'] = 2000000000 # 2GB
fields['default'] = 500000000 # 500M
fields['resource'] = 1
fields['unit'] = 1
if fields['name'].upper() == 'LARGE_POOL_SIZE':
fields['tunable'] = True
fields['minval'] = 0
fields['maxval'] = 2000000000 # 2GB
fields['default'] = 500000000 # 500M
fields['resource'] = 1
fields['unit'] = 1
if fields['name'].upper() == 'PGA_AGGREGATE_TARGET':
fields['tunable'] = True
fields['minval'] = 0
fields['maxval'] = 33000000000 # 33G
fields['default'] = 0
fields['resource'] = 1
fields['unit'] = 1
if fields['name'].lower() == 'bitmap_merge_area_size':
fields['tunable'] = True
fields['minval'] = 0
fields['maxval'] = 5000000000 # 3G
fields['default'] = 0
fields['resource'] = 1
fields['unit'] = 1
if fields['name'].lower() == 'create_bitmap_area_size':
fields['tunable'] = True
fields['minval'] = 0
fields['maxval'] = 5000000000 # 3G
fields['default'] = 0
fields['resource'] = 1
fields['unit'] = 1
if fields['name'].lower() == 'hash_area_size':
fields['tunable'] = True
fields['minval'] = 0
fields['maxval'] = 3000000000 # 3G
fields['default'] = 0
fields['resource'] = 1
fields['unit'] = 1
if fields['name'].lower() == 'sort_area_size':
fields['tunable'] = True
fields['minval'] = 0
fields['maxval'] = 3000000000 # 3G
fields['default'] = 0
fields['resource'] = 1
fields['unit'] = 1
if fields['name'].upper() == 'OPEN_CURSORS':
fields['tunable'] = True
fields['minval'] = 200
fields['maxval'] = 400
fields['default'] = 300
if fields['name'].upper() == 'DB_FILE_MULTIBLOCK_READ_COUNT':
fields['tunable'] = True
fields['minval'] = 20
fields['maxval'] = 256
fields['default'] = 128
if fields['name'].upper() == 'optimizer_index_cost_adj'.upper():
fields['tunable'] = False
fields['minval'] = 1
fields['maxval'] = 10000
fields['default'] = 100
if fields['name'].upper() == 'OPTIMIZER_USE_PENDING_STATISTICS':
fields['tunable'] = False
fields['minval'] = None
fields['maxval'] = None
fields['default'] = False
fields['vartype'] = 4
if fields['name'].upper() == 'OPTIMIZER_USE_INVISIBLE_INDEXES':
fields['tunable'] = False
fields['minval'] = None
fields['maxval'] = None
fields['default'] = False
fields['vartype'] = 4
if fields['name'].upper() == 'OPTIMIZER_USE_SQL_PLAN_BASELINES':
fields['tunable'] = False
fields['minval'] = None
fields['maxval'] = None
fields['default'] = True
fields['vartype'] = 4
if fields['name'].upper() == 'OPTIMIZER_CAPTURE_SQL_PLAN_BASELINES':
fields['tunable'] = False
fields['minval'] = None
fields['maxval'] = None
fields['default'] = False
fields['vartype'] = 4
if fields['name'].lower() == 'optimizer_dynamic_sampling':
fields['tunable'] = True
fields['minval'] = 2
fields['maxval'] = 10
fields['default'] = 2
if fields['name'].lower() == 'optimizer_adaptive_plans':
fields['tunable'] = True
fields['minval'] = None
fields['maxval'] = None
fields['default'] = True
fields['vartype'] = 4
if fields['name'].lower() == 'optimizer_adaptive_statistics':
fields['tunable'] = True
fields['minval'] = None
fields['maxval'] = None
fields['default'] = True
fields['vartype'] = 4
if fields['name'].lower() == 'optimizer_features_enable':
fields['tunable'] = True
fields['minval'] = None
fields['maxval'] = None
fields['default'] = '172.16.31.10'
fields['vartype'] = 5
fields['enumvals'] = '192.168.127.12,172.16.58.3,192.168.3.11,172.16.17.32,192.168.127.12,192.168.127.12,172.16.31.10'
if fields['name'].lower() == 'optimizer_inmemory_aware':
fields['tunable'] = True
fields['minval'] = None
fields['maxval'] = None
fields['default'] = True
fields['vartype'] = 4
if fields['name'].upper() == 'DISK_ASYNCH_IO':
fields['tunable'] = True
fields['vartype'] = 4
fields['default'] = True
fields['minval'] = None
fields['maxval'] = None
if fields['name'].lower() == 'db_writer_processes':
fields['tunable'] = False
fields['minval'] = 1
fields['maxval'] = 10
fields['default'] = 1
if fields['name'].lower() == 'filesystemio_options':
fields['default'] = 'none'
fields['minval'] = None
fields['maxval'] = None
fields['vartype'] = 5
fields['enumvals'] = 'asynch,directio,none,setall'
if fields['name'].lower() == 'optimizer_mode':
fields['default'] = 'ALL_ROWS'
fields['minval'] = None
fields['maxval'] = None
fields['vartype'] = 5
fields['enumvals'] = 'FIRST_ROWS_1,FIRST_ROWS_10,FIRST_ROWS_100,FIRST_ROWS_1000,FIRST_ROWS,ALL_ROWS,CHOOSE'
if fields['name'].lower() == 'workarea_size_policy':
fields['default'] = 'AUTO'
fields['minval'] = None
fields['maxval'] = None
fields['vartype'] = 5
fields['enumvals'] = 'AUTO,MANUAL'
if fields['name'].lower() == 'cursor_sharing':
fields['default'] = 'EXACT'
fields['minval'] = None
fields['maxval'] = None
fields['vartype'] = 5
fields['enumvals'] = 'SIMILAR,EXACT,FORCE'
if fields['name'].lower() == 'java_jit_enabled':
fields['minval'] = None
fields['maxval'] = None
fields['default'] = True
fields['vartype'] = 4
if fields['name'].lower() == 'java_pool_size':
fields['minval'] = 0
fields['maxval'] = 1000000000
fields['default'] = 0
fields['resource'] = 1
fields['unit'] = 1
if fields['name'].lower() == 'log_archive_max_processes':
fields['minval'] = 1
fields['maxval'] = 30
fields['default'] = 4
if fields['name'].lower() == 'commit_logging':
fields['default'] = ''
fields['minval'] = None
fields['maxval'] = None
fields['vartype'] = 5
fields['enumvals'] = ',IMMEDIATE,BATCH'
if fields['name'].lower() == 'result_cache_max_result':
fields['minval'] = 0
fields['maxval'] = 100
fields['default'] = 5
if fields['name'].lower() == 'approx_for_aggregation':
fields['minval'] = None
fields['maxval'] = None
fields['default'] = False
fields['vartype'] = 4
if fields['name'].lower() == 'approx_for_count_distinct':
fields['minval'] = None
fields['maxval'] = None
fields['default'] = False
fields['vartype'] = 4
if fields['name'].lower() == 'approx_for_percentile':
fields['minval'] = None
fields['maxval'] = None
fields['default'] = False
fields['vartype'] = 5
fields['enumvals'] = 'none,NONE,PERCENTILE_CONT,PERCENTILE_CONT DETERMINISTIC,PERCENTILE_DISC,PERCENTILE_DISC DETERMINISTIC,ALL,ALL DETERMINISTIC'
if fields['name'].lower() == 'session_cached_cursors':
fields['minval'] = 0
fields['maxval'] = 100
fields['default'] = 50
if fields['name'].lower() == 'use_large_pages':
fields['minval'] = None
fields['maxval'] = None
fields['default'] = True
fields['vartype'] = 4
if fields['name'].lower() == 'hs_autoregister':
fields['minval'] = None
fields['maxval'] = None
fields['default'] = True
fields['vartype'] = 4
if fields['name'].lower() == 'cursor_invalidation':
fields['default'] = 'IMMEDIATE'
fields['minval'] = None
fields['maxval'] = None
fields['vartype'] = 5
fields['enumvals'] = 'IMMEDIATE,DEFERRED'
if fields['name'].lower() == 'plsql_optimize_level':
fields['minval'] = 0
fields['maxval'] = 3
fields['default'] = 2
if fields['name'].lower() == 'db_big_table_cache_percent_target':
fields['minval'] = 0
fields['maxval'] = 90
fields['default'] = 0
fields['vartype'] = 2
if fields['name'].lower() == 'query_rewrite_enabled':
fields['default'] = 'TRUE'
fields['minval'] = None
fields['maxval'] = None
fields['vartype'] = 5
fields['enumvals'] = 'TRUE,FALSE,FORCE'
COLNAMES = ("NAME", "TYPE", "DEFAULT_VALUE", "DESCRIPTION")
def process_version(version, delim=','):
fields_list = []
add_fields(fields_list, version)
with open('oracle{}.csv'.format(version), 'r', newline='') as f:
reader = csv.reader(f, delimiter=delim)
header = [h.upper() for h in next(reader)]
idxs = [header.index(c) for c in COLNAMES]
ncols = len(header)
ri = 0
for row in reader:
assert ncols == len(row), (ri, ncols, len(row))
fields = {}
for i, cname in zip(idxs, COLNAMES):
value = row[i]
if isinstance(value, str):
value = value.strip()
if cname == 'NAME':
fields['name'] = value.upper()
elif cname == 'TYPE':
value = int(value)
if value == 1:
fields['vartype'] = 4 # Boolean
elif value in (3, 6):
fields['vartype'] = 2 # Integer
else:
fields['vartype'] = 1 # Assume it's a sting otherwise
elif cname == 'DEFAULT_VALUE':
fields['default'] = value
else:
fields['summary'] = value
fields.update(
scope='global',
dbms=version,
category='',
enumvals=None,
context='',
unit=3, # Other
tunable=False,
description='',
minval=None,
maxval=None,
)
set_field(fields)
fields['name'] = ('global.' + fields['name']).lower()
fields_list.append(fields)
ri += 1
fields_list = sorted(fields_list, key=itemgetter('name'))
final_metrics = [dict(model='website.KnobCatalog', fields=fs) for fs in fields_list]
filename = 'oracle-{}_knobs.json'.format(version)
with open(filename, 'w') as f:
json.dump(final_metrics, f, indent=4)
shutil.copy(filename, "../../../../website/fixtures/{}".format(filename))
def main():
process_version(19) # v19c
process_version(12) # v12.2c
process_version(121, delim='|') # v12.1c
if __name__ == '__main__':
main()
|
staddi99/AdventOfCode | 2020/day_8/input.js | const input = `acc +18
nop +222
acc -16
acc +28
jmp +475
acc -6
jmp +584
acc -12
acc -8
jmp +554
acc -9
acc +12
acc -16
acc +27
jmp +336
acc -4
jmp +214
acc +38
jmp +61
acc +3
acc +28
acc +5
acc -19
jmp +584
nop +206
jmp +506
acc +36
jmp +133
acc +20
acc +43
acc -18
jmp +409
acc +24
jmp +131
acc -12
acc +7
acc +7
jmp +454
acc +37
acc -6
nop +558
acc +31
jmp +124
acc -15
nop +201
acc -7
jmp +297
acc +3
nop +517
jmp +221
jmp +211
acc +28
acc +35
jmp +5
acc +31
nop +325
acc -15
jmp +116
jmp +1
nop +333
acc -2
acc -5
jmp +138
acc +19
acc +9
jmp +180
acc +18
jmp +228
jmp +495
jmp +382
acc +20
nop +414
nop +139
acc +33
jmp +171
acc -10
jmp +41
acc -2
jmp +80
acc +20
nop +451
acc +2
acc +24
jmp +102
acc +1
acc -11
acc +9
acc +38
jmp -73
acc +17
acc +16
acc +12
acc +43
jmp +168
jmp +286
acc +6
acc +6
jmp +271
acc -17
acc -5
acc +1
jmp -50
acc -9
acc +6
acc -2
acc +33
jmp +385
acc +18
acc +24
jmp +370
acc -5
acc +23
acc +6
jmp +98
acc -10
acc -16
jmp +329
nop +41
jmp +463
nop +224
acc +35
jmp +345
acc +34
acc -18
acc +5
jmp +177
nop -57
nop -80
acc +20
jmp -12
acc +24
acc +39
jmp +363
jmp +253
acc -14
acc +0
acc +22
jmp +118
acc +43
acc -2
jmp +300
acc -14
acc +8
acc +47
jmp +271
jmp +420
acc +33
acc +15
acc +20
acc +25
jmp +84
acc +41
jmp +420
acc +25
jmp +238
jmp +1
acc +14
jmp +415
jmp +68
jmp +262
acc +34
jmp +346
acc +39
jmp +56
jmp +364
jmp -133
acc +13
jmp +1
acc +33
jmp +408
acc +29
acc -4
jmp +319
jmp +106
jmp +228
acc -8
acc +8
acc +22
jmp -146
jmp +223
acc +27
nop +191
acc +49
jmp +331
jmp +39
jmp -170
acc +28
acc -6
acc +50
jmp +268
acc +41
nop +254
acc +28
jmp +269
jmp +140
acc +10
nop +131
acc +3
jmp -40
jmp +373
acc +47
jmp -91
acc -19
jmp +300
acc -2
jmp +1
acc +44
acc -11
jmp +306
acc +33
jmp -15
acc +9
jmp +1
jmp +144
acc +40
nop +184
nop -75
nop +228
jmp +296
acc +22
nop +364
jmp -214
jmp +18
jmp +375
acc +22
jmp -67
acc +8
acc -17
jmp +174
jmp -99
nop -45
acc +7
jmp -213
jmp -218
acc +50
nop +52
nop +98
jmp -142
acc +18
jmp +252
acc +36
jmp -194
acc +1
nop -53
jmp -127
jmp +327
acc +7
acc -9
acc +39
nop -127
jmp +84
jmp -117
nop -29
acc +43
jmp -216
acc +25
acc +16
acc +40
nop +122
jmp +140
jmp +180
acc +42
acc -5
acc -14
jmp -84
jmp -31
acc +37
acc -11
jmp -217
jmp +210
jmp +170
nop +301
jmp +309
acc +6
jmp +135
acc +6
nop -123
acc +17
jmp +315
acc -1
nop -46
nop -58
nop -59
jmp +202
acc +48
acc +38
jmp +86
acc -4
acc +33
acc +28
jmp -50
nop +43
acc +38
acc +13
jmp +33
acc +4
acc +6
jmp -78
acc +22
acc +7
acc -9
jmp -56
acc +30
nop +54
nop -81
nop +198
jmp +252
jmp +1
acc +6
acc -10
acc +29
jmp -242
jmp +1
acc +42
acc +34
acc +22
jmp +231
acc +29
acc -10
jmp -161
acc +37
acc +9
jmp -77
acc -15
acc +32
acc +32
jmp -6
acc +0
nop -124
nop +174
jmp +20
acc +45
acc +24
jmp -13
acc +6
acc -10
acc +23
acc -15
jmp +34
acc +5
acc +38
acc +42
jmp -116
acc +0
acc +8
jmp -243
acc -18
acc +25
acc +1
jmp +158
nop +65
jmp +1
jmp +151
acc +12
acc +12
jmp +1
jmp -305
jmp +29
jmp -263
acc +33
jmp +1
nop +142
jmp +78
acc +41
nop -141
acc -9
acc +5
jmp -245
jmp +41
acc +16
nop -83
jmp -28
nop -149
acc +38
jmp -15
acc +7
nop -329
acc +5
acc +21
jmp -7
acc -19
jmp -38
acc +5
acc +3
acc +10
jmp -181
jmp -240
acc +19
acc +15
acc +31
acc -11
jmp -340
acc +12
acc +46
jmp +127
acc +12
acc +31
acc +30
jmp -158
acc -10
jmp -374
jmp +50
acc +43
nop +42
acc +19
jmp -232
acc -14
acc -4
jmp +95
acc +23
acc +49
acc +31
nop -139
jmp -272
jmp -141
acc +26
acc -8
jmp +173
nop +145
nop +133
jmp +164
acc +7
jmp +23
acc -4
acc +48
jmp -138
acc +4
jmp -389
nop +156
acc +44
acc +40
jmp +146
nop -247
acc +44
jmp +1
acc +28
jmp +95
acc +13
acc +2
jmp -254
acc +24
jmp +122
acc +39
acc +0
jmp -12
jmp -179
nop -44
nop +100
acc -19
nop -47
jmp -107
acc +32
acc +33
acc +42
acc +6
jmp -366
jmp -122
acc +2
nop -443
nop +72
jmp -381
jmp -446
jmp -332
acc -7
acc +45
jmp -355
acc +27
acc -4
acc +3
jmp +96
acc +45
jmp -402
acc +45
acc -3
acc +22
jmp -141
acc +29
acc -1
jmp +29
acc -1
acc -10
jmp -208
acc +6
nop -196
jmp -218
acc -12
acc +49
nop -137
jmp -430
acc +21
jmp -110
nop -287
acc -3
jmp -42
jmp -487
acc -16
acc -1
acc +7
acc +39
jmp -119
jmp +1
acc +9
jmp -23
acc +27
jmp -300
acc +12
jmp -440
acc +2
acc +38
acc +12
jmp -84
acc +25
acc -14
jmp -418
acc -15
acc +48
jmp +1
nop -383
jmp -365
acc +47
jmp -193
acc +23
jmp -235
jmp +1
acc -4
acc +35
nop -64
jmp -87
acc +32
jmp -339
jmp -479
acc -4
acc +32
acc -10
jmp -77
acc +0
acc +47
acc +41
jmp -308
acc -8
acc -9
jmp -229
acc -14
acc +24
nop -380
acc +49
jmp -174
acc -11
nop -69
jmp +3
acc -14
jmp -89
jmp -301
acc +46
acc +8
nop -156
acc +44
jmp +1
jmp +26
acc +17
acc +23
acc +6
jmp -4
jmp -97
jmp -324
acc +2
jmp -27
nop -195
acc +3
acc -13
acc +15
jmp -19
acc +30
nop -318
jmp +19
nop -72
jmp -315
acc +4
nop +6
jmp -384
jmp -505
jmp -512
acc +33
jmp -168
jmp -443
nop -519
acc +7
acc +41
acc +15
jmp -269
nop -539
jmp -416
jmp -326
nop -221
acc +14
jmp -186
acc -1
jmp -295
acc +29
acc +43
nop -436
nop -421
jmp -123
acc +13
acc -11
acc +12
jmp -155
acc +9
acc -16
acc -15
nop -380
jmp +1`;
export default input; |
aliyun/dingtalk-sdk | dingtalk/java/src/main/java/com/aliyun/dingtalkyida_1_0/models/GetTaskCopiesRequest.java | // This file is auto-generated, don't edit it. Thanks.
package com.aliyun.dingtalkyida_1_0.models;
import com.aliyun.tea.*;
public class GetTaskCopiesRequest extends TeaModel {
// 应用ID
@NameInMap("appType")
public String appType;
// 验权token
@NameInMap("systemToken")
public String systemToken;
// 每页记录数; 必须大于0 默认10 最大值:100
@NameInMap("pageSize")
public Integer pageSize;
// 语言环境; 可选值:zh_CN/en_US
@NameInMap("language")
public String language;
// 当前页; 必须大于0 默认1
@NameInMap("pageNumber")
public Integer pageNumber;
// 关键词
@NameInMap("keyword")
public String keyword;
// 钉钉的userId
@NameInMap("userId")
public String userId;
// 流程code列表
@NameInMap("processCodes")
public String processCodes;
// 创建时间开始; 时间戳
@NameInMap("createFromTimeGMT")
public Long createFromTimeGMT;
// 创建时间结束; 时间戳
@NameInMap("createToTimeGMT")
public Long createToTimeGMT;
public static GetTaskCopiesRequest build(java.util.Map<String, ?> map) throws Exception {
GetTaskCopiesRequest self = new GetTaskCopiesRequest();
return TeaModel.build(map, self);
}
public GetTaskCopiesRequest setAppType(String appType) {
this.appType = appType;
return this;
}
public String getAppType() {
return this.appType;
}
public GetTaskCopiesRequest setSystemToken(String systemToken) {
this.systemToken = systemToken;
return this;
}
public String getSystemToken() {
return this.systemToken;
}
public GetTaskCopiesRequest setPageSize(Integer pageSize) {
this.pageSize = pageSize;
return this;
}
public Integer getPageSize() {
return this.pageSize;
}
public GetTaskCopiesRequest setLanguage(String language) {
this.language = language;
return this;
}
public String getLanguage() {
return this.language;
}
public GetTaskCopiesRequest setPageNumber(Integer pageNumber) {
this.pageNumber = pageNumber;
return this;
}
public Integer getPageNumber() {
return this.pageNumber;
}
public GetTaskCopiesRequest setKeyword(String keyword) {
this.keyword = keyword;
return this;
}
public String getKeyword() {
return this.keyword;
}
public GetTaskCopiesRequest setUserId(String userId) {
this.userId = userId;
return this;
}
public String getUserId() {
return this.userId;
}
public GetTaskCopiesRequest setProcessCodes(String processCodes) {
this.processCodes = processCodes;
return this;
}
public String getProcessCodes() {
return this.processCodes;
}
public GetTaskCopiesRequest setCreateFromTimeGMT(Long createFromTimeGMT) {
this.createFromTimeGMT = createFromTimeGMT;
return this;
}
public Long getCreateFromTimeGMT() {
return this.createFromTimeGMT;
}
public GetTaskCopiesRequest setCreateToTimeGMT(Long createToTimeGMT) {
this.createToTimeGMT = createToTimeGMT;
return this;
}
public Long getCreateToTimeGMT() {
return this.createToTimeGMT;
}
}
|
Miyo-Excellent/Friender_Advance | src/app/views/User/views/components/Profile/components/ProfileInformation/components/Header/index.js | // Dependencies
import { connect } from 'react-redux';
import React, { Component } from 'react';
// Styles
import styles from './scss/Header.scss';
class Header extends Component {
constructor(props) {
super(props);
}
render() {
const { user } = this.props;
const headerWrapperCustomStyles = (options) => {
const { header } = options;
return {
background: `
hsla(0, 0%, 98%, 1)
url(${header}) no-repeat`
};
};
return (
<header className={styles.header}>
<div className={styles.header_whapper} style={headerWrapperCustomStyles({header: user.header})}>
<div className={styles.user_info}>
<div className={styles.picture}>
<img src={user.picture} alt={`Foto de perfil de ${user.name} ${user.lastname}`} />
</div>
<div className={styles.full_name}>
<span>{`${user.name} ${user.lastname}`}</span>
</div>
<div className={styles.email}>
<span>{`${user.email}`}</span>
</div>
</div>
</div>
<div className={styles.information}>
<div className={styles.connect}>
<div className={styles.connectors}>
<span className={styles.title}>Seguidos</span>
<span className={styles.how}>{user.connectors.length}</span>
</div>
</div>
</div>
</header>
);
}
}
const mapStateToProps = state => ({
devices: state.devices,
user: state.user
});
const mapDispatchToProps = dispatch => ({});
export default connect(mapStateToProps, mapDispatchToProps)(Header);
|
ChrisHilborne/to-do-api | src/main/java/com/chilborne/todoapi/security/SecurityConfig.java | <gh_stars>0
package com.chilborne.todoapi.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/api/v1/user/register");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
.and()
.csrf()
.disable()
.antMatcher("/api/v1/**")
.authorizeRequests()
.anyRequest()
.hasRole("USER")
.and()
.httpBasic();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
|
TrustedBSD/sebsd | sys/dev/usb/if_cdcereg.h | /*
* Copyright (c) 2003-2005 <NAME>
* 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.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by <NAME>.
* 4. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY <NAME> 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 <NAME>, THE VOICES IN HIS HEAD OR
* THE 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.
*
* $FreeBSD: src/sys/dev/usb/if_cdcereg.h,v 1.6 2005/09/26 05:29:46 sobomax Exp $
*/
#ifndef _USB_IF_CDCEREG_H_
#define _USB_IF_CDCEREG_H_
struct cdce_type {
struct usb_devno cdce_dev;
u_int16_t cdce_flags;
#define CDCE_ZAURUS 1
#define CDCE_NO_UNION 2
};
struct cdce_softc {
struct ifnet *cdce_ifp;
#define GET_IFP(sc) ((sc)->cdce_ifp)
struct ifmedia cdce_ifmedia;
usbd_device_handle cdce_udev;
usbd_interface_handle cdce_data_iface;
int cdce_bulkin_no;
usbd_pipe_handle cdce_bulkin_pipe;
int cdce_bulkout_no;
usbd_pipe_handle cdce_bulkout_pipe;
char cdce_dying;
device_t cdce_dev;
int cdce_unit;
struct ue_cdata cdce_cdata;
struct timeval cdce_rx_notice;
int cdce_rxeof_errors;
u_int16_t cdce_flags;
struct mtx cdce_mtx;
struct usb_qdat q;
char devinfo[1024];
};
/* We are still under Giant */
#if 0
#define CDCE_LOCK(_sc) mtx_lock(&(_sc)->cdce_mtx)
#define CDCE_UNLOCK(_sc) mtx_unlock(&(_sc)->cdce_mtx)
#else
#define CDCE_LOCK(_sc)
#define CDCE_UNLOCK(_sc)
#endif
#endif /* _USB_IF_CDCEREG_H_ */
|
Xtra-Computing/briskstream | FlinkBenchmarks/src/main/java/applications/FlinkRunner.java | <filename>FlinkBenchmarks/src/main/java/applications/FlinkRunner.java
package applications;
import applications.topology.benchmarks.*;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.ParameterException;
import constants.*;
import org.apache.flink.storm.api.FlinkLocalCluster;
import org.apache.flink.storm.api.FlinkSubmitter;
import org.apache.flink.storm.api.FlinkTopology;
import org.apache.storm.Config;
import org.apache.storm.generated.AlreadyAliveException;
import org.apache.storm.generated.InvalidTopologyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.Configuration;
import java.io.IOException;
import java.util.Properties;
//import applications.Brisk.topology.special_LRF.toll.MemoryTollDataStore;
//import applications.Brisk.topology.special_LRF.tools.Helper;
public class FlinkRunner extends abstractRunner {
private static final Logger LOG = LoggerFactory.getLogger(FlinkRunner.class);
public static FlinkLocalCluster cluster;
private final AppDriver driver;
public Config config = new Config();
public FlinkRunner() {
driver = new AppDriver();
// driver.addApp("StreamingAnalysis", StreamingAnalysis.class);//Extra
driver.addApp("WordCount", WordCount.class);
driver.addApp("FraudDetection", FraudDetection.class);
driver.addApp("FraudDetection_latency", FraudDetection_latency.class);
driver.addApp("SpikeDetection", SpikeDetection.class);
driver.addApp("SpikeDetection_latency", SpikeDetection_latency.class);
// driver.addApp("TrafficMonitoring", TrafficMonitoring.class);
driver.addApp("LogProcessing_latency", LogProcessing_latency.class);
// driver.addApp("VoIPSTREAM", VoIPSTREAM.class);
driver.addApp("LinearRoad", LinearRoad.class);//
driver.addApp("LinearRoad_latency", LinearRoad_latency.class);//
}
public static void main(String[] args) {
FlinkRunner runner = new FlinkRunner();
JCommander cmd = new JCommander(runner);
try {
cmd.parse(args);
} catch (ParameterException ex) {
System.err.println("Argument error: " + ex.getMessage());
cmd.usage();
System.exit(1);
}
try {
runner.run();
} catch (InterruptedException ex) {
LOG.error("Error in running Brisk.topology locally", ex);
}
}
/**
* Run the Brisk.topology locally
*
* @param topology The Brisk.topology to be executed
* @param topologyName The name of the Brisk.topology
* @param conf The Configs for the Brisk.execution
* @param runtimeInSeconds For how much time the Brisk.topology will run
* @throws InterruptedException
*/
public static void runTopologyLocally(FlinkTopology topology, String topologyName, Config conf,
int runtimeInSeconds) throws InterruptedException {
LOG.info("Starting Flink on local mode to run for {} seconds", runtimeInSeconds);
cluster = new FlinkLocalCluster();
LOG.info("Topology {} submitted", topologyName);
try {
cluster.submitTopology(topologyName, conf, topology);
} catch (Exception e) {
e.printStackTrace();
}
Thread.sleep((long) runtimeInSeconds * 1000);
cluster.shutdown();
}
/**
* Run the Brisk.topology remotely
*
* @param topology The Brisk.topology to be executed
* @param topologyName The name of the Brisk.topology
* @param conf The Configs for the Brisk.execution
* @throws AlreadyAliveException
* @throws InvalidTopologyException
*/
public static void runTopologyRemotely(FlinkTopology topology, String topologyName, Config conf) {
// conf.registerMetricsConsumer(LoggingMetricsConsumer.class, 2);
//conf.setMaxSpoutPending(Conf.getInt("max_pending", 5000));
// This will simply log all Metrics received into
// $STORM_HOME/logs/metrics.log on one or more worker nodes.
// conf.registerMetricsConsumer(LoggingMetricsConsumer.class, 2);
//LOG.info("max pending;" + conf.get("Brisk.topology.max.spout.pending"));
//LOG.info("metrics.output:" + Conf.getString("metrics.output"));
//LOG.info("NumWorkers:" + Conf.getInt("num_workers"));
LOG.info("Run with Config:" + conf.values());
try {
FlinkSubmitter.submitTopology(topologyName, conf, topology);
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() throws InterruptedException {
// Loads the Config file set by the user or the default
// Config
try {
// load default Config
if (configStr == null) {
String cfg = String.format(CFG_PATH, application);
Properties p = loadProperties(cfg);
config.put(BaseConstants.BaseConf.SPOUT_THREADS, sthread);
config.put(BaseConstants.BaseConf.SINK_THREADS, sithread);
config.putAll(Configuration.fromProperties(p));
if (mode.equalsIgnoreCase(RUN_REMOTE)) {
final String spout_class = String.valueOf(config.get("mb.spout.class"));
if (spout_class.equals("applications.spout.LocalStateSpout")) {
LOG.info("Please use kafkaSpout in cluster mode!!!");
System.exit(-1);
}
}
configuration(config);
} else {
config.putAll(Configuration.fromStr(configStr));
LOG.info("Loaded Config from command line argument");
}
} catch (IOException ex) {
LOG.error("Unable to load Config file", ex);
throw new RuntimeException("Unable to load Config file", ex);
}
// Get the descriptor for the given application
AppDriver.AppDescriptor app = driver.getApp(application);
if (app == null) {
throw new RuntimeException("The given application name " + application + " is invalid");
}
// In case no Brisk.topology names is given, create one
if (topologyName == null) {
topologyName = application;
}
config.put(BaseConstants.BaseConf.SPOUT_THREADS, sthread);
config.put(BaseConstants.BaseConf.SINK_THREADS, sithread);
config.put(BaseConstants.BaseConf.PARSER_THREADS, pthread);
//set total parallelism, equally parallelism
int max_hz = 0;
switch (application) {
case "StreamingAnalysis": {
int threads = (int) Math.ceil(tthread / 5.0);
config.put(BaseConstants.BaseConf.PARSER_THREADS, threads);
config.put(streamingAnalysisConstants.Conf.EXECUTOR_THREADS1, threads);
config.put(streamingAnalysisConstants.Conf.EXECUTOR_THREADS2, threads);
config.put(streamingAnalysisConstants.Conf.EXECUTOR_THREADS3, threads);
config.put(streamingAnalysisConstants.Conf.EXECUTOR_THREADS4, threads);
break;
}
case "WordCount": {
//config.put(BaseConstants.BaseConf.SPOUT_THREADS, 2);//special treatment to WC>
int threads = (int) Math.ceil(tthread / 3.0);
LOG.info("Average threads:" + threads);
config.put(BaseConstants.BaseConf.PARSER_THREADS, threads);//insignificant
config.put(WordCountConstants.Conf.SPLITTER_THREADS, threads);//2
config.put(WordCountConstants.Conf.COUNTER_THREADS, threads);
max_hz = WordCountConstants.max_hz;
break;
}
case "FraudDetection": {
//config.put(BaseConstants.BaseConf.SPOUT_THREADS, 1);//special treatment to SD>
int threads = Math.max(1, (int) Math.floor((tthread - sthread - sithread) / 2.0));
config.put(BaseConstants.BaseConf.PARSER_THREADS, threads);//insignificant
config.put(FraudDetectionConstants.Conf.PREDICTOR_THREADS, threads);
max_hz = FraudDetectionConstants.max_hz;
break;
}
case "SpikeDetection": {
//config.put(BaseConstants.BaseConf.SPOUT_THREADS, 1);//special treatment to SD>
int threads = Math.max(1, (int) Math.floor((tthread - sthread - sithread) / 3.0));
LOG.info("Average threads:" + threads);
config.put(BaseConstants.BaseConf.PARSER_THREADS, threads);
config.put(SpikeDetectionConstants.Conf.MOVING_AVERAGE_THREADS, threads);//insignificant
config.put(SpikeDetectionConstants.Conf.SPIKE_DETECTOR_THREADS, threads);//insignificant
max_hz = SpikeDetectionConstants.max_hz;
break;
}
// case "TrafficMonitoring": {
// int threads = tthread / 1;
//// config.put(BaseConstants.BaseConf.PARSER_THREADS, threads);
// config.put(TrafficMonitoringConstants.Conf.MAP_MATCHER_THREADS, threads);//*5
//// config.put(TrafficMonitoringConstants.Conf.SPEED_CALCULATOR_THREADS, threads);
// max_hz = TrafficMonitoringConstants.max_hz;
// break;
// }
case "LogProcessing": {
config.put(BaseConstants.BaseConf.SPOUT_THREADS, 1);//special treatment to LG>
int threads = (int) Math.ceil(tthread / 5.0);
LOG.info("Average threads:" + threads);
config.put(BaseConstants.BaseConf.PARSER_THREADS, threads);
config.put(LogProcessingConstants.Conf.GEO_FINDER_THREADS, threads);//2
config.put(LogProcessingConstants.Conf.GEO_STATS_THREADS, threads);//insignificant
config.put(LogProcessingConstants.Conf.STATUS_COUNTER_THREADS, threads);//insignificant
config.put(LogProcessingConstants.Conf.VOLUME_COUNTER_THREADS, threads);//insignificant
break;
}
case "VoIPSTREAM": {
int threads = (int) Math.ceil(tthread / 11.0);
LOG.info("Average threads:" + threads);
config.put(BaseConstants.BaseConf.PARSER_THREADS, threads);
config.put(VoIPSTREAMConstants.Conf.VAR_DETECT_THREADS, threads);
config.put(VoIPSTREAMConstants.Conf.RCR_THREADS, threads);//2
config.put(VoIPSTREAMConstants.Conf.ECR_THREADS, threads);//2
config.put(VoIPSTREAMConstants.Conf.ENCR_THREADS, threads);//insignificant
config.put(VoIPSTREAMConstants.Conf.CT24_THREADS, threads);//insignificant
config.put(VoIPSTREAMConstants.Conf.ECR24_THREADS, threads);
// config.put(VoIPSTREAMConstants.Conf.GLOBAL_ACD, threads); 1
config.put(VoIPSTREAMConstants.Conf.FOFIR_THREADS, threads);//2
config.put(VoIPSTREAMConstants.Conf.URL_THREADS, threads);
config.put(VoIPSTREAMConstants.Conf.ACD_THREADS, threads);
config.put(VoIPSTREAMConstants.Conf.SCORER_THREADS, threads);
break;
}
case "LinearRoad": {
int threads = Math.max(1, (int) Math.floor((tthread - sthread - sithread) / 10.0));
// LOG.info("Average threads:" + threads);
config.put(BaseConstants.BaseConf.PARSER_THREADS, threads);
config.put(LinearRoadConstants.Conf.DispatcherBoltThreads, threads);
config.put(LinearRoadConstants.Conf.AccidentDetectionBoltThreads, threads);//insignificant
config.put(LinearRoadConstants.Conf.COUNT_VEHICLES_Threads, threads);//insignificant
config.put(LinearRoadConstants.Conf.AccidentNotificationBoltThreads, threads);//insignificant
config.put(LinearRoadConstants.Conf.toll_cv_BoltThreads, threads);//insignificant
config.put(LinearRoadConstants.Conf.toll_las_BoltThreads, threads);//insignificant
config.put(LinearRoadConstants.Conf.toll_pos_BoltThreads, threads);//insignificant
config.put(LinearRoadConstants.Conf.AverageSpeedThreads, threads);
config.put(LinearRoadConstants.Conf.LatestAverageVelocityThreads, threads);
break;
}
}
// Get the Brisk.topology and execute on Storm
FlinkTopology flinkTopology = app.getTopology(topologyName, config);
switch (mode) {
case RUN_LOCAL:
runTopologyLocally(flinkTopology, topologyName, config, runtimeInSeconds * 2);
break;
case RUN_REMOTE:
runTopologyRemotely(flinkTopology, topologyName, config);
break;
default:
throw new RuntimeException("Valid running modes are 'local' and 'remote'");
}
}
}
|
mmiladi/galaxy | config/plugins/visualizations/charts/static/client/views/groups.js | <reponame>mmiladi/galaxy
/** This class renders the chart data selection form with repeats. */
define( [ 'utils/utils', 'mvc/ui/ui-misc', 'mvc/form/form-view', 'mvc/form/form-repeat', 'mvc/form/form-data', 'plugin/views/description' ],
function( Utils, Ui, Form, Repeat, FormData, Description ) {
var GroupView = Backbone.View.extend({
initialize: function( app, options ) {
var self = this;
this.app = app;
this.chart = app.chart;
this.group = options.group;
this.setElement( $( '<div/>' ) );
this.listenTo( this.chart, 'change:dataset_id change:type', function() { self.render() } );
this.render();
},
render: function() {
var self = this;
var inputs = this.chart.definition.groups ? Utils.clone( this.chart.definition.groups ) : {};
var dataset_id = this.chart.get( 'dataset_id' );
var chart_type = this.chart.get( 'type' );
var chart_definition = this.chart.definition;
if ( dataset_id && chart_type ) {
this.chart.state( 'wait', 'Loading metadata...' );
this.app.deferred.execute( function( process ) {
Utils.get({
url : Galaxy.root + 'api/datasets/' + dataset_id,
cache : true,
success : function( dataset ) {
var data_columns = {};
FormData.visitInputs( inputs, function( input, prefixed ) {
if ( input.type == 'data_column' ) {
data_columns[ prefixed ] = Utils.clone( input );
var columns = [];
input.is_auto && columns.push( { 'label': 'Column: Row Number', 'value': 'auto' } );
input.is_zero && columns.push( { 'label' : 'Column: None', 'value' : 'zero' } );
var meta = dataset.metadata_column_types;
for ( var key in meta ) {
var valid = ( [ 'int', 'float' ].indexOf( meta[ key ] ) != -1 && input.is_numeric ) || input.is_label;
valid && columns.push( { 'label' : 'Column: ' + ( parseInt( key ) + 1 ), 'value' : key } );
}
input.data = columns;
}
var model_value = self.group.get( prefixed );
model_value !== undefined && !input.hidden && ( input.value = model_value );
});
inputs[ '__data_columns' ] = { name: '__data_columns', type: 'hidden', hidden: true, value: data_columns };
self.chart.state( 'ok', 'Metadata initialized...' );
self.form = new Form( {
inputs : inputs,
cls : 'ui-portlet-plain',
onchange: function() {
self.group.set( self.form.data.create() );
self.chart.set( 'modified', true );
}
} );
self.group.set( self.form.data.create() );
self.$el.empty().append( self.form.$el );
process.resolve();
}
});
});
}
}
});
return Backbone.View.extend({
initialize: function( app ) {
var self = this;
this.app = app;
this.chart = app.chart;
this.repeat = new Repeat.View({
title : 'Data series',
title_new : 'Data series',
min : 1,
onnew : function() { self.chart.groups.add( { id : Utils.uid() } ) }
});
this.description = new Description( this.app );
this.message = new Ui.Message( { message : 'There are no options for this visualization type.', persistent : true, status : 'info' } );
this.setElement( $( '<div/>' ).append( this.description.$el )
.append( this.repeat.$el.addClass( 'ui-margin-bottom' ) )
.append( this.message.$el.addClass( 'ui-margin-bottom' ) ) );
this.listenTo( this.chart, 'change', function() { self.render() } );
this.listenTo( this.chart.groups, 'add remove reset', function() { self.chart.set( 'modified', true ) } );
this.listenTo( this.chart.groups, 'remove', function( group ) { self.repeat.del( group.id ) } );
this.listenTo( this.chart.groups, 'reset', function() { self.repeat.delAll() } );
this.listenTo( this.chart.groups, 'add', function( group ) {
self.repeat.add({
id : group.id,
cls : 'ui-portlet-panel',
$el : ( new GroupView( self.app, { group: group } ) ).$el,
ondel : function() { self.chart.groups.remove( group ) }
});
});
},
render: function() {
if ( _.size( this.chart.definition.groups ) > 0 ) {
this.repeat.$el.show();
this.message.$el.hide();
} else {
this.repeat.$el.hide();
this.message.$el.show();
}
}
});
}); |
AlexAtNet/galgo | solutions/hackerrank/palindrome-index/palindrome-index.go | package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
r := bufio.NewReader(os.Stdin)
d, _ := r.ReadBytes('\n')
n, _ := strconv.Atoi(strings.Trim(string(d), "\n"))
for i := 0; i < n; i++ {
d, _ = r.ReadBytes('\n')
line := strings.Trim(string(d), "\n")
if check(line, -1) {
fmt.Printf("-1\n")
continue
}
for j := 0; j < len(line); j++ {
if check(line, j) {
fmt.Printf("%v\n", j)
break
}
}
}
}
func check(word string, ex int) bool {
i := -1
j := len(word)
for {
i += 1
j -= 1
if i == ex {
i += 1
}
if j == ex {
j -= 1
}
if i > j {
return true
}
if word[i] != word[j] {
return false
}
}
return true
}
|
hpham/odftoolkit | odfdom/src/main/java/org/odftoolkit/odfdom/dom/element/table/TableDataPilotFieldReferenceElement.java | <reponame>hpham/odftoolkit<gh_stars>10-100
/**
* **********************************************************************
*
* <p>DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* <p>Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved.
*
* <p>Use is subject to license terms.
*
* <p>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. You can also obtain a copy of the License at
* http://odftoolkit.org/docs/license.txt
*
* <p>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.
*
* <p>See the License for the specific language governing permissions and limitations under the
* License.
*
* <p>**********************************************************************
*/
/*
* This file is automatically generated.
* Don't edit manually.
*/
package org.odftoolkit.odfdom.dom.element.table;
import org.odftoolkit.odfdom.dom.DefaultElementVisitor;
import org.odftoolkit.odfdom.dom.OdfDocumentNamespace;
import org.odftoolkit.odfdom.dom.attribute.table.TableFieldNameAttribute;
import org.odftoolkit.odfdom.dom.attribute.table.TableMemberNameAttribute;
import org.odftoolkit.odfdom.dom.attribute.table.TableMemberTypeAttribute;
import org.odftoolkit.odfdom.dom.attribute.table.TableTypeAttribute;
import org.odftoolkit.odfdom.pkg.ElementVisitor;
import org.odftoolkit.odfdom.pkg.OdfElement;
import org.odftoolkit.odfdom.pkg.OdfFileDom;
import org.odftoolkit.odfdom.pkg.OdfName;
/** DOM implementation of OpenDocument element {@odf.element table:data-pilot-field-reference}. */
public class TableDataPilotFieldReferenceElement extends OdfElement {
public static final OdfName ELEMENT_NAME =
OdfName.newName(OdfDocumentNamespace.TABLE, "data-pilot-field-reference");
/**
* Create the instance of <code>TableDataPilotFieldReferenceElement</code>
*
* @param ownerDoc The type is <code>OdfFileDom</code>
*/
public TableDataPilotFieldReferenceElement(OdfFileDom ownerDoc) {
super(ownerDoc, ELEMENT_NAME);
}
/**
* Get the element name
*
* @return return <code>OdfName</code> the name of element {@odf.element
* table:data-pilot-field-reference}.
*/
public OdfName getOdfName() {
return ELEMENT_NAME;
}
/**
* Receives the value of the ODFDOM attribute representation <code>TableFieldNameAttribute</code>
* , See {@odf.attribute table:field-name}
*
* <p>Attribute is mandatory.
*
* @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set
* and no default value defined.
*/
public String getTableFieldNameAttribute() {
TableFieldNameAttribute attr =
(TableFieldNameAttribute) getOdfAttribute(OdfDocumentNamespace.TABLE, "field-name");
if (attr != null) {
return String.valueOf(attr.getValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>TableFieldNameAttribute</code> , See
* {@odf.attribute table:field-name}
*
* @param tableFieldNameValue The type is <code>String</code>
*/
public void setTableFieldNameAttribute(String tableFieldNameValue) {
TableFieldNameAttribute attr = new TableFieldNameAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setValue(tableFieldNameValue);
}
/**
* Receives the value of the ODFDOM attribute representation <code>TableMemberNameAttribute</code>
* , See {@odf.attribute table:member-name}
*
* @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set
* and no default value defined.
*/
public String getTableMemberNameAttribute() {
TableMemberNameAttribute attr =
(TableMemberNameAttribute) getOdfAttribute(OdfDocumentNamespace.TABLE, "member-name");
if (attr != null) {
return String.valueOf(attr.getValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>TableMemberNameAttribute</code> , See
* {@odf.attribute table:member-name}
*
* @param tableMemberNameValue The type is <code>String</code>
*/
public void setTableMemberNameAttribute(String tableMemberNameValue) {
TableMemberNameAttribute attr = new TableMemberNameAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setValue(tableMemberNameValue);
}
/**
* Receives the value of the ODFDOM attribute representation <code>TableMemberTypeAttribute</code>
* , See {@odf.attribute table:member-type}
*
* <p>Attribute is mandatory.
*
* @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set
* and no default value defined.
*/
public String getTableMemberTypeAttribute() {
TableMemberTypeAttribute attr =
(TableMemberTypeAttribute) getOdfAttribute(OdfDocumentNamespace.TABLE, "member-type");
if (attr != null) {
return String.valueOf(attr.getValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>TableMemberTypeAttribute</code> , See
* {@odf.attribute table:member-type}
*
* @param tableMemberTypeValue The type is <code>String</code>
*/
public void setTableMemberTypeAttribute(String tableMemberTypeValue) {
TableMemberTypeAttribute attr = new TableMemberTypeAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setValue(tableMemberTypeValue);
}
/**
* Receives the value of the ODFDOM attribute representation <code>TableTypeAttribute</code> , See
* {@odf.attribute table:type}
*
* <p>Attribute is mandatory.
*
* @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set
* and no default value defined.
*/
public String getTableTypeAttribute() {
TableTypeAttribute attr =
(TableTypeAttribute) getOdfAttribute(OdfDocumentNamespace.TABLE, "type");
if (attr != null) {
return String.valueOf(attr.getValue());
}
return null;
}
/**
* Sets the value of ODFDOM attribute representation <code>TableTypeAttribute</code> , See
* {@odf.attribute table:type}
*
* @param tableTypeValue The type is <code>String</code>
*/
public void setTableTypeAttribute(String tableTypeValue) {
TableTypeAttribute attr = new TableTypeAttribute((OdfFileDom) this.ownerDocument);
setOdfAttribute(attr);
attr.setValue(tableTypeValue);
}
@Override
public void accept(ElementVisitor visitor) {
if (visitor instanceof DefaultElementVisitor) {
DefaultElementVisitor defaultVisitor = (DefaultElementVisitor) visitor;
defaultVisitor.visit(this);
} else {
visitor.visit(this);
}
}
}
|
Iron-Panthers/FTC-2017 | TeamCode/src/main/java/org/firstinspires/ftc/team7316/util/commands/sensors/PollColor.java | package org.firstinspires.ftc.team7316.util.commands.sensors;
import org.firstinspires.ftc.team7316.util.Constants;
import org.firstinspires.ftc.team7316.util.Hardware;
import org.firstinspires.ftc.team7316.util.commands.Command;
import org.firstinspires.ftc.team7316.util.subsystems.Subsystems;
/**
* Created by jerry on 11/14/17.
*/
public class PollColor extends Command {
private int iteration = 0;
public PollColor() {
requires(Subsystems.instance.jewelArm);
}
@Override
public void init() {
Hardware.instance.colorWrapper.reset();
}
@Override
public void loop() {
Hardware.instance.colorWrapper.push();
Hardware.instance.colorWrapper.logSums();
Hardware.instance.colorWrapper.logColors();
iteration++;
}
@Override
public boolean shouldRemove() {
return iteration >= Constants.COLOR_BUFFER_SIZE;
}
@Override
protected void end() {
Hardware.instance.colorWrapper.setNoColor();
}
}
|
openeuler-mirror/radiaTest | radiaTest-web/src/views/backendTask/modules/taskSocket.js | import { Socket } from '@/socket';
import config from '@/assets/config/settings';
import { getTask } from './taskTable';
function connectSocket() {
const socketObj = new Socket(`${config.websocketProtocol}://${config.serverPath}/celerytask`);
console.log('connect');
socketObj.connect();
socketObj.listen('update', () => {
getTask();
});
}
export { connectSocket };
|
turbo-play/ewallet | apps/admin_panel/assets/src/helpers/copier.js | <reponame>turbo-play/ewallet<gh_stars>1-10
export default function copyToClipboard(text) {
const textArea = document.createElement('textarea');
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
try {
document.execCommand('copy');
} catch (error) {
console.log('Unable to copy'); //eslint-disable-line
}
document.body.removeChild(textArea);
}
|
steinarvk/orclib | module/orc-tinkgcpkms/module.go | <reponame>steinarvk/orclib
package orctinkgcpkms
import (
"github.com/google/tink/go/core/registry"
"github.com/google/tink/go/integration/gcpkms"
"github.com/sirupsen/logrus"
"github.com/steinarvk/orc"
)
type Module struct {
}
func (m *Module) ModuleName() string { return "TinkGCPKMS" }
var M = &Module{}
func (m *Module) OnRegister(hooks orc.ModuleHooks) {
hooks.OnUse(func(ctx orc.UseContext) {
})
hooks.OnSetup(func() error {
const (
prefix = "gcp-kms://"
)
client := &gcpkms.GCPClient{}
_, err := client.LoadDefaultCredentials()
if err != nil {
logrus.Infof("GCP KMS: %v", err)
return nil
}
registry.RegisterKMSClient(client)
return nil
})
}
|
jd3538/Marist-Sakai-11.x | gradebookng/tool/src/java/org/sakaiproject/gradebookng/tool/panels/SettingsGradeReleasePanel.java | package org.sakaiproject.gradebookng.tool.panels;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ajax.AjaxEventBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Radio;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.sakaiproject.gradebookng.business.GbCategoryType;
import org.sakaiproject.gradebookng.tool.model.GbSettings;
import org.sakaiproject.gradebookng.tool.pages.SettingsPage;
import org.sakaiproject.service.gradebook.shared.GradebookInformation;
public class SettingsGradeReleasePanel extends BasePanel {
private static final long serialVersionUID = 1L;
IModel<GbSettings> model;
Label preview;
Label minimumOptions;
private boolean expanded;
AjaxCheckBox points;
public SettingsGradeReleasePanel(final String id, final IModel<GbSettings> model, final boolean expanded) {
super(id, model);
this.model = model;
this.expanded = expanded;
}
@Override
public void onInitialize() {
super.onInitialize();
final SettingsPage settingsPage = (SettingsPage) getPage();
final WebMarkupContainer settingsGradeReleasePanel = new WebMarkupContainer("settingsGradeReleasePanel");
// Preserve the expand/collapse state of the panel
settingsGradeReleasePanel.add(new AjaxEventBehavior("shown.bs.collapse") {
@Override
protected void onEvent(final AjaxRequestTarget ajaxRequestTarget) {
settingsGradeReleasePanel.add(new AttributeModifier("class", "panel-collapse collapse in"));
SettingsGradeReleasePanel.this.expanded = true;
}
});
settingsGradeReleasePanel.add(new AjaxEventBehavior("hidden.bs.collapse") {
@Override
protected void onEvent(final AjaxRequestTarget ajaxRequestTarget) {
settingsGradeReleasePanel.add(new AttributeModifier("class", "panel-collapse collapse"));
SettingsGradeReleasePanel.this.expanded = false;
}
});
if (this.expanded) {
settingsGradeReleasePanel.add(new AttributeModifier("class", "panel-collapse collapse in"));
}
add(settingsGradeReleasePanel);
// display released items to students
final AjaxCheckBox displayReleased = new AjaxCheckBox("displayReleased",
new PropertyModel<Boolean>(this.model, "gradebookInformation.displayReleasedGradeItemsToStudents")) {
private static final long serialVersionUID = 1L;
@Override
protected void onUpdate(final AjaxRequestTarget target) {
// nothing required
}
};
displayReleased.setOutputMarkupId(true);
settingsGradeReleasePanel.add(displayReleased);
// display course grade
final AjaxCheckBox displayCourseGrade = new AjaxCheckBox("displayCourseGrade",
new PropertyModel<Boolean>(this.model, "gradebookInformation.courseGradeDisplayed")) {
private static final long serialVersionUID = 1L;
@Override
protected void onUpdate(final AjaxRequestTarget target) {
// update preview
target.add(SettingsGradeReleasePanel.this.preview);
}
};
displayCourseGrade.setOutputMarkupId(true);
settingsGradeReleasePanel.add(displayCourseGrade);
// course grade type container
final WebMarkupContainer courseGradeType = new WebMarkupContainer("courseGradeType") {
private static final long serialVersionUID = 1L;
@Override
public boolean isVisible() {
return displayCourseGrade.getModelObject();
}
};
courseGradeType.setOutputMarkupPlaceholderTag(true);
settingsGradeReleasePanel.add(courseGradeType);
// letter grade
final AjaxCheckBox letterGrade = new AjaxCheckBox("letterGrade",
new PropertyModel<Boolean>(this.model, "gradebookInformation.courseLetterGradeDisplayed")) {
private static final long serialVersionUID = 1L;
@Override
protected void onUpdate(final AjaxRequestTarget target) {
// update preview and validation
target.add(SettingsGradeReleasePanel.this.preview);
target.add(SettingsGradeReleasePanel.this.minimumOptions);
}
};
letterGrade.setOutputMarkupId(true);
courseGradeType.add(letterGrade);
// percentage
final AjaxCheckBox percentage = new AjaxCheckBox("percentage",
new PropertyModel<Boolean>(this.model, "gradebookInformation.courseAverageDisplayed")) {
private static final long serialVersionUID = 1L;
@Override
protected void onUpdate(final AjaxRequestTarget target) {
// update preview and validation
target.add(SettingsGradeReleasePanel.this.preview);
target.add(SettingsGradeReleasePanel.this.minimumOptions);
}
};
percentage.setOutputMarkupId(true);
courseGradeType.add(percentage);
// points
this.points = new AjaxCheckBox("points",
new PropertyModel<Boolean>(this.model, "gradebookInformation.coursePointsDisplayed")) {
private static final long serialVersionUID = 1L;
@Override
protected void onUpdate(final AjaxRequestTarget target) {
// update preview and validation
target.add(SettingsGradeReleasePanel.this.preview);
target.add(SettingsGradeReleasePanel.this.minimumOptions);
// if points selected, disable categories and weighting
final GradebookInformation settings = SettingsGradeReleasePanel.this.model.getObject().getGradebookInformation();
final Radio<Integer> categoriesAndWeightingRadio = settingsPage.getSettingsCategoryPanel().getCategoriesAndWeightingRadio();
if (settings.isCoursePointsDisplayed()) {
categoriesAndWeightingRadio.setEnabled(false);
} else {
categoriesAndWeightingRadio.setEnabled(true);
}
target.add(categoriesAndWeightingRadio);
}
};
this.points.setOutputMarkupId(true);
courseGradeType.add(this.points);
// minimum options label. only shows if we have too few selected
this.minimumOptions = new Label("minimumOptions", new ResourceModel("settingspage.displaycoursegrade.notenough")) {
private static final long serialVersionUID = 1L;
@Override
public boolean isVisible() {
final GradebookInformation settings = SettingsGradeReleasePanel.this.model.getObject().getGradebookInformation();
// validation label
if (settings.isCourseGradeDisplayed()) {
int displayOptions = 0;
if (settings.isCourseLetterGradeDisplayed()) {
displayOptions++;
}
if (settings.isCourseAverageDisplayed()) {
displayOptions++;
}
if (settings.isCoursePointsDisplayed()) {
displayOptions++;
}
if (displayOptions == 0) {
return true;
}
}
return false;
}
};
this.minimumOptions.setOutputMarkupPlaceholderTag(true);
courseGradeType.add(this.minimumOptions);
// preview model, uses settings to determine out what to display
final Model<String> previewModel = new Model<String>() {
private static final long serialVersionUID = 1L;
@Override
public String getObject() {
final List<String> parts = new ArrayList<>();
final GradebookInformation settings = SettingsGradeReleasePanel.this.model.getObject().getGradebookInformation();
if (settings.isCourseLetterGradeDisplayed()) {
parts.add(getString("settingspage.displaycoursegrade.preview-letter"));
}
if (settings.isCourseAverageDisplayed()) {
if (parts.isEmpty()) {
parts.add(getString("settingspage.displaycoursegrade.preview-percentage-first"));
} else {
parts.add(getString("settingspage.displaycoursegrade.preview-percentage-second"));
}
}
if (settings.isCoursePointsDisplayed()) {
if (parts.isEmpty()) {
parts.add(getString("settingspage.displaycoursegrade.preview-points-first"));
} else {
parts.add(getString("settingspage.displaycoursegrade.preview-points-second"));
}
}
if (parts.isEmpty()) {
parts.add(getString("settingspage.displaycoursegrade.preview-none"));
}
return StringUtils.join(parts, " ");
}
};
// course grade type container
final WebMarkupContainer courseGradePreview = new WebMarkupContainer("courseGradePreview") {
private static final long serialVersionUID = 1L;
@Override
public boolean isVisible() {
return displayCourseGrade.getModelObject();
}
};
courseGradePreview.setOutputMarkupPlaceholderTag(true);
settingsGradeReleasePanel.add(courseGradePreview);
// preview
this.preview = new Label("preview", previewModel);
this.preview.setOutputMarkupId(true);
courseGradePreview.add(this.preview);
// behaviour for when the 'display course grade' checkbox is changed
displayCourseGrade.add(new AjaxFormComponentUpdatingBehavior("onchange") {
private static final long serialVersionUID = 1L;
@Override
protected void onUpdate(final AjaxRequestTarget target) {
final boolean checked = displayCourseGrade.getModelObject();
courseGradeType.setVisible(checked);
courseGradePreview.setVisible(checked);
target.add(courseGradeType);
target.add(courseGradePreview);
}
});
// if weighted category, disable points
final GbCategoryType type = GbCategoryType.valueOf(this.model.getObject().getGradebookInformation().getCategoryType());
if (type == GbCategoryType.WEIGHTED_CATEGORY) {
this.points.setEnabled(false);
}
}
public boolean isExpanded() {
return this.expanded;
}
// to enable inter panel comms
AjaxCheckBox getPointsCheckBox() {
return this.points;
}
}
|
BJackal/biodynamo_singularity | src/core/environment/kd_tree_environment.cc | // -----------------------------------------------------------------------------
//
// Copyright (C) 2021 CERN & University of Surrey for the benefit of the
// BioDynaMo collaboration. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// See the LICENSE file distributed with this work for details.
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership.
//
// -----------------------------------------------------------------------------
#include <algorithm>
#include "core/environment/kd_tree_environment.h"
#include <nanoflann.hpp>
namespace bdm {
using nanoflann::KDTreeSingleIndexAdaptor;
using nanoflann::KDTreeSingleIndexAdaptorParams;
using nanoflann::L2_Simple_Adaptor;
typedef KDTreeSingleIndexAdaptor<L2_Simple_Adaptor<double, NanoFlannAdapter>,
NanoFlannAdapter, 3, uint64_t>
bdm_kd_tree_t;
struct KDTreeEnvironment::NanoflannImpl {
bdm_kd_tree_t* index_ = nullptr;
};
KDTreeEnvironment::KDTreeEnvironment() {
auto* param = Simulation::GetActive()->GetParam();
nf_adapter_ = new NanoFlannAdapter();
impl_ = std::unique_ptr<KDTreeEnvironment::NanoflannImpl>(
new KDTreeEnvironment::NanoflannImpl());
impl_->index_ = new bdm_kd_tree_t(
3, *nf_adapter_, KDTreeSingleIndexAdaptorParams(param->nanoflann_depth));
}
KDTreeEnvironment::~KDTreeEnvironment() {
delete impl_->index_;
delete nf_adapter_;
}
void KDTreeEnvironment::UpdateImplementation() {
nf_adapter_->rm_ = Simulation::GetActive()->GetResourceManager();
// Update the flattened indices map
nf_adapter_->flat_idx_map_.Update();
if (nf_adapter_->rm_->GetNumAgents() != 0) {
Clear();
auto inf = Math::kInfinity;
std::array<double, 6> tmp_dim = {{inf, -inf, inf, -inf, inf, -inf}};
CalcSimDimensionsAndLargestAgent(&tmp_dim);
RoundOffGridDimensions(tmp_dim);
CheckGridGrowth();
impl_->index_->buildIndex();
} else {
// There are no sim objects in this simulation
auto* param = Simulation::GetActive()->GetParam();
bool uninitialized = impl_->index_->m_size == 0;
if (uninitialized && param->bound_space) {
// Simulation has never had any simulation objects
// Initialize grid dimensions with `Param::min_bound_` and
// `Param::max_bound_`
// This is required for the DiffusionGrid
int min = param->min_bound;
int max = param->max_bound;
grid_dimensions_ = {min, max, min, max, min, max};
threshold_dimensions_ = {min, max};
has_grown_ = true;
} else if (!uninitialized) {
// all simulation objects have been removed in the last iteration
// grid state remains the same, but we have to set has_grown_ to false
// otherwise the DiffusionGrid will attempt to resize
has_grown_ = false;
} else {
Log::Fatal(
"KDtreeEnvironment",
"You tried to initialize an empty simulation without bound space. "
"Therefore we cannot determine the size of the simulation space. "
"Please add simulation objects, or set Param::bound_space_, "
"Param::min_bound_, and Param::max_bound_.");
}
}
}
void KDTreeEnvironment::ForEachNeighbor(Functor<void, Agent*, double>& lambda,
const Agent& query,
double squared_radius) {
ForEachNeighbor(lambda, query.GetPosition(), squared_radius, &query);
}
void KDTreeEnvironment::ForEachNeighbor(Functor<void, Agent*, double>& lambda,
const Double3& query_position,
double squared_radius,
const Agent* query_agent) {
std::vector<std::pair<uint64_t, double>> neighbors;
nanoflann::SearchParams params;
params.sorted = false;
// calculate neighbors
impl_->index_->radiusSearch(&query_position[0], squared_radius, neighbors,
params);
auto* rm = Simulation::GetActive()->GetResourceManager();
for (auto& n : neighbors) {
Agent* nb_so =
rm->GetAgent(nf_adapter_->flat_idx_map_.GetAgentHandle(n.first));
if (nb_so != query_agent) {
lambda(nb_so, n.second);
}
}
}
void KDTreeEnvironment::ForEachNeighbor(Functor<void, Agent*>& lambda,
const Agent& query, void* criteria) {
Log::Fatal("KDTreeEnvironment::ForEachNeighbor",
"You tried to call a specific ForEachNeighbor in an "
"environment that does not yet support it.");
}
std::array<int32_t, 6> KDTreeEnvironment::GetDimensions() const {
return grid_dimensions_;
}
std::array<int32_t, 2> KDTreeEnvironment::GetDimensionThresholds() const {
return threshold_dimensions_;
}
LoadBalanceInfo* KDTreeEnvironment::GetLoadBalanceInfo() {
Log::Fatal("KDTreeEnvironment::GetLoadBalanceInfo",
"You tried to call GetLoadBalanceInfo in an environment that does "
"not support it.");
return nullptr;
}
Environment::NeighborMutexBuilder*
KDTreeEnvironment::GetNeighborMutexBuilder() {
return nullptr;
};
void KDTreeEnvironment::Clear() {
int32_t inf = std::numeric_limits<int32_t>::max();
grid_dimensions_ = {inf, -inf, inf, -inf, inf, -inf};
threshold_dimensions_ = {inf, -inf};
}
void KDTreeEnvironment::RoundOffGridDimensions(
const std::array<double, 6>& grid_dimensions) {
grid_dimensions_[0] = floor(grid_dimensions[0]);
grid_dimensions_[2] = floor(grid_dimensions[2]);
grid_dimensions_[4] = floor(grid_dimensions[4]);
grid_dimensions_[1] = ceil(grid_dimensions[1]);
grid_dimensions_[3] = ceil(grid_dimensions[3]);
grid_dimensions_[5] = ceil(grid_dimensions[5]);
}
void KDTreeEnvironment::CheckGridGrowth() {
// Determine if the grid dimensions have changed (changed in the sense that
// the grid has grown outwards)
auto min_gd =
*std::min_element(grid_dimensions_.begin(), grid_dimensions_.end());
auto max_gd =
*std::max_element(grid_dimensions_.begin(), grid_dimensions_.end());
if (min_gd < threshold_dimensions_[0]) {
threshold_dimensions_[0] = min_gd;
has_grown_ = true;
}
if (max_gd > threshold_dimensions_[1]) {
threshold_dimensions_[1] = max_gd;
has_grown_ = true;
}
}
} // namespace bdm
|
abhisheks008/Design-and-Analysis-Algorithm-Lab-4th-Semester | OOPs using JAVA/Day 10/Assignment 3/a3q12.java | // Write a Java program to print transpose of matrix.
// Author : <NAME>
public class a3q12{
public static void main(String args[]){
int original[][]={{1,3,4},{2,4,3},{3,4,5}};
int transpose[][]=new int[3][3];
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
transpose[i][j]=original[j][i];
}
}
System.out.println("Printing Matrix without transpose:");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(original[i][j]+" ");
}
System.out.println();
}
System.out.println("Printing Matrix After Transpose:");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(transpose[i][j]+" ");
}
System.out.println();
}
}
}
/*
Output :
Printing Matrix without transpose:
1 3 4
2 4 3
3 4 5
Printing Matrix After Transpose:
1 2 3
3 4 4
4 3 5
*/
|
trae-horton/secret-bridge | models/monitors/monitor.py | <reponame>trae-horton/secret-bridge
from abc import ABC, abstractmethod
class MonitorModel(ABC):
@abstractmethod
def poll(self):
"""Polls the appropriate Github Events API for new events associated
with this model.
"""
pass |
qatix/JavaBase | src/main/java/com/qatix/base/jol/EmptyClassArr.java | package com.qatix.base.jol;
import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.vm.VM;
public class EmptyClassArr {
public static void main(String[] args) throws Exception {
System.out.println(VM.current().details());
A[] as = new A[2];
System.out.println(ClassLayout.parseInstance(new A[2]).toPrintable());
}
public static class A {
// no fields
}
}
/*
[Lcom.qatix.base.jol.EmptyClassArr$A; object internals:
OFFSET SIZE TYPE DESCRIPTION VALUE
0 4 (object header) 01 00 00 00 (00000001 00000000 00000000 00000000) (1)
4 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
8 4 (object header) 73 f0 00 f8 (01110011 11110000 00000000 11111000) (-134156173)
12 4 (object header) 02 00 00 00 (00000010 00000000 00000000 00000000) (2)
解释:上面是数组size
16 8 com.qatix.base.jol.EmptyClassArr$A EmptyClassArr$A;.<elements> N/A
解释: 上面是数组元素
Instance size: 24 bytes
Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
*/
|
BBN-E/text-open | src/python/serif/util/dump_eer_only_custom.py | import os,sys,enum, multiprocessing
current_script_path = __file__
project_root = os.path.realpath(os.path.join(current_script_path, os.path.pardir, os.path.pardir, os.path.pardir))
sys.path.append(project_root)
import serifxml3
def get_event_anchor(serif_em:serifxml3.EventMention,serif_sentence_tokens:serifxml3.TokenSequence):
if serif_em.semantic_phrase_start is not None:
serif_em_semantic_phrase_text = " ".join(i.text for i in serif_sentence_tokens[int(serif_em.semantic_phrase_start):int(serif_em.semantic_phrase_end)+1])
return serif_em_semantic_phrase_text
elif len(serif_em.anchors) > 0:
return " ".join(i.anchor_node.text for i in serif_em.anchors)
else:
return serif_em.anchor_node.text
class SerifEventMentionTypingField(enum.Enum):
event_type = "event_type"
event_types = "event_types"
factor_types = "factor_types"
def get_event_type(serif_em:serifxml3.EventMention,typing_field:SerifEventMentionTypingField):
if typing_field == SerifEventMentionTypingField.event_type:
return [[serif_em.event_type,serif_em.score]]
ret = list()
if typing_field == SerifEventMentionTypingField.event_types:
for event_type in serif_em.event_types:
ret.append([event_type.event_type,event_type.score])
elif typing_field == SerifEventMentionTypingField.factor_types:
for event_type in serif_em.factor_types:
ret.append([event_type.event_type,event_type.score])
else:
raise NotImplementedError
return ret
def get_event_arg(serif_em:serifxml3.EventMention):
ret = list()
for argument in serif_em.arguments:
if isinstance(argument.mention,serifxml3.Mention):
ret.append("event_arg: {}: {}".format(argument.role,argument.mention.text))
elif isinstance(argument.value_mention,serifxml3.ValueMention):
ret.append("event_arg: {}: {}".format(argument.role,argument.value_mention.text))
else:
raise NotImplementedError
return ret
def assembley_event_frame(serif_em:serifxml3.EventMention):
sentence = serif_em.owner_with_type(serifxml3.Sentence)
sentence_theory = sentence.sentence_theory
# sentence_text = " ".join(i.text for i in sentence_theory.token_sequence).replace("\n", " ").replace("\t", " ")
event_anchor = get_event_anchor(serif_em, sentence_theory.token_sequence).replace("\n", " ").replace("\t", " ")
event_type_groundings = []
event_types_groundings = []
factor_types_groundings = []
event_type_groundings.append("event_type: {} , score: {}".format(serif_em.event_type, serif_em.score))
for event_type in serif_em.event_types:
event_types_groundings.append("event_types: {} , score: {}".format(event_type.event_type, event_type.score))
for event_type in serif_em.factor_types:
factor_types_groundings.append("factor_types: {} , score: {}".format(event_type.event_type, event_type.score))
event_args = get_event_arg(serif_em)
pattern_id = "pattern_id: {}".format(serif_em.pattern_id)
# buf = "[EM]\nAnchor: {}\n{}\n{}\n{}\n{}\n{}\n[EM END]".format(event_anchor,pattern_id,"\n".join(event_type_groundings),"\n".join(event_types_groundings),"\n".join(factor_types_groundings),"\n".join(event_args))
buf = "[EM START] Anchor: {}[EM END]".format(event_anchor)
return buf
def single_document_hanlder(serif_path):
eer_list = list()
serif_doc = serifxml3.Document(serif_path)
event_mention_in_eer = set()
eer_frame = list()
standalone_event_frame = list()
for serif_eerm in serif_doc.event_event_relation_mention_set or []:
serif_em_arg1 = None
serif_em_arg2 = None
relation_type = serif_eerm.relation_type
confidence = serif_eerm.confidence
for arg in serif_eerm.event_mention_relation_arguments:
if arg.role == "arg1":
serif_em_arg1 = arg.event_mention
if arg.role == "arg2":
serif_em_arg2 = arg.event_mention
if serif_em_arg1 is not None and serif_em_arg2 is not None:
event_mention_in_eer.add(serif_em_arg1)
event_mention_in_eer.add(serif_em_arg2)
sentence = serif_em_arg1.owner_with_type(serifxml3.Sentence)
sentence_theory = sentence.sentence_theory
sentence_text = " ".join(i.text for i in sentence_theory.token_sequence).replace("\n", " ").replace("\t", " ")
left_event_buf = assembley_event_frame(serif_em_arg1)
right_event_buf = assembley_event_frame(serif_em_arg2)
buf = "[EER] docid:{} sentid:{} sent:{} {} eer_type:{}\tscore:{} {} [EER END]".format(serif_doc.docid,sentence.sent_no,sentence_text,left_event_buf,relation_type,confidence,right_event_buf)
eer_frame.append((confidence, buf))
for sent_idx,sentence in enumerate(serif_doc.sentences):
sentence_theory = sentence.sentence_theory
sentence_text = " ".join(i.text for i in sentence_theory.token_sequence).replace("\n", " ").replace("\t", " ")
for event_mention in sentence_theory.event_mention_set:
if event_mention not in event_mention_in_eer:
event_buf = assembley_event_frame(event_mention)
buf = "[SEVENT]\ndocid:{} sentid:{}\nsent:{}\n{}\n[SEVENT END]".format(serif_doc.docid,sentence.sent_no,sentence_text,event_buf)
standalone_event_frame.append(buf)
eer_list.extend(eer_frame)
return eer_list
def main(serif_list):
manager = multiprocessing.Manager()
lock = manager.Lock()
global_list = list()
with manager.Pool(multiprocessing.cpu_count()) as pool:
workers = list()
with open(serif_list) as fp:
for i in fp:
i = i.strip()
workers.append(pool.apply_async(single_document_hanlder,args=(i,)))
for idx,i in enumerate(workers):
i.wait()
buf = i.get()
global_list.extend(buf)
# print("{}".format(buf))
global_list.sort(reverse=True)
for i, eer in enumerate(global_list):
print(i, eer)
# print('\n'.join(global_list))
if __name__ == "__main__":
import argparse
parser= argparse.ArgumentParser()
parser.add_argument("--serif_list",required=True)
args = parser.parse_args()
main(args.serif_list)
|
Abhiroopks/MuJava-Project | src/openjava/ptree/VariableInitializer.java | //
// Decompiled by Procyon v0.5.36
//
package openjava.ptree;
public interface VariableInitializer extends ParseTree
{
}
|
Dqu1J/marbles | src/main/java/net/dodogang/marbles/block/vanilla/PublicTorchBlock.java | <reponame>Dqu1J/marbles
package net.dodogang.marbles.block.vanilla;
import net.minecraft.block.TorchBlock;
import net.minecraft.particle.ParticleEffect;
public class PublicTorchBlock extends TorchBlock {
public PublicTorchBlock(Settings settings, ParticleEffect particle) {
super(settings, particle);
}
}
|
jakkrits/ChewEste | mutations/CreateWebMutation.js | <filename>mutations/CreateWebMutation.js
// @flow
import { graphql, commitMutation } from 'react-relay';
import type { Commit } from '../types';
import type {
CreateWebMutationVariables,
CreateWebMutationResponse,
} from './__generated__/CreateWebMutation.graphql';
import { ConnectionHandler } from 'relay-runtime';
import { queryFilters } from '../pages/index';
const mutation = graphql`
mutation CreateWebMutation($input: CreateWebInput!) {
createWeb(input: $input) {
# Request payload data needed for store update.
edge {
node {
...WebListItem_web
}
}
}
}
`;
const sharedUpdater = (store, edge, userId) => {
const viewerProxy = store.get('viewer-fixed');
const connection = ConnectionHandler.getConnection(
viewerProxy,
'WebList_allWebs',
{
...queryFilters(userId),
orderBy: 'createdAt_ASC',
},
);
// https://github.com/facebook/relay/issues/1808#issuecomment-304519883
if (!connection) {
// eslint-disable-next-line no-console
console.warn('Undefined connection. Check getConnection arguments.');
}
ConnectionHandler.insertEdgeAfter(connection, edge);
};
type CommitWithArgs = (
userId: string,
) => Commit<CreateWebMutationVariables, CreateWebMutationResponse>;
const commit: CommitWithArgs = userId => (
environment,
variables,
onCompleted,
onError,
) =>
commitMutation(environment, {
mutation,
variables,
onCompleted,
onError,
updater: store => {
const payload = store.getRootField('createWeb');
const edge = payload.getLinkedRecord('edge');
sharedUpdater(store, edge, userId);
},
});
export default { commit };
|
tsegall/mongo-jdbc-driver | src/main/java/com/dbschema/mongo/nashorn/MemberFunction.java | package com.dbschema.mongo.nashorn;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.*;
/**
* @author <NAME>
**/
public class MemberFunction {
private final String name;
private final Function<Object[], Optional<Object>> function;
public MemberFunction(String name, Function<Object[], Optional<Object>> function) {
this.name = name;
this.function = function;
}
public Optional<Object> tryRun(Object... args) {
return function.apply(args);
}
public String getName() {
return name;
}
public static MemberFunction voidFunc(String name, Runnable function) {
return new MemberFunction(name, args -> {
if (args.length == 0) {
function.run();
return Optional.of(Undefined.INSTANCE);
}
return Optional.empty();
});
}
public static <R> MemberFunction func(String name, Supplier<R> function) {
return new MemberFunction(name, args -> args.length == 0 ? Optional.of(function.get()) : Optional.empty());
}
public static MemberFunction ignoreParams(String name, Runnable function) {
return new MemberFunction(name, args -> {
function.run();
return Optional.of(Undefined.INSTANCE);
});
}
public static MemberFunction notImplemented(String name, ObjectKind objectKind) {
return ignoreParams(name, () -> {
String msg;
switch (objectKind) {
case DATABASE:
msg = "Method db." + name + " is not implemented";
break;
case COLLECTION:
msg = "Method db.collection." + name + " is not implemented";
break;
case CURSOR:
msg = "Method cursor." + name + " is not implemented";
break;
default:
msg = "Method " + name + " is not implemented";
}
throw new UnsupportedOperationException(msg);
});
}
public static <T, R> MemberFunction func(String name, Function<T, R> function, Class<T> clazz) {
return new MemberFunction(name, args -> {
if (args.length != 1) return Optional.empty();
Optional<T> o1 = isInstance(clazz, args[0]);
return o1.map(function);
});
}
public static <T, R> MemberFunction vararg(String name, Function<List<T>, R> function, Class<T> clazz) {
return new MemberFunction(name, args -> {
List<T> objects = new ArrayList<>();
for (Object arg : args) {
Optional<T> o = isInstance(clazz, arg);
if (!o.isPresent()) return Optional.empty();
objects.add(o.get());
}
return Optional.of(function.apply(objects));
});
}
public static <T1, T2, R> MemberFunction func(String name, BiFunction<T1, T2, R> function, Class<T1> clazzA, Class<T2> clazzB) {
return new MemberFunction(name, args -> {
if (args.length != 2) return Optional.empty();
Optional<T1> o1 = isInstance(clazzA, args[0]);
Optional<T2> o2 = isInstance(clazzB, args[1]);
return !o1.isPresent() || !o2.isPresent() ? Optional.empty() : Optional.of(function.apply(o1.get(), o2.get()));
});
}
public static <T1, T2, T3, R> MemberFunction func(String name, TriFunction<T1, T2, T3, R> function, Class<T1> clazzA, Class<T2> clazzB, Class<T3> clazzC) {
return new MemberFunction(name, args -> {
if (args.length != 3) return Optional.empty();
Optional<T1> o1 = isInstance(clazzA, args[0]);
Optional<T2> o2 = isInstance(clazzB, args[1]);
Optional<T3> o3 = isInstance(clazzC, args[2]);
return !o1.isPresent() || !o2.isPresent() || !o3.isPresent() ? Optional.empty() : Optional.of(function.apply(o1.get(), o2.get(), o3.get()));
});
}
public static <T1, T2, T3, T4, R> MemberFunction func(String name, FourFunction<T1, T2, T3, T4, R> function, Class<T1> clazzA, Class<T2> clazzB, Class<T3> clazzC, Class<T4> clazzD) {
return new MemberFunction(name, args -> {
if (args.length != 4) return Optional.empty();
Optional<T1> o1 = isInstance(clazzA, args[0]);
Optional<T2> o2 = isInstance(clazzB, args[1]);
Optional<T3> o3 = isInstance(clazzC, args[2]);
Optional<T4> o4 = isInstance(clazzD, args[3]);
return !o1.isPresent() || !o2.isPresent() || !o3.isPresent() || !o4.isPresent() ?
Optional.empty() :
Optional.of(function.apply(o1.get(), o2.get(), o3.get(), o4.get()));
});
}
public static <T> MemberFunction voidFunc(String name, Consumer<T> function, Class<T> clazz) {
return new MemberFunction(name, args -> {
if (args.length != 1) return Optional.empty();
Optional<T> o1 = isInstance(clazz, args[0]);
if (!o1.isPresent()) return Optional.empty();
function.accept(o1.get());
return Optional.of(Undefined.INSTANCE);
});
}
public static <T1, T2> MemberFunction voidFunc(String name, BiConsumer<T1, T2> function, Class<T1> clazzA, Class<T2> clazzB) {
return new MemberFunction(name, args -> {
if (args.length != 2) return Optional.empty();
Optional<T1> o1 = isInstance(clazzA, args[0]);
Optional<T2> o2 = isInstance(clazzB, args[1]);
if (!o1.isPresent() || !o2.isPresent()) return Optional.empty();
function.accept(o1.get(), o2.get());
return Optional.of(Undefined.INSTANCE);
});
}
public static <T1, T2, T3> MemberFunction voidFunc(String name, TriConsumer<T1, T2, T3> function, Class<T1> clazzA, Class<T2> clazzB, Class<T3> clazzC) {
return new MemberFunction(name, args -> {
if (args.length != 3) return Optional.empty();
Optional<T1> o1 = isInstance(clazzA, args[0]);
Optional<T2> o2 = isInstance(clazzB, args[1]);
Optional<T3> o3 = isInstance(clazzC, args[2]);
if (!o1.isPresent() || !o2.isPresent() || !o3.isPresent()) return Optional.empty();
function.accept(o1.get(), o2.get(), o3.get());
return Optional.of(Undefined.INSTANCE);
});
}
public static <T1, T2, T3, T4> MemberFunction voidFunc(String name, FourConsumer<T1, T2, T3, T4> function, Class<T1> clazzA, Class<T2> clazzB, Class<T3> clazzC, Class<T4> clazzD) {
return new MemberFunction(name, args -> {
if (args.length != 4) return Optional.empty();
Optional<T1> o1 = isInstance(clazzA, args[0]);
Optional<T2> o2 = isInstance(clazzB, args[1]);
Optional<T3> o3 = isInstance(clazzC, args[2]);
Optional<T4> o4 = isInstance(clazzD, args[3]);
if (!o1.isPresent() || !o2.isPresent() || !o3.isPresent() || !o4.isPresent()) return Optional.empty();
function.accept(o1.get(), o2.get(), o3.get(), o4.get());
return Optional.of(Undefined.INSTANCE);
});
}
private static <T> Optional<T> isInstance(@NotNull Class<T> clazz, @Nullable Object value) {
if (clazz.isInstance(value)) //noinspection unchecked
return Optional.of((T) value);
if (clazz == List.class && value instanceof ScriptObjectMirror && ((ScriptObjectMirror) value).isArray()) {
//noinspection unchecked
return Optional.of((T) new JSArray((ScriptObjectMirror) value));
}
if (clazz == JSFunction.class && value instanceof ScriptObjectMirror && ((ScriptObjectMirror) value).isFunction())
return Optional.of((T) new JSFunction((ScriptObjectMirror) value));
return Optional.empty();
}
public enum ObjectKind {
DATABASE,
COLLECTION,
CURSOR
}
}
|
mskoenz/arduino_crash_course | libraries/CustomHeaderLibs/ustd/filter/lowpass.hpp | // Author: <NAME> <<EMAIL>>
// Date: 23.07.2013 05:09:59 EDT
// File: lowpass.hpp
/* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://www.wtfpl.net/ or COPYING for more details. */
#ifndef __LOWPASS_HEADER
#define __LOWPASS_HEADER
#include "realization.hpp"
#include "../../util/mean_trait.hpp"
namespace ustd {
template<typename T, unsigned N, typename _base = identity_filter<T> >
class lowpass_filter: public _base {
typedef typename util::mean_trait<T>::type mean_type;
typedef _base base;
public:
//------------------- ctors -------------------
lowpass_filter(): val_() {
}
lowpass_filter(lowpass_filter const & arg): val_(arg.val_) {
}
lowpass_filter(T const & arg): val_(arg) {
}
//------------------- ops -------------------
lowpass_filter & operator=(T const & in) {
base::operator=(in);
val_ = base::value();
return (*this);
}
lowpass_filter & operator<<(T const & in) {
base::operator<<(in);
val_ = ((N - 1) * val_ + base::value()) / N;
return (*this);
}
//------------------- converter -------------------
T value() const {
return lowpass_impl<mean_type, T>();
}
operator T() const {
return value();
}
private:
//------------------- impl -------------------
template<typename M, typename U>
typename enable_if<is_same<M, U>::value, M>::type lowpass_impl() const {
return val_;
}
template<typename M, typename U>
typename enable_if<not is_same<M, U>::value, M>::type lowpass_impl() const {
return val_ + 0.5; //round for integer types
}
private:
mean_type val_;
};
//------------------- spez for N == 1 -------------------
EMPTY_FILTER(lowpass, 1)
//------------------- realization for filter -------------------
template<typename T, typename _base, unsigned N>
struct realization<T, tag::lowpass<N>, _base> {
typedef lowpass_filter<T, N, _base> type;
};
}//end namespace ustd
#endif //__LOWPASS_HEADER
|
MouseLightProject/Fetch | ui/uiunits.h | <filename>ui/uiunits.h
#pragma once
#include "units.h"
#include <QtWidgets>
#include <Eigen\Core>
using namespace Eigen;
namespace fetch {
namespace units {
template<Length dst, Length src>
inline Vector3f cvt(const Vector3f& r)
{ return cvt<dst,src>(1.0)*r;
}
template<Length dst, Length src>
inline QPointF cvt(const QPointF& r)
{ return QPointF(cvt<dst,src>(r.x()),cvt<dst,src>(r.y()));
}
template<Length dst, Length src>
inline QRectF cvt(const QRectF& r)
{ return QRectF(cvt<dst,src>(r.topLeft()),cvt<dst,src>(r.bottomRight()));
}
}//namespace fetch {
}//namespace units {
|
Jorch72/OpenPeripheral | src/main/java/openperipheral/api/ApiAccess.java | package openperipheral.api;
/**
* This class is used to access instancef of API interfaces (marked with {@link IApiInterface}).
*
* For alternative method, see {@link ApiHolder}.
*/
public class ApiAccess {
public static final String API_VERSION = "$OP-API-VERSION$";
public interface ApiProvider {
public <T extends IApiInterface> T getApi(Class<T> cls);
public <T extends IApiInterface> boolean isApiPresent(Class<T> cls);
}
private ApiAccess() {}
private static ApiProvider provider;
// OpenPeripheralCore will use this method to provide actual implementation
public static void init(ApiProvider provider) {
if (ApiAccess.provider != null) throw new IllegalStateException("API already initialized");
ApiAccess.provider = provider;
}
public static <T extends IApiInterface> T getApi(Class<T> cls) {
if (provider == null) throw new IllegalStateException("API not initialized");
return provider.getApi(cls);
}
public static <T extends IApiInterface> boolean isApiPresent(Class<T> cls) {
if (provider == null) throw new IllegalStateException("API not initialized");
return provider.isApiPresent(cls);
}
}
|
Siddhant-K-code/darwin | third_party/gtest/gtest.h | <reponame>Siddhant-K-code/darwin<gh_stars>10-100
#pragma once
#include "src/googletest/include/gtest/gtest.h"
|
edusasse/SaGUI | sagui-parent/sagui-render-common/src/main/java/com/sagui/ext/common/render/util/ListDiference.java | package com.sagui.ext.common.render.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class ListDiference<E> {
private final Comparator<E> comparator;
private final List<E> newList;
private final List<E> oldList;
private final List<DifferenceOperation<E>> operations;
private ListDiference(List<E> oldList, List<E> newList, Comparator<E> comparator) {
this.oldList = Collections.unmodifiableList(oldList);
this.newList = Collections.unmodifiableList(newList);
this.comparator = comparator;
this.operations = new ArrayList<DifferenceOperation<E>>();
}
public static <T> ListDiference<T> getDiference(List<T> oldList, List<T> newList, Comparator<T> comparator) {
ListDiference<T> ld = new ListDiference<T>(oldList, newList, comparator);
ld.checkDiference();
return ld;
}
private void checkDiference() {
Set<E> tempSet = new TreeSet<E>(comparator);
tempSet.addAll(newList);
for (E elem : oldList) {
if (!tempSet.contains(elem)) {
operations.add(DifferenceOperation.getDeleteCommand(elem));
}
}
tempSet.clear();
tempSet.addAll(oldList);
int index = 0;
for (E elem : newList) {
if (!tempSet.contains(elem)) {
operations.add(DifferenceOperation.getInsertCommand(elem, index));
}
index++;
}
}
}
|
markllama/osp-survey | src/ospsurvey/probes/sm.py | """
Classes and Functions to query the software update status of a Red Hat
server.
"""
import logging
import os
import re
import subprocess
import tempfile
#
# Subscription Manager
#
class SubscriptionManager():
"""
Query and report status of Subscription Manager
"""
def __init__(self):
self._status = None
self._config = None
self._purpose = None
self._consumed = None
self._repos = None
@staticmethod
def subscribed():
"""
Check if the host is registered using Subscription Manager
"""
try:
subprocess.check_call(
"sudo subscription-manager status".split(),
stdout=open(os.devnull),
stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
# called but unsuccessful
return False
except OSError as e:
# command not found
return False
return True
def status(self, refresh=False):
"""
Gather subscription manager and yum status
"""
if self._status == None or refresh == True:
# define the value search patterns
status_re = re.compile("Overall Status: (.*)")
purpose_re = re.compile("System Purpose Status: (.*)")
# get the actual status
try:
sm_status_string = \
subprocess.check_output("sudo subscription-manager status".split())
# extract the status string
status_match = status_re.search(sm_status_string, re.MULTILINE)
self._status = status_match.groups()[0]
# extract the purpose string
purpose_match = purpose_re.search(sm_status_string, re.MULTILINE)
self._purpose = purpose_match.groups()[0]
except subprocess.CalledProcessError as e:
self._status = "Unsubscribed"
self._purpose = "Unknown"
return {'status': self._status, 'purpose': self._purpose}
def config(self, refresh=False):
"""
Read the subscription-manager configuration and return it as a dict
"""
if self._config == None or refresh == True:
config_string = subprocess.check_output("sudo subscription-manager config".split())
# remove lines afer the one containing "default value in use"
default_line = '[] - Default value in use'
config_lines = config_string.split('\n')
# remove the default line and everything after
config_lines = config_lines[:config_lines.index(default_line)]
# remove leading white space because ConfigParser doesn't like it.
config_lines = [line.lstrip() for line in config_lines]
config_string = "\n".join(config_lines)
config_string = re.sub(r'= \[\]', '= default', config_string)
config_string = re.sub(r'= \[([^]]+)\]', r'= \1', config_string)
# Write and then read an anonymous temp file because ConfigParser can't
# read strings
tf = tempfile.TemporaryFile(mode='w+')
tf.write(unicode(config_string))
tf.seek(0)
sm_config = SmConfigParser()
sm_config.readfp(tf)
self._config = sm_config.as_dict()
return self._config
def repos(self, refresh=False):
"""
Get a list of repositories enabled in subscription manager
"""
if self._repos == None or refresh == True:
sm_repos_string = \
subprocess.check_output("sudo subscription-manager repos --list-enabled".split())
sm_repos_lines = sm_repos_string.split('\n')
repos = {}
# The first line of each subscription record will have this string
marker = "Repo ID"
# Get the index of each line with the marker in it
# Those are the beginning lines of subscription records
starts = [i for i, line in enumerate(sm_repos_lines) if line.startswith(marker + ':')]
# Collect all of the subscription records
for start in starts:
# Clip out just the lines for this record from the output
end = sm_repos_lines[start:].index("")
repo_lines = sm_repos_lines[start:start + end]
title, record = parse_sm_record(repo_lines)
repos[title] = record
self._repos = repos
return self._repos
def consumed(self, refresh=False):
"""
Report the consumed subscriptions
"""
if self._consumed == None or refresh == True:
# get the actual status
sm_consumed_string = \
subprocess.check_output("sudo subscription-manager list --consumed".split())
# read the header and get the title
sm_consumed_lines = sm_consumed_string.split('\n')
# 1st and 3rd lines should match "^\+-*\*$"
# Second line is title, with white space stripped
# lines are key/value, with multiple values signalled by white space at the
# beginning of the line.
# blank lines signal the end of a structure
kv_re = re.compile("^([^:]+):\s+(.*)$")
# Initialize the consumed subscriptions set
subscriptions = {}
# The first line of each subscription record will have this string
marker = "Subscription Name"
# Get the index of each line with the marker in it
# Those are the beginning lines of subscription records
starts = [i for i, line in enumerate(sm_consumed_lines) if line.startswith(marker + ':')]
# Collect all of the subscription records
for start in starts:
# Clip out just the lines for this record from the output
end = sm_consumed_lines[start:].index("")
sub_lines = sm_consumed_lines[start:start + end]
title, record = parse_sm_record(sub_lines)
subscriptions[title] = record
self._consumed = subscriptions
return self._consumed
# ----------------------------------------------------------------------------
# Module functions
# ----------------------------------------------------------------------------
# Extend the ConfigParser to create a dict
# from https://stackoverflow.com/questions/3220670/read-all-the-contents-in-ini-file-into-dictionary-with-python
import ConfigParser as configparser
class SmConfigParser(configparser.ConfigParser):
def as_dict(self):
d = dict(self._sections)
for k in d:
d[k] = dict(self._defaults, **d[k])
d[k].pop('__name__', None)
return d
def parse_sm_record(lines):
"""
Create a dict record from a fragment of a subscription-manager output
"""
# lines are key/value, with multiple values signalled by white space at the
# beginning of the line.
# blank lines signal the end of a structure
kv_re = re.compile('^(([^:]+):)?\s+(.*)$')
record = {}
# The subscription name will be the key for each subscription record
title = re.sub('^.*:\s+', '', lines[0]).strip()
for l in lines[1:]:
# check all lines for "((key):)? (value)"
#new_value = kv_re.match('^(([^:]+):)?\s+(.*)$', l)
new_value = kv_re.match(l)
if new_value:
a,k,v = new_value.groups()
# If a key is present, this is a new field of the record
if k:
record[k] = v
hold_k = k
# If not, the field is a list of values. Append to it
else:
if type(record[hold_k]) is list:
record[hold_k].append(v)
else:
record[hold_k] = [record[hold_k], v]
return title, record
# ----------------------------------------------------------------------------
# Legacy subscription: RHN
# ----------------------------------------------------------------------------
class RedHatNetwork():
"""
TBD
"""
def __init__(self):
"""
TBD
"""
self._config = None
@staticmethod
def subscribed():
"""
Check if the host is registered with RHN Classic or Sat5
"""
# This needs renaming to show intent
try:
subprocess.check_call(
"/usr/sbin/rhn_check",
stdout=open(os.devnull),
stderr=subprocess.STDOUT)
except:
# CalledSubprocessError returns non-0
# OSError - no such file
return False
return True
def config(self, refresh=False, up2date_file='/etc/sysconfig/rhn/up2date'):
"""
Read and return the RHN/Sat5 subscription configuration
"""
if self._config == None or refresh == True:
config_file = open(up2date_file)
lines = config_file.readlines()
config_file.close()
varlist = [l.strip('\n').split('=') for l in lines if '=' in l and not re.match('.*\[comment\].*', l)]
self._config = {v[0]:v[1] for v in varlist}
return self._config
|
msxiehui/eoLinker-API-Management-for-PHP | frontend_resource/src/app/service/service.module.js | <gh_stars>1-10
(function() {
'use strict';
/**
* @Author 广州银云信息科技有限公司 eolinker
* @function [服务模块定义js] [Service module definition js]
* @version 3.0.2
*/
angular.module('eolinker.service', [])
})();
|
teddywest32/intellij-community | java/java-tests/testData/psi/resolve/method/Remove4.java | <gh_stars>1-10
package ;
/**
* Created by IntelliJ IDEA.
* User: ik
* Date: 17.01.2003
* Time: 19:11:56
* To change this template use Options | File Templates.
*/
public class Remove4 {
}
|
drkane/find-that-charity | ftc/management/commands/import_rsl.py | import datetime
import io
from openpyxl import load_workbook
from ftc.management.commands._base_scraper import HTMLScraper
from ftc.models import Organisation, OrganisationLocation
class Command(HTMLScraper):
"""
Spider for scraping details of Registered Social Landlords in England
"""
name = "rsl"
allowed_domains = ["gov.uk", "githubusercontent.com"]
start_urls = [
"https://www.gov.uk/government/publications/current-registered-providers-of-social-housing",
]
org_id_prefix = "GB-SHPE"
id_field = "registration number"
source = {
"title": "Current registered providers of social housing",
"description": "Current registered providers of social housing and new registrations and deregistrations. Covers England",
"identifier": "rsl",
"license": "http://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/",
"license_name": "Open Government Licence v3.0",
"issued": "",
"modified": "",
"publisher": {
"name": "Regulator of Social Housing",
"website": "https://www.gov.uk/government/organisations/regulator-of-social-housing",
},
"distribution": [
{
"downloadURL": "",
"accessURL": "",
"title": "Current registered providers of social housing",
}
],
}
orgtypes = ["Registered Provider of Social Housing"]
def parse_file(self, response, source_url):
link = [link for link in response.html.links if link.endswith(".xlsx")][0]
self.set_download_url(link)
r = self.session.get(link)
r.raise_for_status()
wb = load_workbook(io.BytesIO(r.content), read_only=True)
sheets = [
sheetname
for sheetname in wb.sheetnames
if "listing" in sheetname.lower() or "find view" in sheetname.lower()
]
for sheetname in sheets:
ws = wb[sheetname]
# self.source["issued"] = wb.properties.modified.isoformat()[0:10]
headers = None
for k, row in enumerate(ws.rows):
if not headers:
headers = [c.value.lower() for c in row]
else:
record = dict(zip(headers, [c.value for c in row]))
self.parse_row(record)
def parse_row(self, record):
record = self.clean_fields(record)
if not record.get("organisation name") or not record.get("registration number"):
return
org_types = [
self.add_org_type("Registered Provider of Social Housing"),
]
if record.get("corporate form"):
if record["corporate form"] == "Company":
org_types.append(self.add_org_type("Registered Company"))
org_types.append(
self.add_org_type(
"{} {}".format(record["designation"], record["corporate form"])
)
)
elif record["corporate form"] == "CIO-Charitable Incorporated Organisation":
org_types.append(
self.add_org_type("Charitable Incorporated Organisation")
)
org_types.append(self.add_org_type("Registered Charity"))
elif record["corporate form"] == "Charitable Company":
org_types.append(self.add_org_type("Registered Company"))
org_types.append(self.add_org_type("Incorporated Charity"))
org_types.append(self.add_org_type("Registered Charity"))
elif record["corporate form"] == "Unincorporated Charity":
org_types.append(self.add_org_type("Registered Charity"))
else:
org_types.append(self.add_org_type(record["corporate form"]))
elif record.get("designation"):
org_types.append(self.add_org_type(record["designation"]))
org_ids = [self.get_org_id(record)]
if record.get("designation") == "Local Authority":
la_codes = LA_LOOKUP.get(record.get(self.id_field))
if la_codes:
org_ids.append("GB-LAE-{}".format(la_codes.get("register-code")))
self.add_location_record(
{
"org_id": self.get_org_id(record),
"name": la_codes.get("name"),
"geoCode": la_codes.get("GSS"),
"geoCodeType": OrganisationLocation.GeoCodeTypes.ONS_CODE,
"locationType": OrganisationLocation.LocationTypes.AREA_OF_OPERATION,
"spider": self.name,
"scrape": self.scrape,
"source": self.source,
}
)
self.add_org_record(
Organisation(
**{
"org_id": self.get_org_id(record),
"name": record.get("organisation name"),
"charityNumber": None,
"companyNumber": None,
"streetAddress": None,
"addressLocality": None,
"addressRegion": None,
"addressCountry": "England",
"postalCode": None,
"telephone": None,
"alternateName": [],
"email": None,
"description": None,
"organisationType": [o.slug for o in org_types],
"organisationTypePrimary": org_types[0],
"url": None,
# "location": locations,
"latestIncome": None,
"dateModified": datetime.datetime.now(),
"dateRegistered": record.get("registration date"),
"dateRemoved": None,
"active": True,
"parent": None,
"orgIDs": org_ids,
"scrape": self.scrape,
"source": self.source,
"spider": self.name,
"org_id_scheme": self.orgid_scheme,
}
)
)
LA_LOOKUP = {
"45UB": {"GSS": "E07000223", "register-code": "ADU", "name": "Adur"},
"45UC": {"GSS": "E07000224", "register-code": "ARU", "name": "Arun"},
"37UB": {"GSS": "E07000170", "register-code": "ASH", "name": "Ashfield"},
"29UB": {"GSS": "E07000105", "register-code": "ASF", "name": "Ashford"},
"42UB": {"GSS": "E07000200", "register-code": "BAB", "name": "Babergh"},
"00CC": {"GSS": "E08000016", "register-code": "BNS", "name": "Barnsley"},
"16UC": {"GSS": "E07000027", "register-code": "BAR", "name": "Barrow-in-Furness"},
"22UB": {"GSS": "E07000066", "register-code": "BAI", "name": "Basildon"},
"37UC": {"GSS": "E07000171", "register-code": "BAE", "name": "Bassetlaw"},
"00CN": {"GSS": "E08000025", "register-code": "BIR", "name": "Birmingham"},
"00EY": {"GSS": "E06000009", "register-code": "BPL", "name": "Blackpool"},
"17UC": {"GSS": "E07000033", "register-code": "BOS", "name": "Bolsover"},
"00BL": {"GSS": "E08000001", "register-code": "BOL", "name": "Bolton"},
"00HP": {"GSS": "E06000029", "register-code": "POL", "name": "Poole"},
"00HN": {"GSS": "E06000028", "register-code": "BMH", "name": "Bournemouth"},
"5069": {
"GSS": "E06000058",
"register-code": "BPC",
"name": "Bournemouth, Christchurch and Poole",
},
"00MA": {"GSS": "E06000036", "register-code": "BRC", "name": "<NAME>"},
"22UD": {"GSS": "E07000068", "register-code": "BRW", "name": "Brentwood"},
"00ML": {"GSS": "E06000043", "register-code": "BNH", "name": "<NAME>"},
"00HB": {"GSS": "E06000023", "register-code": "BST", "name": "Bristol, City of"},
"37UD": {"GSS": "E07000172", "register-code": "BRT", "name": "Broxtowe"},
"00BM": {"GSS": "E08000002", "register-code": "BUR", "name": "Bury"},
"12UB": {"GSS": "E07000008", "register-code": "CAB", "name": "Cambridge"},
"41UB": {"GSS": "E07000192", "register-code": "CAN", "name": "<NAME>"},
"29UC": {"GSS": "E07000106", "register-code": "CAT", "name": "Canterbury"},
"22UE": {"GSS": "E07000069", "register-code": "CAS", "name": "<NAME>"},
"00KC": {
"GSS": "E06000056",
"register-code": "CBF",
"name": "Central Bedfordshire",
},
"31UC": {"GSS": "E07000130", "register-code": "CHA", "name": "Charnwood"},
"23UB": {"GSS": "E07000078", "register-code": "CHT", "name": "Cheltenham"},
"38UB": {"GSS": "E07000177", "register-code": "CHR", "name": "Cherwell"},
"00EW": {
"GSS": "E06000050",
"register-code": "CHW",
"name": "Cheshire West and Chester",
},
"17UD": {"GSS": "E07000034", "register-code": "CHS", "name": "Chesterfield"},
"30UE": {"GSS": "E07000118", "register-code": "CHO", "name": "Chorley"},
"00CX": {"GSS": "E08000032", "register-code": "BRD", "name": "Bradford"},
"32UD": {"GSS": "E07000138", "register-code": "LIC", "name": "Lincoln"},
"00AA": {"GSS": "E09000001", "register-code": "LND", "name": "City of London"},
"00DB": {"GSS": "E08000036", "register-code": "WKF", "name": "Wakefield"},
"00BK": {"GSS": "E09000033", "register-code": "WSM", "name": "Westminster"},
"00FF": {"GSS": "E06000014", "register-code": "YOR", "name": "York"},
"22UG": {"GSS": "E07000071", "register-code": "COL", "name": "Colchester"},
"34UB": {"GSS": "E07000150", "register-code": "COR", "name": "Corby"},
"00HE": {"GSS": "E06000052", "register-code": "CON", "name": "Cornwall"},
"00HF": {"GSS": "E06000053", "register-code": "IOS", "name": "<NAME>"},
"36UB": {"GSS": "E07000163", "register-code": "CRA", "name": "Craven"},
"45UE": {"GSS": "E07000226", "register-code": "CRW", "name": "Crawley"},
"26UC": {"GSS": "E07000096", "register-code": "DAC", "name": "Dacorum"},
"00EH": {"GSS": "E06000005", "register-code": "DAL", "name": "Darlington"},
"29UD": {"GSS": "E07000107", "register-code": "DAR", "name": "Dartford"},
"5076": {"GSS": "E07000151", "register-code": "DAV", "name": "Daventry"},
"00FK": {"GSS": "E06000015", "register-code": "DER", "name": "Derby"},
"00CE": {"GSS": "E08000017", "register-code": "DNC", "name": "Doncaster"},
"29UE": {"GSS": "E07000108", "register-code": "DOV", "name": "Dover"},
"00CR": {"GSS": "E08000027", "register-code": "DUD", "name": "Dudley"},
"00EJ": {"GSS": "E06000047", "register-code": "DUR", "name": "<NAME>"},
"18UB": {"GSS": "E07000040", "register-code": "EDE", "name": "<NAME>"},
"5070": {"GSS": "E07000244", "register-code": "ESK", "name": "East Suffolk"},
"26UD": {"GSS": "E07000097", "register-code": "EHE", "name": "East Hertfordshire"},
"00FB": {
"GSS": "E06000011",
"register-code": "ERY",
"name": "East Riding of Yorkshire",
},
"21UC": {"GSS": "E07000061", "register-code": "EAS", "name": "Eastbourne"},
"22UH": {"GSS": "E07000072", "register-code": "EPP", "name": "Epping Forest"},
"18UC": {"GSS": "E07000041", "register-code": "EXE", "name": "Exeter"},
"24UE": {"GSS": "E07000087", "register-code": "FAR", "name": "Fareham"},
"42UC": {"GSS": "E07000201", "register-code": "FOR", "name": "Forest Heath"},
"00CH": {"GSS": "E08000037", "register-code": "GAT", "name": "Gateshead"},
"23UE": {"GSS": "E07000081", "register-code": "GLO", "name": "Gloucester"},
"24UF": {"GSS": "E07000088", "register-code": "GOS", "name": "Gosport"},
"29UG": {"GSS": "E07000109", "register-code": "GRA", "name": "Gravesham"},
"33UD": {"GSS": "E07000145", "register-code": "GRY", "name": "Great Yarmouth"},
"43UD": {"GSS": "E07000209", "register-code": "GRT", "name": "Guildford"},
"00AP": {"GSS": "E09000014", "register-code": "HRY", "name": "Haringey"},
"22UJ": {"GSS": "E07000073", "register-code": "HAR", "name": "Harlow"},
"36UD": {"GSS": "E07000165", "register-code": "HAG", "name": "Harrogate"},
"00EB": {"GSS": "E06000001", "register-code": "HPL", "name": "Hartlepool"},
"17UH": {"GSS": "E07000037", "register-code": "HIG", "name": "<NAME>"},
"31UE": {
"GSS": "E07000132",
"register-code": "HIN",
"name": "<NAME>",
},
"42UD": {"GSS": "E07000202", "register-code": "IPS", "name": "Ipswich"},
"34UE": {"GSS": "E07000153", "register-code": "KET", "name": "Kettering"},
"00FA": {
"GSS": "E06000010",
"register-code": "KHL",
"name": "<NAME>, City of",
},
"00CZ": {"GSS": "E08000034", "register-code": "KIR", "name": "Kirklees"},
"30UH": {"GSS": "E07000121", "register-code": "LAC", "name": "Lancaster"},
"00DA": {"GSS": "E08000035", "register-code": "LDS", "name": "Leeds"},
"00FN": {"GSS": "E06000016", "register-code": "LCE", "name": "Leicester"},
"21UF": {"GSS": "E07000063", "register-code": "LEE", "name": "Lewes"},
"00AB": {
"GSS": "E09000002",
"register-code": "BDG",
"name": "<NAME>",
},
"00AC": {"GSS": "E09000003", "register-code": "BNE", "name": "Barnet"},
"00AD": {"GSS": "E09000004", "register-code": "BEX", "name": "Bexley"},
"00AE": {"GSS": "E09000005", "register-code": "BEN", "name": "Brent"},
"00AG": {"GSS": "E09000007", "register-code": "CMD", "name": "Camden"},
"00AH": {"GSS": "E09000008", "register-code": "CRY", "name": "Croydon"},
"00AJ": {"GSS": "E09000009", "register-code": "EAL", "name": "Ealing"},
"00AK": {"GSS": "E09000010", "register-code": "ENF", "name": "Enfield"},
"00AL": {"GSS": "E09000011", "register-code": "GRE", "name": "Greenwich"},
"00AM": {"GSS": "E09000012", "register-code": "HCK", "name": "Hackney"},
"00AN": {
"GSS": "E09000013",
"register-code": "HMF",
"name": "<NAME>",
},
"00AQ": {"GSS": "E09000015", "register-code": "HRW", "name": "Harrow"},
"00AR": {"GSS": "E09000016", "register-code": "HAV", "name": "Havering"},
"00AS": {"GSS": "E09000017", "register-code": "HIL", "name": "Hillingdon"},
"00AT": {"GSS": "E09000018", "register-code": "HNS", "name": "Hounslow"},
"00AU": {"GSS": "E09000019", "register-code": "ISL", "name": "Islington"},
"00AY": {"GSS": "E09000022", "register-code": "LBH", "name": "Lambeth"},
"00AZ": {"GSS": "E09000023", "register-code": "LEW", "name": "Lewisham"},
"00BA": {"GSS": "E09000024", "register-code": "MRT", "name": "Merton"},
"00BB": {"GSS": "E09000025", "register-code": "NWM", "name": "Newham"},
"00BC": {"GSS": "E09000026", "register-code": "RDB", "name": "Redbridge"},
"00BF": {"GSS": "E09000029", "register-code": "STN", "name": "Sutton"},
"00BG": {"GSS": "E09000030", "register-code": "TWH", "name": "<NAME>"},
"00BH": {"GSS": "E09000031", "register-code": "WFT", "name": "<NAME>"},
"00BJ": {"GSS": "E09000032", "register-code": "WND", "name": "Wandsworth"},
"00KA": {"GSS": "E06000032", "register-code": "LUT", "name": "Luton"},
"5074": {"GSS": "E08000012", "register-code": "LIV", "name": "Liverpool"},
"29UH": {"GSS": "E07000110", "register-code": "MAI", "name": "Maidstone"},
"00BN": {"GSS": "E08000003", "register-code": "MAN", "name": "Manchester"},
"37UF": {"GSS": "E07000174", "register-code": "MAS", "name": "Mansfield"},
"00LC": {"GSS": "E06000035", "register-code": "MDW", "name": "Medway"},
"31UG": {"GSS": "E07000133", "register-code": "MEL", "name": "Melton"},
"18UD": {"GSS": "E07000042", "register-code": "MDE", "name": "<NAME>"},
"42UE": {"GSS": "E07000203", "register-code": "MSU", "name": "Mid Suffolk"},
"00EC": {"GSS": "E06000002", "register-code": "MDB", "name": "Middlesbrough"},
"00MG": {"GSS": "E06000042", "register-code": "MIK", "name": "<NAME>"},
"43UE": {"GSS": "E07000210", "register-code": "MOL", "name": "<NAME>"},
"24UJ": {"GSS": "E07000091", "register-code": "NEW", "name": "New Forest"},
"37UG": {"GSS": "E07000175", "register-code": "NEA", "name": "Newark and Sherwood"},
"00CJ": {"GSS": "E08000021", "register-code": "NET", "name": "Newcastle upon Tyne"},
"17UJ": {
"GSS": "E07000038",
"register-code": "NED",
"name": "North East Derbyshire",
},
"32UE": {"GSS": "E07000139", "register-code": "NKE", "name": "North Kesteven"},
"00HC": {"GSS": "E06000024", "register-code": "NSM", "name": "North Somerset"},
"00CK": {"GSS": "E08000022", "register-code": "NTY", "name": "North Tyneside"},
"44UB": {"GSS": "E07000218", "register-code": "NWA", "name": "North Warwickshire"},
"31UH": {
"GSS": "E07000134",
"register-code": "NWL",
"name": "North West Leicestershire",
},
"34UF": {"GSS": "E07000154", "register-code": "NOR", "name": "Northampton"},
"00EM": {"GSS": "E06000057", "register-code": "NBL", "name": "Northumberland"},
"33UG": {"GSS": "E07000148", "register-code": "NOW", "name": "Norwich"},
"00FY": {"GSS": "E06000018", "register-code": "NGM", "name": "Nottingham"},
"44UC": {
"GSS": "E07000219",
"register-code": "NUN",
"name": "<NAME>",
},
"31UJ": {"GSS": "E07000135", "register-code": "OAD", "name": "<NAME>"},
"00BP": {"GSS": "E08000004", "register-code": "OLD", "name": "Oldham"},
"38UC": {"GSS": "E07000178", "register-code": "OXO", "name": "Oxford"},
"00MR": {"GSS": "E06000044", "register-code": "POR", "name": "Portsmouth"},
"00MC": {"GSS": "E06000038", "register-code": "RDG", "name": "Reading"},
"47UD": {"GSS": "E07000236", "register-code": "RED", "name": "Redditch"},
"30UL": {"GSS": "E07000124", "register-code": "RIB", "name": "<NAME>"},
"36UE": {"GSS": "E07000166", "register-code": "RIH", "name": "Richmondshire"},
"00BQ": {"GSS": "E08000005", "register-code": "RCH", "name": "Rochdale"},
"30UM": {"GSS": "E07000125", "register-code": "ROS", "name": "Rossendale"},
"00CF": {"GSS": "E08000018", "register-code": "ROT", "name": "Rotherham"},
"00AW": {
"GSS": "E09000020",
"register-code": "KEC",
"name": "<NAME>",
},
"00AX": {
"GSS": "E09000021",
"register-code": "KTT",
"name": "<NAME>",
},
"44UD": {"GSS": "E07000220", "register-code": "RUG", "name": "Rugby"},
"43UG": {"GSS": "E07000212", "register-code": "RUN", "name": "Runnymede"},
"36UF": {"GSS": "E07000167", "register-code": "RYE", "name": "Ryedale"},
"00BR": {"GSS": "E08000006", "register-code": "SLF", "name": "Salford"},
"00CS": {"GSS": "E08000028", "register-code": "SAW", "name": "Sandwell"},
"40UC": {"GSS": "E07000188", "register-code": "SEG", "name": "Sedgemoor"},
"36UH": {"GSS": "E07000169", "register-code": "SEL", "name": "Selby"},
"00CG": {"GSS": "E08000019", "register-code": "SHF", "name": "Sheffield"},
"29UL": {"GSS": "E07000112", "register-code": "SHE", "name": "Shepway"},
"00GG": {"GSS": "E06000051", "register-code": "SHR", "name": "Shropshire"},
"00MD": {"GSS": "E06000039", "register-code": "SLG", "name": "Slough"},
"00CT": {"GSS": "E08000029", "register-code": "SOL", "name": "Solihull"},
"5067": {
"GSS": "E07000246",
"register-code": "SWT",
"name": "<NAME>",
},
"12UG": {
"GSS": "E07000012",
"register-code": "SCA",
"name": "South Cambridgeshire",
},
"17UK": {"GSS": "E07000039", "register-code": "SDE", "name": "South Derbyshire"},
"5078": {"GSS": "E07000044", "register-code": "SHA", "name": "South Hams"},
"32UF": {"GSS": "E07000140", "register-code": "SHO", "name": "South Holland"},
"32UG": {"GSS": "E07000141", "register-code": "SKE", "name": "South Kesteven"},
"16UG": {"GSS": "E07000031", "register-code": "SLA", "name": "South Lakeland"},
"5085": {"GSS": "E07000126", "register-code": "SRI", "name": "South Ribble"},
"00CL": {"GSS": "E08000023", "register-code": "STY", "name": "South Tyneside"},
"00MS": {"GSS": "E06000045", "register-code": "STH", "name": "Southampton"},
"00KF": {"GSS": "E06000033", "register-code": "SOS", "name": "Southend-on-Sea"},
"00BE": {"GSS": "E09000028", "register-code": "SWK", "name": "Southwark"},
"5091": {"GSS": "E07000213", "register-code": "SPE", "name": "Spelthorne"},
"26UG": {"GSS": "E07000100", "register-code": "SAL", "name": "St Albans"},
"26UH": {"GSS": "E07000101", "register-code": "STV", "name": "Stevenage"},
"00BS": {"GSS": "E08000007", "register-code": "SKP", "name": "Stockport"},
"00EF": {"GSS": "E06000004", "register-code": "STT", "name": "Stockton-on-Tees"},
"00GL": {"GSS": "E06000021", "register-code": "STE", "name": "Stoke-on-Trent"},
"23UF": {"GSS": "E07000082", "register-code": "STO", "name": "Stroud"},
"5080": {"GSS": "E08000024", "register-code": "SND", "name": "Sunderland"},
"42UG": {"GSS": "E07000205", "register-code": "SUF", "name": "Suffolk Coastal"},
"00HX": {"GSS": "E06000030", "register-code": "SWD", "name": "Swindon"},
"41UK": {"GSS": "E07000199", "register-code": "TAW", "name": "Tamworth"},
"43UK": {"GSS": "E07000215", "register-code": "TAN", "name": "Tandridge"},
"40UE": {"GSS": "E07000190", "register-code": "TAU", "name": "<NAME>"},
"18UH": {"GSS": "E07000045", "register-code": "TEI", "name": "Teignbridge"},
"22UN": {"GSS": "E07000076", "register-code": "TEN", "name": "Tendring"},
"29UN": {"GSS": "E07000114", "register-code": "THA", "name": "Thanet"},
"00KG": {"GSS": "E06000034", "register-code": "THR", "name": "Thurrock"},
"29UP": {
"GSS": "E07000115",
"register-code": "TON",
"name": "<NAME>",
},
"22UQ": {"GSS": "E07000077", "register-code": "UTT", "name": "Uttlesford"},
"00EU": {"GSS": "E06000007", "register-code": "WRT", "name": "Warrington"},
"44UF": {"GSS": "E07000222", "register-code": "WAW", "name": "Warwick"},
"26UK": {"GSS": "E07000103", "register-code": "WAT", "name": "Watford"},
"42UH": {"GSS": "E07000206", "register-code": "WAV", "name": "Waveney"},
"43UL": {"GSS": "E07000216", "register-code": "WAE", "name": "Waverley"},
"21UH": {"GSS": "E07000065", "register-code": "WEA", "name": "Wealden"},
"26UL": {"GSS": "E07000104", "register-code": "WEW", "name": "<NAME>"},
"00MB": {"GSS": "E06000037", "register-code": "WBK", "name": "West Berkshire"},
"5077": {"GSS": "E07000047", "register-code": "WDE", "name": "West Devon"},
"30UP": {"GSS": "E07000127", "register-code": "WLA", "name": "West Lancashire"},
"5068": {"GSS": "E07000245", "register-code": "WSK", "name": "West Suffolk"},
"00BW": {"GSS": "E08000010", "register-code": "WGN", "name": "Wigan"},
"00HY": {"GSS": "E06000054", "register-code": "WIL", "name": "Wiltshire"},
"24UP": {"GSS": "E07000094", "register-code": "WIN", "name": "Winchester"},
"00CB": {"GSS": "E08000015", "register-code": "WRL", "name": "Wirral"},
"43UM": {"GSS": "E07000217", "register-code": "WOI", "name": "Woking"},
"00MF": {"GSS": "E06000041", "register-code": "WOK", "name": "Wokingham"},
"00CW": {"GSS": "E08000031", "register-code": "WLV", "name": "Wolverhampton"},
"11UF": {"GSS": "E07000007", "register-code": "WYO", "name": "Wycombe"},
}
|
keyboardcowboy42/LightZone | lightcrafts/jnisrc/lcms/lcms/cmsgamma.c | <gh_stars>10-100
//
// Little cms
// Copyright (C) 1998-2006 <NAME>
//
// 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.
#include "lcms.h"
// Gamma handling.
LPGAMMATABLE LCMSEXPORT cmsAllocGamma(int nEntries);
void LCMSEXPORT cmsFreeGamma(LPGAMMATABLE Gamma);
void LCMSEXPORT cmsFreeGammaTriple(LPGAMMATABLE Gamma[3]);
LPGAMMATABLE LCMSEXPORT cmsBuildGamma(int nEntries, double Gamma);
LPGAMMATABLE LCMSEXPORT cmsDupGamma(LPGAMMATABLE Src);
LPGAMMATABLE LCMSEXPORT cmsReverseGamma(int nResultSamples, LPGAMMATABLE InGamma);
LPGAMMATABLE LCMSEXPORT cmsBuildParametricGamma(int nEntries, int Type, double Params[]);
LPGAMMATABLE LCMSEXPORT cmsJoinGamma(LPGAMMATABLE InGamma, LPGAMMATABLE OutGamma);
LPGAMMATABLE LCMSEXPORT cmsJoinGammaEx(LPGAMMATABLE InGamma, LPGAMMATABLE OutGamma, int nPoints);
BOOL LCMSEXPORT cmsSmoothGamma(LPGAMMATABLE Tab, double lambda);
BOOL cdecl _cmsSmoothEndpoints(LPWORD Table, int nPoints);
// Sampled curves
LPSAMPLEDCURVE cdecl cmsAllocSampledCurve(int nItems);
void cdecl cmsFreeSampledCurve(LPSAMPLEDCURVE p);
void cdecl cmsEndpointsOfSampledCurve(LPSAMPLEDCURVE p, double* Min, double* Max);
void cdecl cmsClampSampledCurve(LPSAMPLEDCURVE p, double Min, double Max);
BOOL cdecl cmsSmoothSampledCurve(LPSAMPLEDCURVE Tab, double SmoothingLambda);
void cdecl cmsRescaleSampledCurve(LPSAMPLEDCURVE p, double Min, double Max, int nPoints);
LPSAMPLEDCURVE cdecl cmsJoinSampledCurves(LPSAMPLEDCURVE X, LPSAMPLEDCURVE Y, int nResultingPoints);
double LCMSEXPORT cmsEstimateGamma(LPGAMMATABLE t);
double LCMSEXPORT cmsEstimateGammaEx(LPWORD GammaTable, int nEntries, double Thereshold);
// ----------------------------------------------------------------------------------------
#define MAX_KNOTS 4096
typedef float vec[MAX_KNOTS+1];
// Ciclic-redundant-check for assuring table is a true representation of parametric curve
// The usual polynomial, which is used for AAL5, FDDI, and probably Ethernet
#define QUOTIENT 0x04c11db7
static
unsigned int Crc32(unsigned int result, LPVOID ptr, int len)
{
int i,j;
BYTE octet;
LPBYTE data = (LPBYTE) ptr;
for (i=0; i < len; i++) {
octet = *data++;
for (j=0; j < 8; j++) {
if (result & 0x80000000) {
result = (result << 1) ^ QUOTIENT ^ (octet >> 7);
}
else
{
result = (result << 1) ^ (octet >> 7);
}
octet <<= 1;
}
}
return result;
}
// Get CRC of gamma table
unsigned int _cmsCrc32OfGammaTable(LPGAMMATABLE Table)
{
unsigned int crc = ~0U;
crc = Crc32(crc, &Table -> Seed.Type, sizeof(int));
crc = Crc32(crc, Table ->Seed.Params, sizeof(double)*10);
crc = Crc32(crc, &Table ->nEntries, sizeof(int));
crc = Crc32(crc, Table ->GammaTable, sizeof(WORD) * Table -> nEntries);
return ~crc;
}
LPGAMMATABLE LCMSEXPORT cmsAllocGamma(int nEntries)
{
LPGAMMATABLE p;
size_t size;
if (nEntries > 65530) {
cmsSignalError(LCMS_ERRC_WARNING, "Couldn't create gammatable of more than 65530 entries; 65530 assumed");
nEntries = 65530;
}
size = sizeof(GAMMATABLE) + (sizeof(WORD) * (nEntries-1));
p = (LPGAMMATABLE) malloc(size);
if (!p) return NULL;
ZeroMemory(p, size);
p -> Seed.Type = 0;
p -> nEntries = nEntries;
return p;
}
void LCMSEXPORT cmsFreeGamma(LPGAMMATABLE Gamma)
{
if (Gamma) free(Gamma);
}
void LCMSEXPORT cmsFreeGammaTriple(LPGAMMATABLE Gamma[3])
{
cmsFreeGamma(Gamma[0]);
cmsFreeGamma(Gamma[1]);
cmsFreeGamma(Gamma[2]);
Gamma[0] = Gamma[1] = Gamma[2] = NULL;
}
// Duplicate a gamma table
LPGAMMATABLE LCMSEXPORT cmsDupGamma(LPGAMMATABLE In)
{
LPGAMMATABLE Ptr;
size_t size;
Ptr = cmsAllocGamma(In -> nEntries);
if (Ptr == NULL) return NULL;
size = sizeof(GAMMATABLE) + (sizeof(WORD) * (In -> nEntries-1));
CopyMemory(Ptr, In, size);
return Ptr;
}
// Handle gamma using interpolation tables. The resulting curves can become
// very stange, but are pleasent to eye.
LPGAMMATABLE LCMSEXPORT cmsJoinGamma(LPGAMMATABLE InGamma,
LPGAMMATABLE OutGamma)
{
register int i;
L16PARAMS L16In, L16Out;
LPWORD InPtr, OutPtr;
LPGAMMATABLE p;
p = cmsAllocGamma(256);
if (!p) return NULL;
cmsCalcL16Params(InGamma -> nEntries, &L16In);
InPtr = InGamma -> GammaTable;
cmsCalcL16Params(OutGamma -> nEntries, &L16Out);
OutPtr = OutGamma-> GammaTable;
for (i=0; i < 256; i++)
{
WORD wValIn, wValOut;
wValIn = cmsLinearInterpLUT16(RGB_8_TO_16(i), InPtr, &L16In);
wValOut = cmsReverseLinearInterpLUT16(wValIn, OutPtr, &L16Out);
p -> GammaTable[i] = wValOut;
}
return p;
}
// New method, using smoothed parametric curves. This works FAR better.
// We want to get
//
// y = f(g^-1(x)) ; f = ingamma, g = outgamma
//
// And this can be parametrized as
//
// y = f(t)
// x = g(t)
LPGAMMATABLE LCMSEXPORT cmsJoinGammaEx(LPGAMMATABLE InGamma,
LPGAMMATABLE OutGamma, int nPoints)
{
LPSAMPLEDCURVE x, y, r;
LPGAMMATABLE res;
x = cmsConvertGammaToSampledCurve(InGamma, nPoints);
y = cmsConvertGammaToSampledCurve(OutGamma, nPoints);
r = cmsJoinSampledCurves(y, x, nPoints);
// Does clean "hair"
cmsSmoothSampledCurve(r, 0.001);
cmsClampSampledCurve(r, 0.0, 65535.0);
cmsFreeSampledCurve(x);
cmsFreeSampledCurve(y);
res = cmsConvertSampledCurveToGamma(r, 65535.0);
cmsFreeSampledCurve(r);
return res;
}
// Reverse a gamma table
LPGAMMATABLE LCMSEXPORT cmsReverseGamma(int nResultSamples, LPGAMMATABLE InGamma)
{
register int i;
L16PARAMS L16In;
LPWORD InPtr;
LPGAMMATABLE p;
p = cmsAllocGamma(nResultSamples);
if (!p) return NULL;
cmsCalcL16Params(InGamma -> nEntries, &L16In);
InPtr = InGamma -> GammaTable;
for (i=0; i < nResultSamples; i++)
{
WORD wValIn, wValOut;
wValIn = _cmsQuantizeVal(i, nResultSamples);
wValOut = cmsReverseLinearInterpLUT16(wValIn, InPtr, &L16In);
p -> GammaTable[i] = wValOut;
}
return p;
}
// Parametric curves
//
// Parameters goes as: Gamma, a, b, c, d, e, f
// Type is the ICC type +1
// if type is negative, then the curve is analyticaly inverted
LPGAMMATABLE LCMSEXPORT cmsBuildParametricGamma(int nEntries, int Type, double Params[])
{
LPGAMMATABLE Table;
double R, Val, dval, e;
int i;
int ParamsByType[] = { 0, 1, 3, 4, 5, 7 };
Table = cmsAllocGamma(nEntries);
if (NULL == Table) return NULL;
Table -> Seed.Type = Type;
CopyMemory(Table ->Seed.Params, Params, ParamsByType[abs(Type)] * sizeof(double));
for (i=0; i < nEntries; i++) {
R = (double) i / (nEntries-1);
switch (Type) {
// X = Y ^ Gamma
case 1:
Val = pow(R, Params[0]);
break;
// Type 1 Reversed: X = Y ^1/gamma
case -1:
Val = pow(R, 1/Params[0]);
break;
// CIE 122-1966
// Y = (aX + b)^Gamma | X >= -b/a
// Y = 0 | else
case 2:
if (R >= -Params[2] / Params[1]) {
e = Params[1]*R + Params[2];
if (e > 0)
Val = pow(e, Params[0]);
else
Val = 0;
}
else
Val = 0;
break;
// Type 2 Reversed
// X = (Y ^1/g - b) / a
case -2:
Val = (pow(R, 1.0/Params[0]) - Params[2]) / Params[1];
if (Val < 0)
Val = 0;
break;
// IEC 61966-3
// Y = (aX + b)^Gamma | X <= -b/a
// Y = c | else
case 3:
if (R >= -Params[2] / Params[1]) {
e = Params[1]*R + Params[2];
Val = pow(e, Params[0]) + Params[3];
}
else
Val = Params[3];
break;
// Type 3 reversed
// X=((Y-c)^1/g - b)/a | (Y>=c)
// X=-b/a | (Y<c)
case -3:
if (R >= Params[3]) {
e = R - Params[3];
Val = (pow(e, 1/Params[0]) - Params[2]) / Params[1];
if (Val < 0) Val = 0;
}
else {
Val = -Params[2] / Params[1];
}
break;
// IEC 61966-2.1 (sRGB)
// Y = (aX + b)^Gamma | X >= d
// Y = cX | X < d
case 4:
if (R >= Params[4]) {
e = Params[1]*R + Params[2];
if (e > 0)
Val = pow(e, Params[0]);
else
Val = 0;
}
else
Val = R * Params[3];
break;
// Type 4 reversed
// X=((Y^1/g-b)/a) | Y >= (ad+b)^g
// X=Y/c | Y< (ad+b)^g
case -4:
if (R >= pow(Params[1] * Params[4] + Params[2], Params[0])) {
Val = (pow(R, 1.0/Params[0]) - Params[2]) / Params[1];
}
else {
Val = R / Params[3];
}
break;
// Y = (aX + b)^Gamma + e | X <= d
// Y = cX + f | else
case 5:
if (R >= Params[4]) {
e = Params[1]*R + Params[2];
Val = pow(e, Params[0]) + Params[5];
}
else
Val = R*Params[3] + Params[6];
break;
// Reversed type 5
// X=((Y-e)1/g-b)/a | Y >=(ad+b)^g+e)
// X=(Y-f)/c | else
case -5:
if (R >= pow(Params[1] * Params[4], Params[0]) + Params[5]) {
Val = pow(R - Params[5], 1/Params[0]) - Params[2] / Params[1];
}
else {
Val = (R - Params[6]) / Params[3];
}
break;
default:
cmsSignalError(LCMS_ERRC_ABORTED, "Unsupported parametric curve type=%d", abs(Type)-1);
cmsFreeGamma(Table);
return NULL;
}
// Saturate
dval = Val * 65535.0 + .5;
if (dval > 65535.) dval = 65535.0;
if (dval < 0) dval = 0;
Table->GammaTable[i] = (WORD) floor(dval);
}
Table -> Seed.Crc32 = _cmsCrc32OfGammaTable(Table);
return Table;
}
// Build a gamma table based on gamma constant
LPGAMMATABLE LCMSEXPORT cmsBuildGamma(int nEntries, double Gamma)
{
return cmsBuildParametricGamma(nEntries, 1, &Gamma);
}
// From: <NAME>. (1994) Smoothing and interpolation with finite
// differences. in: Graphic Gems IV, Heckbert, P.S. (ed.), Academic press.
//
// Smoothing and interpolation with second differences.
//
// Input: weights (w), data (y): vector from 1 to m.
// Input: smoothing parameter (lambda), length (m).
// Output: smoothed vector (z): vector from 1 to m.
static
void smooth2(vec w, vec y, vec z, float lambda, int m)
{
int i, i1, i2;
vec c, d, e;
d[1] = w[1] + lambda;
c[1] = -2 * lambda / d[1];
e[1] = lambda /d[1];
z[1] = w[1] * y[1];
d[2] = w[2] + 5 * lambda - d[1] * c[1] * c[1];
c[2] = (-4 * lambda - d[1] * c[1] * e[1]) / d[2];
e[2] = lambda / d[2];
z[2] = w[2] * y[2] - c[1] * z[1];
for (i = 3; i < m - 1; i++) {
i1 = i - 1; i2 = i - 2;
d[i]= w[i] + 6 * lambda - c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2];
c[i] = (-4 * lambda -d[i1] * c[i1] * e[i1])/ d[i];
e[i] = lambda / d[i];
z[i] = w[i] * y[i] - c[i1] * z[i1] - e[i2] * z[i2];
}
i1 = m - 2; i2 = m - 3;
d[m - 1] = w[m - 1] + 5 * lambda -c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2];
c[m - 1] = (-2 * lambda - d[i1] * c[i1] * e[i1]) / d[m - 1];
z[m - 1] = w[m - 1] * y[m - 1] - c[i1] * z[i1] - e[i2] * z[i2];
i1 = m - 1; i2 = m - 2;
d[m] = w[m] + lambda - c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2];
z[m] = (w[m] * y[m] - c[i1] * z[i1] - e[i2] * z[i2]) / d[m];
z[m - 1] = z[m - 1] / d[m - 1] - c[m - 1] * z[m];
for (i = m - 2; 1<= i; i--)
z[i] = z[i] / d[i] - c[i] * z[i + 1] - e[i] * z[i + 2];
}
// Smooths a curve sampled at regular intervals
BOOL LCMSEXPORT cmsSmoothGamma(LPGAMMATABLE Tab, double lambda)
{
vec w, y, z;
int i, nItems, Zeros, Poles;
if (cmsIsLinear(Tab->GammaTable, Tab->nEntries)) return FALSE; // Nothing to do
nItems = Tab -> nEntries;
if (nItems > MAX_KNOTS) {
cmsSignalError(LCMS_ERRC_ABORTED, "cmsSmoothGamma: too many points.");
return FALSE;
}
ZeroMemory(w, nItems * sizeof(float));
ZeroMemory(y, nItems * sizeof(float));
ZeroMemory(z, nItems * sizeof(float));
for (i=0; i < nItems; i++)
{
y[i+1] = (float) Tab -> GammaTable[i];
w[i+1] = 1.0;
}
smooth2(w, y, z, (float) lambda, nItems);
// Do some reality - checking...
Zeros = Poles = 0;
for (i=nItems; i > 1; --i) {
if (z[i] == 0.) Zeros++;
if (z[i] >= 65535.) Poles++;
if (z[i] < z[i-1]) return FALSE; // Non-Monotonic
}
if (Zeros > (nItems / 3)) return FALSE; // Degenerated, mostly zeros
if (Poles > (nItems / 3)) return FALSE; // Degenerated, mostly poles
// Seems ok
for (i=0; i < nItems; i++) {
// Clamp to WORD
float v = z[i+1];
if (v < 0) v = 0;
if (v > 65535.) v = 65535.;
Tab -> GammaTable[i] = (WORD) floor(v + .5);
}
return TRUE;
}
// Check if curve is exponential, return gamma if so.
double LCMSEXPORT cmsEstimateGammaEx(LPWORD GammaTable, int nEntries, double Thereshold)
{
double gamma, sum, sum2;
double n, x, y, Std;
int i;
sum = sum2 = n = 0;
// Does exclude endpoints
for (i=1; i < nEntries - 1; i++) {
x = (double) i / (nEntries - 1);
y = (double) GammaTable[i] / 65535.;
// Avoid 7% on lower part to prevent
// artifacts due to linear ramps
if (y > 0. && y < 1. && x > 0.07) {
gamma = log(y) / log(x);
sum += gamma;
sum2 += gamma * gamma;
n++;
}
}
// Take a look on SD to see if gamma isn't exponential at all
Std = sqrt((n * sum2 - sum * sum) / (n*(n-1)));
if (Std > Thereshold)
return -1.0;
return (sum / n); // The mean
}
double LCMSEXPORT cmsEstimateGamma(LPGAMMATABLE t)
{
return cmsEstimateGammaEx(t->GammaTable, t->nEntries, 0.7);
}
// -----------------------------------------------------------------Sampled curves
// Allocate a empty curve
LPSAMPLEDCURVE cmsAllocSampledCurve(int nItems)
{
LPSAMPLEDCURVE pOut;
pOut = (LPSAMPLEDCURVE) malloc(sizeof(SAMPLEDCURVE));
if (pOut == NULL)
return NULL;
if((pOut->Values = (double *) malloc(nItems * sizeof(double))) == NULL)
{
free(pOut);
return NULL;
}
pOut->nItems = nItems;
ZeroMemory(pOut->Values, nItems * sizeof(double));
return pOut;
}
void cmsFreeSampledCurve(LPSAMPLEDCURVE p)
{
free((LPVOID) p -> Values);
free((LPVOID) p);
}
// Does duplicate a sampled curve
LPSAMPLEDCURVE cmsDupSampledCurve(LPSAMPLEDCURVE p)
{
LPSAMPLEDCURVE out;
out = cmsAllocSampledCurve(p -> nItems);
if (!out) return NULL;
CopyMemory(out ->Values, p ->Values, p->nItems * sizeof(double));
return out;
}
// Take min, max of curve
void cmsEndpointsOfSampledCurve(LPSAMPLEDCURVE p, double* Min, double* Max)
{
int i;
*Min = 65536.;
*Max = 0.;
for (i=0; i < p -> nItems; i++) {
double v = p -> Values[i];
if (v < *Min)
*Min = v;
if (v > *Max)
*Max = v;
}
if (*Min < 0) *Min = 0;
if (*Max > 65535.0) *Max = 65535.0;
}
// Clamps to Min, Max
void cmsClampSampledCurve(LPSAMPLEDCURVE p, double Min, double Max)
{
int i;
for (i=0; i < p -> nItems; i++) {
double v = p -> Values[i];
if (v < Min)
v = Min;
if (v > Max)
v = Max;
p -> Values[i] = v;
}
}
// Smooths a curve sampled at regular intervals
BOOL cmsSmoothSampledCurve(LPSAMPLEDCURVE Tab, double lambda)
{
vec w, y, z;
int i, nItems;
nItems = Tab -> nItems;
if (nItems > MAX_KNOTS) {
cmsSignalError(LCMS_ERRC_ABORTED, "cmsSmoothSampledCurve: too many points.");
return FALSE;
}
ZeroMemory(w, nItems * sizeof(float));
ZeroMemory(y, nItems * sizeof(float));
ZeroMemory(z, nItems * sizeof(float));
for (i=0; i < nItems; i++)
{
float value = (float) Tab -> Values[i];
y[i+1] = value;
w[i+1] = (float) ((value < 0.0) ? 0 : 1);
}
smooth2(w, y, z, (float) lambda, nItems);
for (i=0; i < nItems; i++) {
Tab -> Values[i] = z[i+1];;
}
return TRUE;
}
// Scale a value v, within domain Min .. Max
// to a domain 0..(nPoints-1)
static
double ScaleVal(double v, double Min, double Max, int nPoints)
{
double a, b;
if (v <= Min) return 0;
if (v >= Max) return (nPoints-1);
a = (double) (nPoints - 1) / (Max - Min);
b = a * Min;
return (a * v) - b;
}
// Does rescale a sampled curve to fit in a 0..(nPoints-1) domain
void cmsRescaleSampledCurve(LPSAMPLEDCURVE p, double Min, double Max, int nPoints)
{
int i;
for (i=0; i < p -> nItems; i++) {
double v = p -> Values[i];
p -> Values[i] = ScaleVal(v, Min, Max, nPoints);
}
}
// Joins two sampled curves for X and Y. Curves should be sorted.
LPSAMPLEDCURVE cmsJoinSampledCurves(LPSAMPLEDCURVE X, LPSAMPLEDCURVE Y, int nResultingPoints)
{
int i, j;
LPSAMPLEDCURVE out;
double MinX, MinY, MaxX, MaxY;
double x, y, x1, y1, x2, y2, a, b;
out = cmsAllocSampledCurve(nResultingPoints);
if (out == NULL)
return NULL;
if (X -> nItems != Y -> nItems) {
cmsSignalError(LCMS_ERRC_ABORTED, "cmsJoinSampledCurves: invalid curve.");
cmsFreeSampledCurve(out);
return NULL;
}
// Get endpoints of sampled curves
cmsEndpointsOfSampledCurve(X, &MinX, &MaxX);
cmsEndpointsOfSampledCurve(Y, &MinY, &MaxY);
// Set our points
out ->Values[0] = MinY;
for (i=1; i < nResultingPoints; i++) {
// Scale t to x domain
x = (i * (MaxX - MinX) / (nResultingPoints-1)) + MinX;
// Find interval in which j is within (always up,
// since fn should be monotonic at all)
j = 1;
while ((j < X ->nItems - 1) && X ->Values[j] < x)
j++;
// Now x is within X[j-1], X[j]
x1 = X ->Values[j-1]; x2 = X ->Values[j];
y1 = Y ->Values[j-1]; y2 = Y ->Values[j];
// Interpolate the value
a = (y1 - y2) / (x1 - x2);
b = y1 - a * x1;
y = a* x + b;
out ->Values[i] = y;
}
cmsClampSampledCurve(out, MinY, MaxY);
return out;
}
// Convert between curve types
LPGAMMATABLE cmsConvertSampledCurveToGamma(LPSAMPLEDCURVE Sampled, double Max)
{
LPGAMMATABLE Gamma;
int i, nPoints;
nPoints = Sampled ->nItems;
Gamma = cmsAllocGamma(nPoints);
for (i=0; i < nPoints; i++) {
Gamma->GammaTable[i] = (WORD) floor(ScaleVal(Sampled ->Values[i], 0, Max, 65536) + .5);
}
return Gamma;
}
// Inverse of anterior
LPSAMPLEDCURVE cmsConvertGammaToSampledCurve(LPGAMMATABLE Gamma, int nPoints)
{
LPSAMPLEDCURVE Sampled;
L16PARAMS L16;
int i;
WORD wQuant, wValIn;
if (nPoints > 4096) {
cmsSignalError(LCMS_ERRC_ABORTED, "cmsConvertGammaToSampledCurve: too many points (max=4096)");
return NULL;
}
cmsCalcL16Params(Gamma -> nEntries, &L16);
Sampled = cmsAllocSampledCurve(nPoints);
for (i=0; i < nPoints; i++) {
wQuant = _cmsQuantizeVal(i, nPoints);
wValIn = cmsLinearInterpLUT16(wQuant, Gamma ->GammaTable, &L16);
Sampled ->Values[i] = (float) wValIn;
}
return Sampled;
}
// Smooth endpoints (used in Black/White compensation)
BOOL _cmsSmoothEndpoints(LPWORD Table, int nEntries)
{
vec w, y, z;
int i, Zeros, Poles;
if (cmsIsLinear(Table, nEntries)) return FALSE; // Nothing to do
if (nEntries > MAX_KNOTS) {
cmsSignalError(LCMS_ERRC_ABORTED, "_cmsSmoothEndpoints: too many points.");
return FALSE;
}
ZeroMemory(w, nEntries * sizeof(float));
ZeroMemory(y, nEntries * sizeof(float));
ZeroMemory(z, nEntries * sizeof(float));
for (i=0; i < nEntries; i++)
{
y[i+1] = (float) Table[i];
w[i+1] = 1.0;
}
w[1] = 65535.0;
w[nEntries] = 65535.0;
smooth2(w, y, z, (float) nEntries, nEntries);
// Do some reality - checking...
Zeros = Poles = 0;
for (i=nEntries; i > 1; --i) {
if (z[i] == 0.) Zeros++;
if (z[i] >= 65535.) Poles++;
if (z[i] < z[i-1]) return FALSE; // Non-Monotonic
}
if (Zeros > (nEntries / 3)) return FALSE; // Degenerated, mostly zeros
if (Poles > (nEntries / 3)) return FALSE; // Degenerated, mostly poles
// Seems ok
for (i=0; i < nEntries; i++) {
// Clamp to WORD
float v = z[i+1];
if (v < 0) v = 0;
if (v > 65535.) v = 65535.;
Table[i] = (WORD) floor(v + .5);
}
return TRUE;
}
|
ARCHTK-prog/utils-tools | utils-spider/src/main/java/com/chua/utils/tools/spider/interpreter/AbstractPageInterpreter.java | package com.chua.utils.tools.spider.interpreter;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
/**
* 页面处理
* @author CH
*/
public abstract class AbstractPageInterpreter implements IPageInterpreter{
private Set<String> nodes = new HashSet<>();
private Consumer<Map<String, List<String>>> consumer;
@Override
public Set<String> getModifier() {
return nodes;
}
@Override
public IPageInterpreter setModifier(Set<String> modifiers) {
nodes.clear();
nodes.addAll(modifiers);
return this;
}
@Override
public IPageInterpreter addModifier(String modifiers) {
nodes.add(modifiers);
return this;
}
@Override
public IPageInterpreter callback(Consumer<Map<String, List<String>>> consumer) {
this.consumer = consumer;
return this;
}
@Override
public Consumer<Map<String, List<String>>> callback() {
return consumer;
}
}
|
prepare/vmware-svga-git | examples/cubemark/main.c | <filename>examples/cubemark/main.c
/*
* Cubemark, a microbenchmark which renders a very large number of
* very simple objects. This stresses the throughput of the SVGA3D
* command pipeline and API layers.
*
* Half of the cubes are rendered using fixed-function, and half of
* them are rendered using shaders. This helps hilight any performance
* differences between per-draw setup for FFP vs. for shaders.
*
* Copyright (C) 2008-2009 VMware, Inc. Licensed under the MIT
* License, please see the README.txt. All rights reserved.
*/
#include "svga3dutil.h"
#include "svga3dtext.h"
#include "matrix.h"
#include "math.h"
typedef uint32 DWORD;
#include "cube_vs.h"
#include "cube_ps.h"
#define MY_VSHADER_ID 0
#define MY_PSHADER_ID 0
#define CONST_MAT_VIEW 0
#define CONST_MAT_PROJ 4
typedef struct {
float position[3];
uint32 color;
} MyVertex;
/*
* Two colors for the cubes, so we can see them rotate more easily.
*/
#define COLOR1 0x8080FF
#define COLOR2 0x000080
/*
* This defines the grid spacing, as well as the total number of cubes we draw.
*/
#define GRID_X_MIN (-35)
#define GRID_X_MAX 35
#define GRID_Y_MIN (-20)
#define GRID_Y_MAX 20
#define GRID_STEP 2
static const MyVertex vertexData[] = {
{ {-1, -1, -1}, COLOR1 },
{ {-1, -1, 1}, COLOR1 },
{ {-1, 1, -1}, COLOR1 },
{ {-1, 1, 1}, COLOR1 },
{ { 1, -1, -1}, COLOR2 },
{ { 1, -1, 1}, COLOR2 },
{ { 1, 1, -1}, COLOR2 },
{ { 1, 1, 1}, COLOR2 },
};
#define QUAD(a,b,c,d) a, b, d, d, c, a
static const uint16 indexData[] = {
QUAD(0,1,2,3), // -X
QUAD(4,5,6,7), // +X
QUAD(0,1,4,5), // -Y
QUAD(2,3,6,7), // +Y
QUAD(0,2,4,6), // -Z
QUAD(1,3,5,7), // +Z
};
#undef QUAD
const uint32 numTriangles = sizeof indexData / sizeof indexData[0] / 3;
uint32 vertexSid, indexSid;
Matrix perspectiveMat;
FPSCounterState gFPS;
VMMousePacket lastMouseState;
/*
* render --
*
* Set up common render state and matrices, then enter a loop
* drawing many cubes with individual draw commands.
*
* This render state only needs to be set each frame because
* SVGA3DText_Draw() changes it.
*/
void
render(void)
{
SVGA3dTextureState *ts;
SVGA3dRenderState *rs;
SVGA3dVertexDecl *decls;
SVGA3dPrimitiveRange *ranges;
static Matrix view, instance;
float x, y;
Bool useShaders = FALSE;
Matrix_Copy(view, gIdentityMatrix);
Matrix_Scale(view, 0.5, 0.5, 0.5, 1.0);
Matrix_RotateX(view, 30.0 * M_PI / 180.0);
Matrix_RotateY(view, gFPS.frame * 0.1f);
Matrix_Translate(view, 0, 0, 75);
SVGA3D_SetTransform(CID, SVGA3D_TRANSFORM_WORLD, gIdentityMatrix);
SVGA3D_SetTransform(CID, SVGA3D_TRANSFORM_PROJECTION, perspectiveMat);
SVGA3DUtil_SetShaderConstMatrix(CID, CONST_MAT_PROJ,
SVGA3D_SHADERTYPE_VS, perspectiveMat);
SVGA3D_BeginSetRenderState(CID, &rs, 4);
{
rs[0].state = SVGA3D_RS_BLENDENABLE;
rs[0].uintValue = FALSE;
rs[1].state = SVGA3D_RS_ZENABLE;
rs[1].uintValue = TRUE;
rs[2].state = SVGA3D_RS_ZWRITEENABLE;
rs[2].uintValue = TRUE;
rs[3].state = SVGA3D_RS_ZFUNC;
rs[3].uintValue = SVGA3D_CMP_LESS;
}
SVGA_FIFOCommitAll();
SVGA3D_BeginSetTextureState(CID, &ts, 4);
{
ts[0].stage = 0;
ts[0].name = SVGA3D_TS_BIND_TEXTURE;
ts[0].value = SVGA3D_INVALID_ID;
ts[1].stage = 0;
ts[1].name = SVGA3D_TS_COLOROP;
ts[1].value = SVGA3D_TC_SELECTARG1;
ts[2].stage = 0;
ts[2].name = SVGA3D_TS_COLORARG1;
ts[2].value = SVGA3D_TA_DIFFUSE;
ts[3].stage = 0;
ts[3].name = SVGA3D_TS_ALPHAARG1;
ts[3].value = SVGA3D_TA_DIFFUSE;
}
SVGA_FIFOCommitAll();
for (x = GRID_X_MIN; x <= GRID_X_MAX; x += GRID_STEP) {
for (y = GRID_Y_MIN; y <= GRID_Y_MAX; y += GRID_STEP) {
Matrix_Copy(instance, view);
Matrix_Translate(instance, x, y, 0);
if (useShaders) {
SVGA3D_SetShader(CID, SVGA3D_SHADERTYPE_VS, MY_VSHADER_ID);
SVGA3D_SetShader(CID, SVGA3D_SHADERTYPE_PS, MY_PSHADER_ID);
SVGA3DUtil_SetShaderConstMatrix(CID, CONST_MAT_VIEW,
SVGA3D_SHADERTYPE_VS, instance);
} else {
SVGA3D_SetShader(CID, SVGA3D_SHADERTYPE_VS, SVGA3D_INVALID_ID);
SVGA3D_SetShader(CID, SVGA3D_SHADERTYPE_PS, SVGA3D_INVALID_ID);
SVGA3D_SetTransform(CID, SVGA3D_TRANSFORM_VIEW, instance);
}
SVGA3D_BeginDrawPrimitives(CID, &decls, 2, &ranges, 1);
{
decls[0].identity.type = SVGA3D_DECLTYPE_FLOAT3;
decls[0].identity.usage = SVGA3D_DECLUSAGE_POSITION;
decls[0].array.surfaceId = vertexSid;
decls[0].array.stride = sizeof(MyVertex);
decls[0].array.offset = offsetof(MyVertex, position);
decls[1].identity.type = SVGA3D_DECLTYPE_D3DCOLOR;
decls[1].identity.usage = SVGA3D_DECLUSAGE_COLOR;
decls[1].array.surfaceId = vertexSid;
decls[1].array.stride = sizeof(MyVertex);
decls[1].array.offset = offsetof(MyVertex, color);
ranges[0].primType = SVGA3D_PRIMITIVE_TRIANGLELIST;
ranges[0].primitiveCount = numTriangles;
ranges[0].indexArray.surfaceId = indexSid;
ranges[0].indexArray.stride = sizeof(uint16);
ranges[0].indexWidth = sizeof(uint16);
}
SVGA_FIFOCommitAll();
}
useShaders = !useShaders;
}
SVGA3D_SetShader(CID, SVGA3D_SHADERTYPE_VS, SVGA3D_INVALID_ID);
SVGA3D_SetShader(CID, SVGA3D_SHADERTYPE_PS, SVGA3D_INVALID_ID);
}
/*
* main --
*
* Our example's entry point, invoked directly by the bootloader.
*/
int
main(void)
{
SVGA3DUtil_InitFullscreen(CID, 800, 600);
SVGA3DText_Init();
vertexSid = SVGA3DUtil_DefineStaticBuffer(vertexData, sizeof vertexData);
indexSid = SVGA3DUtil_DefineStaticBuffer(indexData, sizeof indexData);
SVGA3D_DefineShader(CID, MY_VSHADER_ID, SVGA3D_SHADERTYPE_VS,
g_vs20_MyVertexShader, sizeof g_vs20_MyVertexShader);
SVGA3D_DefineShader(CID, MY_PSHADER_ID, SVGA3D_SHADERTYPE_PS,
g_ps20_MyPixelShader, sizeof g_ps20_MyPixelShader);
Matrix_Perspective(perspectiveMat, 45.0f,
gSVGA.width / (float)gSVGA.height, 10.0f, 100.0f);
while (1) {
if (SVGA3DUtil_UpdateFPSCounter(&gFPS)) {
Console_Clear();
Console_Format("Cubemark microbenchmark\n\n%s", gFPS.text);
SVGA3DText_Update();
VMBackdoor_VGAScreenshot();
}
SVGA3DUtil_ClearFullscreen(CID, SVGA3D_CLEAR_COLOR | SVGA3D_CLEAR_DEPTH,
0x000000, 1.0f, 0);
render();
SVGA3DText_Draw();
SVGA3DUtil_PresentFullscreen();
}
return 0;
}
|
wgarcia1309/competitive-programming | URI Online Judge/Beginners/1158 - Sum of Consecutive Odd Numbers III.cpp | <gh_stars>0
//1158 - Sum of Consecutive Odd Numbers III
#include<iostream>
using namespace std;
int main(){
int n,t=0;
double c=0;
cin>>n;
for(int i=1;i<=n;i++){
int x,y,s=0;
cin>>x;
cin>>y;
y=x+(y*2);
if(x%2==0)x++;
for(int j=x;j<y;j+=2){
s+=j;
}
cout<<s<<endl;
}
return 0;
}
|
Robbbert/messui | src/devices/bus/isa/bt54x.cpp | // license:BSD-3-Clause
// copyright-holders:AJR
/***************************************************************************
BusTek/BusLogic BT-54x series PC/AT SCSI host adapters
The earlier version of the BT-542B, with BusTek labels, has a NCR 86C05
bus controller where a later version has the 80C20 ASIC instead. It is
believed that these chips are largely compatible with each other, as
are the NCR 53CF94 and Emulex FAS216 SCSI controllers.
2.41/2.21 is the last BIOS version compatible with revisions A-G of
the BT-542B.
***************************************************************************/
#include "emu.h"
#include "bt54x.h"
#include "bus/nscsi/devices.h"
#include "machine/ncr5390.h"
//#include "machine/ncr86c05.h"
DEFINE_DEVICE_TYPE(BT542B, bt542b_device, "bt542b", "BusTek BT-542B SCSI Host Adapter") // Rev. G or earlier
DEFINE_DEVICE_TYPE(BT542BH, bt542bh_device, "bt542bh", "BusLogic BT-542B SCSI Host Adapter (Rev. H)")
DEFINE_DEVICE_TYPE(BT545S, bt545s_device, "bt545s", "BusLogic BT-545S Fast SCSI Host Adapter")
bt54x_device::bt54x_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, u32 clock)
: device_t(mconfig, type, tag, owner, clock)
, device_isa16_card_interface(mconfig, *this)
, m_mpu(*this, "mpu")
, m_fdc(*this, "fdc")
, m_bios(*this, "bios")
{
}
bt542b_device::bt542b_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock)
: bt54x_device(mconfig, BT542B, tag, owner, clock)
{
}
bt542bh_device::bt542bh_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock)
: bt54x_device(mconfig, BT542BH, tag, owner, clock)
{
}
bt545s_device::bt545s_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock)
: bt54x_device(mconfig, BT545S, tag, owner, clock)
{
}
void bt54x_device::device_start()
{
}
u8 bt54x_device::local_status_r()
{
return 0;
}
void bt54x_device::local_map(address_map &map)
{
map(0x00000, 0x01fff).ram();
//map(0x02000, 0x0201f).rw("busintf", FUNC(ncr86c05_device::local_read), FUNC(ncr86c05_device::local_write));
map(0x02080, 0x0208f).m("scsi:7:scsic", FUNC(ncr53cf94_device::map));
map(0x02180, 0x02180).r(FUNC(bt54x_device::local_status_r));
map(0xf8000, 0xfffff).rom().region("mpu", 0);
}
void bt54x_device::asc_config(device_t *device)
{
ncr53c94_device &asc = downcast<ncr53c94_device &>(*device);
asc.set_clock(25_MHz_XTAL); // not verified; perhaps selectable? (40 MHz XTAL also on board)
asc.irq_handler_cb().set(m_mpu, FUNC(i80188_cpu_device::int0_w));
//asc.drq_handler_cb().set("busintf", FUNC(ncr86c05_device::dma_req_w));
}
void bt54x_device::fsc_config(device_t *device)
{
ncr53cf94_device &fsc = downcast<ncr53cf94_device &>(*device);
fsc.set_clock(40_MHz_XTAL);
fsc.irq_handler_cb().set(m_mpu, FUNC(i80188_cpu_device::int0_w)); // mostly polled on BT-545S
//fsc.drq_handler_cb().set("busintf", FUNC(ncr86c05_device::dma_req_w));
}
void bt54x_device::fsc_base(machine_config &config)
{
//ncr86c05_device &busintf(NCR86C05(config, "busintf", 0));
//busintf.mint_callback().set(m_mpu, FUNC(i80188_cpu_device::int1_w));
//busintf.dma_ack_callback().set("scsi:7:scsic", FUNC(ncr53cf94_device::dma_w));
NSCSI_BUS(config, "scsi");
NSCSI_CONNECTOR(config, "scsi:0", default_scsi_devices, nullptr);
NSCSI_CONNECTOR(config, "scsi:1", default_scsi_devices, nullptr);
NSCSI_CONNECTOR(config, "scsi:2", default_scsi_devices, nullptr);
NSCSI_CONNECTOR(config, "scsi:3", default_scsi_devices, nullptr);
NSCSI_CONNECTOR(config, "scsi:4", default_scsi_devices, nullptr);
NSCSI_CONNECTOR(config, "scsi:5", default_scsi_devices, nullptr);
NSCSI_CONNECTOR(config, "scsi:6", default_scsi_devices, nullptr);
NSCSI_CONNECTOR(config, "scsi:7", default_scsi_devices, "scsic", true)
.option_add_internal("scsic", NCR53CF94) // FAS216
.machine_config([this] (device_t *device) { fsc_config(device); });
}
void bt542b_device::device_add_mconfig(machine_config &config)
{
I80188(config, m_mpu, 16_MHz_XTAL);
m_mpu->set_addrmap(AS_PROGRAM, &bt542b_device::local_map);
//ncr86c05_device &busintf(NCR86C05(config, "busintf", 0));
//busintf.mint_callback().set(m_mpu, FUNC(i80188_cpu_device::int1_w));
//busintf.dma_ack_callback().set("scsi:7:scsic", FUNC(ncr53c94_device::dma_w));
NSCSI_BUS(config, "scsi");
NSCSI_CONNECTOR(config, "scsi:0", default_scsi_devices, nullptr);
NSCSI_CONNECTOR(config, "scsi:1", default_scsi_devices, nullptr);
NSCSI_CONNECTOR(config, "scsi:2", default_scsi_devices, nullptr);
NSCSI_CONNECTOR(config, "scsi:3", default_scsi_devices, nullptr);
NSCSI_CONNECTOR(config, "scsi:4", default_scsi_devices, nullptr);
NSCSI_CONNECTOR(config, "scsi:5", default_scsi_devices, nullptr);
NSCSI_CONNECTOR(config, "scsi:6", default_scsi_devices, nullptr);
NSCSI_CONNECTOR(config, "scsi:7", default_scsi_devices, "scsic", true)
.option_add_internal("scsic", NCR53C94)
.machine_config([this] (device_t *device) { asc_config(device); });
DP8473(config, m_fdc, 24_MHz_XTAL);
}
void bt542bh_device::device_add_mconfig(machine_config &config)
{
I80188(config, m_mpu, 40_MHz_XTAL / 2); // clock guessed
m_mpu->set_addrmap(AS_PROGRAM, &bt542bh_device::local_map);
fsc_base(config);
DP8473(config, m_fdc, 24_MHz_XTAL);
}
void bt545s_device::device_add_mconfig(machine_config &config)
{
I80188(config, m_mpu, 40_MHz_XTAL / 2); // SAB80188-1-N; clock guessed
m_mpu->set_addrmap(AS_PROGRAM, &bt545s_device::local_map);
fsc_base(config);
PC8477A(config, m_fdc, 24_MHz_XTAL); // actually PC8477BV
}
ROM_START(bt542b)
ROM_REGION(0x4000, "bios", 0) // "(C) Copyright 1991 BIOS Version 2.41"
ROM_LOAD("1000006-2.41_bustek.u15", 0x0000, 0x4000, CRC(5eb00d0f) SHA1(74a8bbae1c2b42f0c605b0ac98660f1e16ac5c4e))
ROM_REGION(0x8000, "mpu", 0) // "(C) Copyright 1991 BusTek Corporation 542B 91/12/14"
ROM_LOAD("1000005-2.21_bustek.u2", 0x0000, 0x8000, CRC(c2c66653) SHA1(054ba1ea71b2aaab31ab9dd5aca955d861f5333b))
ROM_END
ROM_START(bt542bh)
ROM_REGION(0x8000, "bios", 0) // "(C) Copyright 1992 BIOS Version 4.70M"
ROM_LOAD("5000006-4.70_buslogic.u15", 0x0000, 0x8000, CRC(f5a5e116) SHA1(d7b73015532838dc694edf24308ebbab6f4dd5bb))
ROM_REGION(0x8000, "mpu", 0) // "(C) Copyright 1992 BusLogic Inc. 542BH93/05/23"
ROM_LOAD("5000005-3.35_buslogic.u2", 0x0000, 0x8000, CRC(181966c3) SHA1(b9b327d50cd13f3e5b5b53892b18f233aff065b7))
ROM_END
ROM_START(bt545s)
ROM_REGION(0x4000, "bios", 0) // "(C) Copyright 1992 BIOS Version 4.50"
ROM_LOAD("u15_27128_5002026-4.50.bin", 0x0000, 0x4000, CRC(1bd3247b) SHA1(9d46a99f4b3057e94ef422f387218de2c4553c1a))
ROM_REGION(0x8000, "mpu", 0) // "(C) Copyright 1992 BusLogic Inc. 542BH92/10/05"
ROM_LOAD("u2_27256_5002005-3.31.bin", 0x0000, 0x8000, CRC(20473714) SHA1(797a8dba182049949f7a5c14d8bef4b4e908305b))
ROM_END
const tiny_rom_entry *bt542b_device::device_rom_region() const
{
return ROM_NAME(bt542b);
}
const tiny_rom_entry *bt542bh_device::device_rom_region() const
{
return ROM_NAME(bt542bh);
}
const tiny_rom_entry *bt545s_device::device_rom_region() const
{
return ROM_NAME(bt545s);
}
|
SebastianWeberKamp/KAMP | bundles/Toometa/toometa.requirements/src/requirements/ProcessRequirements.java | <filename>bundles/Toometa/toometa.requirements/src/requirements/ProcessRequirements.java
/**
*/
package requirements;
import de.uka.ipd.sdq.identifier.Identifier;
import org.eclipse.emf.common.util.EList;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Process Requirements</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link requirements.ProcessRequirements#getProcessRrequirements <em>Process Rrequirements</em>}</li>
* </ul>
*
* @see requirements.RequirementsPackage#getProcessRequirements()
* @model
* @generated
*/
public interface ProcessRequirements extends Identifier {
/**
* Returns the value of the '<em><b>Process Rrequirements</b></em>' containment reference list.
* The list contents are of type {@link requirements.ProcessRequirement}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Process Rrequirements</em>' containment reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Process Rrequirements</em>' containment reference list.
* @see requirements.RequirementsPackage#getProcessRequirements_ProcessRrequirements()
* @model containment="true"
* @generated
*/
EList<ProcessRequirement> getProcessRrequirements();
} // ProcessRequirements
|
valencik/bloop | frontend/src/main/scala/bloop/exec/JavaEnv.scala | package bloop.exec
import bloop.io.AbsolutePath
/**
* The configuration of the Java environment for a given project.
*
* @param javaHome Location of the java home. The `java` binary is expected to be found
* in `$javaHome/bin/java`.
* @param javaOptions The options to pass the JVM when starting.
*/
final case class JavaEnv(javaHome: AbsolutePath, javaOptions: Array[String])
object JavaEnv {
/**
* Default `JavaEnv` constructed from this JVM. Uses the same `javaHome`,
* and specifies no arguments.
*/
val default: JavaEnv = {
val javaHome = AbsolutePath(sys.props("java.home"))
val javaOptions = Array.empty[String]
JavaEnv(javaHome, javaOptions)
}
}
|
npocmaka/Windows-Server-2003 | drivers/wdm/audio/legacy/wdmaud.sys/mixer.c | <filename>drivers/wdm/audio/legacy/wdmaud.sys/mixer.c
//---------------------------------------------------------------------------
//
// Module: mixer.c
//
// Description:
// Contains the kernel mode portion of the mixer line driver.
//
//
//@@BEGIN_MSINTERNAL
// Development Team:
// <NAME>
//
// History: Date Author Comment
//
//@@END_MSINTERNAL
//
//---------------------------------------------------------------------------
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE.
//
// Copyright (C) Microsoft Corporation, 1997 - 1999 All Rights Reserved.
//
//---------------------------------------------------------------------------
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
// //
// I N C L U D E S //
// //
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
#include "WDMSYS.H"
typedef struct {
VOID *pNext;
PMXLCONTROL pControl;
#ifdef DEBUG
DWORD dwSig; // CONTROLLINK_SIGNATURE
#endif
} CONTROLLINK, *PCONTROLLINK;
//
// Data structure for Notification list.
//
typedef struct {
PVOID pNext; // Pointer to next node in linked list.
DWORD NodeId; // This is the control's Id as seen by SysAudio
DWORD LineID; // Line that this control lives on
DWORD ControlID; // ControlID from pControl->Control.dwControlID
DWORD ControlType; //
// context specific stuff...
PWDMACONTEXT pContext; // Pointer to Global Context structure
PMIXERDEVICE pmxd; // The mixer device for this control
// PFILE_OBJECT pfo; // File Object to SysAudio for this Context
PCONTROLLINK pcLink; // points to structure that contains valid
// pControl addresses in this context.
KDPC NodeEventDPC; // For handling the DPCs
KSEVENTDATA NodeEventData;
#ifdef DEBUG
DWORD dwSig; // NOTIFICATION_SIGNATURE
#endif
} NOTENODE, *PNOTENODE;
#ifdef DEBUG
BOOL
IsValidNoteNode(
IN PNOTENODE pnnode
);
BOOL
IsValidControlLink(
IN PCONTROLLINK pcLink
);
/////////////////////////////////////////////////////////////////////////////
//
// IsValidNoteNode
//
// Validates that the pointer is a PNOTENODE type.
//
BOOL
IsValidNoteNode(
IN PNOTENODE pnnode)
{
NTSTATUS Status=STATUS_SUCCESS;
try
{
if(pnnode->dwSig != NOTIFICATION_SIGNATURE)
{
DPF(DL_ERROR|FA_ASSERT,("Invalid pnnode->dwSig(%08X)",pnnode->dwSig) );
Status=STATUS_UNSUCCESSFUL;
}
/*
if(pnnode->pfo == NULL)
{
DPF(DL_ERROR|FA_ASSERT,("Invalid pnnode->pfo(%08X)",pnnode->pfo) );
Status=STATUS_UNSUCCESSFUL;
}
*/
if( !IsValidWdmaContext(pnnode->pContext) )
{
DPF(DL_ERROR|FA_ASSERT,("Invalid pnnode->pContext(%08X)",pnnode->pContext) );
Status=STATUS_UNSUCCESSFUL;
}
if( !IsValidMixerDevice(pnnode->pmxd) )
{
DPF(DL_ERROR|FA_ASSERT,("Invalid pnnode->pmxd(%08X)",pnnode->pmxd) );
Status=STATUS_UNSUCCESSFUL;
}
if( !IsValidControlLink(pnnode->pcLink) )
{
DPF(DL_ERROR|FA_ASSERT,("Invalid pnnode->pcLink(%08X)",pnnode->pcLink) );
Status=STATUS_UNSUCCESSFUL;
}
}
except (EXCEPTION_EXECUTE_HANDLER)
{
Status = GetExceptionCode();
}
if( NT_SUCCESS(Status) )
{
return TRUE;
} else {
return FALSE;
}
}
/////////////////////////////////////////////////////////////////////////////
//
// IsValidControlLink
//
// Validates that the pointer is a PNOTENODE type.
//
BOOL
IsValidControlLink(
IN PCONTROLLINK pcLink)
{
NTSTATUS Status=STATUS_SUCCESS;
try
{
if(pcLink->dwSig != CONTROLLINK_SIGNATURE)
{
DPF(DL_ERROR|FA_ASSERT,("Invalid pcLink->dwSig(%08X)",pcLink->dwSig) );
Status=STATUS_UNSUCCESSFUL;
}
if( !IsValidControl(pcLink->pControl) )
{
Status=STATUS_UNSUCCESSFUL;
}
//
// pcLink->pNext is a pointer to another CONTROLLINK structure. Thus,
// if it's not NULL, the structure that it points to should also be valid.
//
if( pcLink->pNext )
{
PCONTROLLINK pTmp=pcLink->pNext;
if( pTmp->dwSig != CONTROLLINK_SIGNATURE )
{
DPF(DL_ERROR|FA_ASSERT,("Invalid pcLink->pNext->dwSig(%08X)",pTmp->dwSig) );
Status=STATUS_UNSUCCESSFUL;
}
}
}
except (EXCEPTION_EXECUTE_HANDLER)
{
Status = GetExceptionCode();
}
if( NT_SUCCESS(Status) )
{
return TRUE;
} else {
return FALSE;
}
}
#endif
PNOTENODE
kmxlNewNoteNode(
);
PCONTROLLINK
kmxlNewControlLink(
IN PMXLCONTROL pControl
);
VOID
kmxlFreeControlLink(
IN OUT PCONTROLLINK pcLink
);
VOID
kmxlFreeNoteNode(
IN OUT PNOTENODE pnnode
);
VOID
kmxlAddNoteNodeToList(
IN OUT PNOTENODE pnnode
);
VOID
kmxlRemoveNoteNodeFromList(
IN OUT PNOTENODE pnnode
);
PNOTENODE
kmxlFindControlInNoteList(
IN PMXLCONTROL pControl
);
NTSTATUS
kmxlFindNodeInNoteList(
IN PNOTENODE pnlookupnode
);
PNOTENODE
kmxlFindIdInContextInNoteList(
IN PWDMACONTEXT pWdmaContext,
IN PMIXERDEVICE pmxd,
IN DWORD Id
);
PNOTENODE
kmxlFindContextInNoteList(
IN PWDMACONTEXT pWdmaContext
);
NTSTATUS
kmxlAddControlToNoteList(
IN OUT PNOTENODE pnnode,
IN PMXLCONTROL pControl
);
PCONTROLLINK
kmxlRemoveControlFromNoteList(
IN OUT PNOTENODE pnnode,
IN PMXLCONTROL pControl
);
NTSTATUS
kmxlQueryControlChange(
IN PFILE_OBJECT pfo,
IN ULONG NodeId
);
NTSTATUS
kmxlEnableControlChange(
IN PFILE_OBJECT pfo,
IN ULONG NodeId,
IN OUT PKSEVENTDATA pksed
);
NTSTATUS
kmxlDisableControlChange(
IN PFILE_OBJECT pfo,
IN ULONG NodeId,
IN OUT PKSEVENTDATA pksed
);
NTSTATUS
kmxlEnableControlChangeNotifications(
IN PMIXEROBJECT pmxobj,
IN PMXLLINE pLine,
IN PMXLCONTROL pControl
);
VOID
kmxlRemoveContextFromNoteList(
IN PWDMACONTEXT pWdmaContext
);
NTSTATUS
kmxlEnableAllControls(
IN PMIXEROBJECT pmxobj
);
//
// Used in persist
//
extern NTSTATUS
kmxlPersistSingleControl(
IN PFILE_OBJECT pfo,
IN PMIXERDEVICE pmxd,
IN PMXLCONTROL pControl,
IN PVOID paDetails
);
VOID
PersistHWControlWorker(
IN LPVOID pData
);
VOID
kmxlGrabNoteMutex(
);
VOID
kmxlReleaseNoteMutex(
);
VOID
kmxlCloseMixerDevice(
IN OUT PMIXERDEVICE pmxd
);
#pragma LOCKED_CODE
#pragma LOCKED_DATA
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
// //
// F U N C T I O N S //
// //
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
//
// This is the head of the notification list. mtxNotification is used to
// handle the list manipulcation. The allocated memory in the firstnotenode
// list will be touched at DPC level.
//
PNOTENODE firstnotenode=NULL;
extern KMUTEX mtxNote;
#ifdef DEBUG
LONG totalnotificationcount=0;
#endif
#define CALLBACKARRAYSIZE 128
typedef struct {
DWORD dwControlID;
DWORD dwLineID;
DWORD dwCallbackType;
} CBINFO, *PCBINFO;
ULONG emptyindex=0;
volatile ULONG loadindex=0;
CBINFO callbacks[CALLBACKARRAYSIZE]={0};
KSPIN_LOCK HardwareCallbackSpinLock;
LIST_ENTRY HardwareCallbackListHead;
PKEVENT pHardwareCallbackEvent=NULL;
PKSWORKER HardwareCallbackWorkerObject=NULL;
WORK_QUEUE_ITEM HardwareCallbackWorkItem;
ULONG HardwareCallbackScheduled=0;
typedef struct tagHWLink {
LIST_ENTRY Next;
PNOTENODE pnnode;
#ifdef DEBUG
DWORD dwSig;
#endif
} HWLINK, *PHWLINK;
/////////////////////////////////////////////////////////////////////////////
//
// NodeEventDPCHandler
//
// This routine is called at DISPATCH_LEVEL, thus you can not touch anything
// but pnnode ellements. pnnode is fixed in memory thus it is safe.
//
VOID NodeEventDPCHandler(
IN PKDPC Dpc,
IN PVOID DeferredContext,
IN PVOID SystemArgument1,
IN PVOID SystemArgument2
)
{
PHWLINK phwlink=NULL;
PNOTENODE pnnode=(PNOTENODE)DeferredContext;
PCBINFO pcbinfo;
//
// WorkItem: Use proper synchronization so that we never go away if there is
// a work item scheduled!
//
DPFASSERT( pnnode->dwSig == NOTIFICATION_SIGNATURE );
DPF(DL_TRACE|FA_HARDWAREEVENT, ("** ++ Event Signaled ++ **") );
DPF(DL_TRACE|FA_HARDWAREEVENT, ("NodeId = %d LineID = %X ControlID = %X ControlType = %X",
pnnode->NodeId,pnnode->LineID,
pnnode->ControlID,pnnode->ControlType) );
callbacks[loadindex%CALLBACKARRAYSIZE].dwControlID=pnnode->ControlID;
callbacks[loadindex%CALLBACKARRAYSIZE].dwLineID=pnnode->LineID;
callbacks[loadindex%CALLBACKARRAYSIZE].dwCallbackType=MIXER_CONTROL_CALLBACK;
//
// Now we want to setup a work item to persist the hardware event. The idea
// is that we'll put all the events in a list and then remove them from the list
// in the handler. If we already have a workitem outstanding to service the
// list, we don't schedule another.
if( HardwareCallbackWorkerObject )
{
//
// Always allocate an entry in our list to service this DPC. We'll free this
// event in the worker routine.
//
if( NT_SUCCESS(AudioAllocateMemory_Fixed(sizeof(HWLINK),
TAG_AuDF_HARDWAREEVENT,
ZERO_FILL_MEMORY,
&phwlink) ) )
{
phwlink->pnnode=pnnode;
#ifdef DEBUG
phwlink->dwSig=HWLINK_SIGNATURE;
#endif
ExInterlockedInsertTailList(&HardwareCallbackListHead,
&phwlink->Next,
&HardwareCallbackSpinLock);
//
// Now, if we haven't scheduled a work item yet, do so to service this
// info in the list. HardwareCallbackSchedule will be 0 at
// initialization time. This variable will be set to 0 in the
// work item handler. If we increment and it's any other value other
// then 1, we've already scheduled a work item.
//
if( InterlockedIncrement(&HardwareCallbackScheduled) == 1 )
{
KsQueueWorkItem(HardwareCallbackWorkerObject, &HardwareCallbackWorkItem);
}
}
}
// Now if the control was a mute, then send line change as well.
if (pnnode->ControlType==MIXERCONTROL_CONTROLTYPE_MUTE) {
callbacks[loadindex%CALLBACKARRAYSIZE].dwCallbackType|=MIXER_LINE_CALLBACK;
}
loadindex++;
if (pHardwareCallbackEvent!=NULL) {
KeSetEvent(pHardwareCallbackEvent, 0 , FALSE);
}
}
#pragma PAGEABLE_CODE
#pragma PAGEABLE_DATA
/////////////////////////////////////////////////////////////////////////////
//
// kmxlNewNoteNode
//
// This routine allocates another Notification node. Note that AudioAllocateMemory zeros
// all successful memory allocations.
//
// The return value is a pointer to a Notification Node or NULL.
//
PNOTENODE
kmxlNewNoteNode(
)
{
PNOTENODE pnnode = NULL;
NTSTATUS Status;
PAGED_CODE();
Status = AudioAllocateMemory_Fixed(sizeof( NOTENODE ),
TAG_AuDN_NOTIFICATION,
ZERO_FILL_MEMORY,
&pnnode );
if( !NT_SUCCESS( Status ) ) {
return( NULL );
}
DPF(DL_MAX|FA_NOTE, ("New notification node allocated %08X",pnnode) );
#ifdef DEBUG
pnnode->dwSig=NOTIFICATION_SIGNATURE;
#endif
return pnnode;
}
/////////////////////////////////////////////////////////////////////////////
//
// kmxlNewControlLink
//
// This routine allocates another CONTROLLINK node. Note that AudioAllocateMemory zeros
// all successful memory allocations.
//
// The return value is a pointer to a Notification Node or NULL.
//
PCONTROLLINK
kmxlNewControlLink(
IN PMXLCONTROL pControl
)
{
PCONTROLLINK pcLink = NULL;
NTSTATUS Status;
PAGED_CODE();
Status = AudioAllocateMemory_Fixed(sizeof( CONTROLLINK ),
TAG_AuDL_LINK,
ZERO_FILL_MEMORY,
&pcLink );
if( !NT_SUCCESS( Status ) ) {
return( NULL );
}
DPF(DL_MAX|FA_NOTE, ("New controllink node allocated %08X",pcLink) );
#ifdef DEBUG
pcLink->dwSig=CONTROLLINK_SIGNATURE;
#endif
//
// Setup the pcontrol first and then link it in.
//
pcLink->pControl=pControl;
return pcLink;
}
VOID
kmxlFreeControlLink(
IN OUT PCONTROLLINK pcLink
)
{
DPFASSERT(IsValidControlLink(pcLink));
PAGED_CODE();
#ifdef DEBUG
pcLink->dwSig=(DWORD)0xDEADBEEF;
#endif
AudioFreeMemory(sizeof( CONTROLLINK ),&pcLink);
}
/////////////////////////////////////////////////////////////////////////////
//
// kmxlFreeNoteNode
//
// This routine frees a Notification Node.
//
VOID
kmxlFreeNoteNode(
IN OUT PNOTENODE pnnode
)
{
PCONTROLLINK pcLink,pcTmp;
PAGED_CODE();
DPFASSERT( pnnode->dwSig == NOTIFICATION_SIGNATURE );
DPFASSERT( pnnode->pNext == NULL );
DPFASSERT( pnnode->pcLink == NULL );
DPF(DL_MAX|FA_NOTE,("NotificationNode freed %08X",pnnode) );
AudioFreeMemory( sizeof( NOTENODE ),&pnnode );
}
/////////////////////////////////////////////////////////////////////////////
//
// kmxlAddNoteNodeToList
//
// This routine adds the NotificationNode to the list. It places the node
// at the head of the list.
//
VOID
kmxlAddNoteNodeToList(
IN OUT PNOTENODE pnnode
)
{
PAGED_CODE();
pnnode->pNext=firstnotenode;
firstnotenode=pnnode;
#ifdef DEBUG
totalnotificationcount++;
#endif
DPF(DL_TRACE|FA_INSTANCE,("New NoteNode head %08X, Total=%d",pnnode,totalnotificationcount) );
}
/////////////////////////////////////////////////////////////////////////////
//
// kmxlRemoveNoteNodeFromList
//
// This routine removes a node from the list.
//
VOID
kmxlRemoveNoteNodeFromList(
IN OUT PNOTENODE pnnode
)
{
PNOTENODE pTmp;
PAGED_CODE();
DPFASSERT(pnnode->dwSig == NOTIFICATION_SIGNATURE);
// are we the head of the list? If so, move the next to the head.
if( pnnode == firstnotenode )
{
firstnotenode=firstnotenode->pNext;
DPF(DL_MAX|FA_NOTE,("removed notenode head") );
} else {
// we are somewhere in the list we need to walk the list until we find
// our node and clip it out.
for (pTmp=firstnotenode;pTmp!=NULL;pTmp=pTmp->pNext)
{
DPFASSERT(pTmp->dwSig==NOTIFICATION_SIGNATURE);
// Did we find our node in the next position? If so, we
// need to clip it out. Thus, pTmp.next needs to point to
// (our node)'s next.
if(pTmp->pNext == pnnode)
{
pTmp->pNext = pnnode->pNext;
DPF(DL_MAX|FA_NOTE,("removed middle") );
break;
}
}
}
#ifdef DEBUG
totalnotificationcount--;
#endif
//
// to indicate that this node has been removed, pNext gets set to NULL!
//
pnnode->pNext=NULL;
}
/////////////////////////////////////////////////////////////////////////////
//
// kmxlFindControlInNoteList
//
// This routine walks the linked list looking for this control. Because all controls
// are globally allocated, all pControl addresses will be unique. Thus, all
// we really need to do is find the control. If an exact match is found,
// pnnode is returned.
//
PNOTENODE
kmxlFindControlInNoteList(
IN PMXLCONTROL pControl )
{
PNOTENODE pnnode;
PCONTROLLINK pcLink;
PAGED_CODE();
for (pnnode=firstnotenode;pnnode!=NULL;pnnode=pnnode->pNext)
{
//
// Can't check entire structure because pmxd may have been cleaned out.
//
DPFASSERT(pnnode->dwSig == NOTIFICATION_SIGNATURE);
for(pcLink=pnnode->pcLink;pcLink!=NULL;pcLink=pcLink->pNext)
{
DPFASSERT(IsValidControlLink(pcLink));
if( pcLink->pControl == pControl )
{
//
// We found this control in the list!
//
return pnnode;
}
}
}
return NULL;
}
/////////////////////////////////////////////////////////////////////////////
//
// kmxlFindControlTypeInList
//
// This routine walks
//
PMXLCONTROL
kmxlFindControlTypeInList(
IN PNOTENODE pnnode,
IN DWORD dwControlType )
{
PCONTROLLINK pcLink;
PAGED_CODE();
for(pcLink=pnnode->pcLink;pcLink!=NULL;pcLink=pcLink->pNext)
{
DPFASSERT(IsValidControlLink(pcLink));
if( pcLink->pControl->Control.dwControlType == dwControlType )
{
//
// We found this control in the list! Types match.
//
DPF(DL_TRACE|FA_NOTE,("Found Correct pControl %08X",pcLink->pControl) );
return pcLink->pControl;
}
}
return NULL;
}
#ifdef DEBUG
/////////////////////////////////////////////////////////////////////////////
//
// kmxlFindAddressInNoteList
//
// This routine walks the linked list looking for this control within this
// context. If an exact match is found, pnnode is returned.
//
VOID
kmxlFindAddressInNoteList(
IN PMXLCONTROL pControl
)
{
PNOTENODE pnnode;
PCONTROLLINK pcLink;
PAGED_CODE();
for (pnnode=firstnotenode;pnnode!=NULL;pnnode=pnnode->pNext)
{
DPFASSERT(pnnode->dwSig == NOTIFICATION_SIGNATURE);
//
// Let's look to see if this address is one of our pControls!
//
for(pcLink=pnnode->pcLink;pcLink!=NULL;pcLink=pcLink->pNext)
{
DPFASSERT(pcLink->dwSig == CONTROLLINK_SIGNATURE);
if( pcLink->pControl == pControl )
{
//
// We found this control in the list - in the right context!
//
DPF(DL_ERROR|FA_NOTE,("Found pControl(%08X) in our list!",pControl) );
return ;
}
}
}
return ;
}
#endif
/////////////////////////////////////////////////////////////////////////////
//
// kmxlFindNodeInNoteList
//
// Walks the node list looking for this node. This must be called within the
// mtxMutex.
//
NTSTATUS
kmxlFindNodeInNoteList(
IN PNOTENODE pnlookupnode )
{
PNOTENODE pnnode;
PAGED_CODE();
for (pnnode=firstnotenode;pnnode!=NULL;pnnode=pnnode->pNext)
{
if( pnnode == pnlookupnode )
{
//
// Only if we find what we're looking for do we actually verify
// that it's still good.
//
DPFASSERT(IsValidNoteNode(pnnode));
//
// we found this control in the list
//
return STATUS_SUCCESS;
}
}
return STATUS_UNSUCCESSFUL;
}
/////////////////////////////////////////////////////////////////////////////
//
// kmxlFindIdInContextInNoteList
//
// Walks the notification list looking for the node that contains this id in
// this context.
//
PNOTENODE
kmxlFindIdInContextInNoteList(
IN PWDMACONTEXT pWdmaContext,
IN PMIXERDEVICE pmxd,
IN DWORD NodeId
)
{
PNOTENODE pnTmp;
PAGED_CODE();
for (pnTmp=firstnotenode;pnTmp!=NULL;pnTmp=pnTmp->pNext)
{
DPFASSERT(IsValidNoteNode(pnTmp));
if(( pnTmp->NodeId == NodeId ) &&
( pnTmp->pmxd == pmxd ) &&
( pnTmp->pContext == pWdmaContext ) )
{
//
// we found this control in the list in this context.
//
return pnTmp;
}
}
//
// We have walked the list. There is no control with this ID in this Context.
//
return NULL;
}
/////////////////////////////////////////////////////////////////////////////
//
// kmxlFindContextInNoteList
//
PNOTENODE
kmxlFindContextInNoteList(
IN PWDMACONTEXT pWdmaContext
)
{
PNOTENODE pnTmp;
PAGED_CODE();
for (pnTmp=firstnotenode;pnTmp!=NULL;pnTmp=pnTmp->pNext)
{
DPFASSERT(IsValidNoteNode(pnTmp));
if( pnTmp->pContext == pWdmaContext )
{
//
// Found this context in our list.
//
DPFBTRAP();
return pnTmp;
}
}
//
// We have walked the list. There is no control with this ID in this Context.
//
return NULL;
}
/////////////////////////////////////////////////////////////////////////////
//
// kmxlAddControlToNoteList
//
// Adds this pControl to pcLink list.
//
NTSTATUS
kmxlAddControlToNoteList(
IN OUT PNOTENODE pnnode,
IN PMXLCONTROL pControl
)
{
NTSTATUS Status=STATUS_SUCCESS;
PCONTROLLINK pcLink = NULL;
PAGED_CODE();
#ifdef DEBUG
//
// Let's walk the list and make double sure that this node is not already in
// the list.
//
for(pcLink=pnnode->pcLink;pcLink!=NULL;pcLink=pcLink->pNext)
{
if( pcLink->pControl == pControl )
{
DPF(DL_ERROR|FA_NOTE,("pControl(%08X) already in list!") );
return STATUS_UNSUCCESSFUL;
}
}
#endif
Status = AudioAllocateMemory_Fixed(sizeof( CONTROLLINK ),
TAG_AuDL_LINK,
ZERO_FILL_MEMORY,
&pcLink );
if( !NT_SUCCESS( Status ) ) {
DPF(DL_ERROR|FA_NOTE,("Wasn't able to add control to list! Status=%08X",Status) );
return Status;
}
#ifdef DEBUG
pcLink->dwSig=CONTROLLINK_SIGNATURE;
#endif
pcLink->pControl=pControl;
//
// Make new head.
//
// if( pnnode->pcLink != NULL )
// _asm int 3
pcLink->pNext=pnnode->pcLink;
pnnode->pcLink=pcLink;
DPF(DL_TRACE|FA_NOTE,("Added pControl %d to pnnode(%08X)",pControl->Control.dwControlID,pnnode) );
return Status;
}
PCONTROLLINK
kmxlRemoveControlFromNoteList(
IN OUT PNOTENODE pnnode,
IN PMXLCONTROL pControl
)
{
PCONTROLLINK pcLink,pcTmp;
PAGED_CODE();
//
// Does the first node contain our pControl?
//
DPFASSERT(IsValidControlLink(pnnode->pcLink));
for(pcLink=pnnode->pcLink;pcLink!=NULL;pcLink=pcLink->pNext)
{
if( pcLink->pControl == pControl )
break;
}
if( pcLink == pnnode->pcLink )
{
pnnode->pcLink = pcLink->pNext;
DPF(DL_TRACE|FA_NOTE,("removed head pControlLink") );
} else {
for( pcTmp=pnnode->pcLink;pcTmp!=NULL;pcTmp=pcTmp->pNext)
{
if( pcTmp->pNext == pcLink )
{
pcTmp->pNext = pcLink->pNext;
DPF(DL_TRACE|FA_NOTE,("Removed Middle pControlLink") );
break;
}
}
}
// DPFASSERT(IsValidNoteNode(pnnode));
return pcLink;
}
/////////////////////////////////////////////////////////////////////////////
//
// kmxlQueryControlChange
//
// Query's to see if control change notifications are supported on this
// control.
//
NTSTATUS
kmxlQueryControlChange(
IN PFILE_OBJECT pfo, // Handle of the topology driver instance
IN ULONG NodeId //PMXLCONTROL pControl
)
{
NTSTATUS Status;
KSE_NODE KsNodeEvent;
ULONG BytesReturned;
PAGED_CODE();
// initialize event for basic support query
RtlZeroMemory(&KsNodeEvent,sizeof(KSE_NODE));
KsNodeEvent.Event.Set = KSEVENTSETID_AudioControlChange;
KsNodeEvent.Event.Id = KSEVENT_CONTROL_CHANGE;
KsNodeEvent.Event.Flags = KSEVENT_TYPE_BASICSUPPORT | KSPROPERTY_TYPE_TOPOLOGY;
KsNodeEvent.NodeId = NodeId;
DPF(DL_TRACE|FA_SYSAUDIO,("IOCTL_KS_ENABLE_EVENT") );
Status = KsSynchronousIoControlDevice(
pfo, // The FILE_OBJECT for SysAudio
KernelMode, // Call originates in Kernel mode
IOCTL_KS_ENABLE_EVENT, // KS PROPERTY IOCTL
&KsNodeEvent, // Pointer to the KSNODEPROPERTY struct
sizeof(KSE_NODE), // Number or bytes input
NULL, // Pointer to the buffer to store output
0, // Size of the output buffer
&BytesReturned // Number of bytes returned from the call
);
if (!NT_SUCCESS(Status)) {
DPF( DL_MAX|FA_HARDWAREEVENT, ("NODE #%d: KSEVENT_CONTROL_CHANGE Not Supported Error %08X",NodeId,Status) );
RETURN( Status );
}
DPF(DL_TRACE|FA_HARDWAREEVENT ,("NodeId #%d: KSEVENT_CONTROL_CHANGE Supported",NodeId) );
return Status;
}
/////////////////////////////////////////////////////////////////////////////
//
// kmxlEnableControlChange
//
// Turns on Control chnage notifications on this control.
//
NTSTATUS
kmxlEnableControlChange(
IN PFILE_OBJECT pfo, // Handle of the topology driver instance
IN ULONG NodeId, //PMXLCONTROL pControl,
IN OUT PKSEVENTDATA pksed
)
{
NTSTATUS Status;
KSE_NODE KsNodeEvent;
ULONG BytesReturned;
PAGED_CODE();
// try to add an event
RtlZeroMemory(&KsNodeEvent,sizeof(KSE_NODE));
KsNodeEvent.Event.Set = KSEVENTSETID_AudioControlChange;
KsNodeEvent.Event.Id = KSEVENT_CONTROL_CHANGE;
KsNodeEvent.Event.Flags = KSEVENT_TYPE_ENABLE | KSPROPERTY_TYPE_TOPOLOGY;
KsNodeEvent.NodeId = NodeId;
DPF(DL_TRACE|FA_SYSAUDIO,("IOCTL_KS_ENABLE_EVENT") );
Status = KsSynchronousIoControlDevice(
pfo, // The FILE_OBJECT for SysAudio
KernelMode, // Call originates in Kernel mode
IOCTL_KS_ENABLE_EVENT, // KS PROPERTY IOCTL
&KsNodeEvent, // Pointer to the KSNODEPROPERTY struct
sizeof(KSE_NODE), // Number or bytes input
pksed, // Pointer to the buffer to store output
sizeof(KSEVENTDATA), // Size of the output buffer
&BytesReturned // Number of bytes returned from the call
);
if (!NT_SUCCESS(Status)) {
DPF(DL_WARNING|FA_HARDWAREEVENT ,("KSEVENT_CONTROL_CHANGE Enable FAILED Error %08X",Status) );
RETURN( Status );
}
DPF(DL_TRACE|FA_HARDWAREEVENT ,
("KSEVENT_CONTROL_CHANGE Enabled on NodeId #%d",NodeId) );
return Status;
}
/////////////////////////////////////////////////////////////////////////////
//
// kmxlDisableControlChange
//
// Turns off Control chnage notifications on this control.
//
NTSTATUS
kmxlDisableControlChange(
IN PFILE_OBJECT pfo, // Handle of the topology driver instance
IN ULONG NodeId, //PMXLCONTROL pControl,
IN OUT PKSEVENTDATA pksed
)
{
NTSTATUS Status;
KSE_NODE KsNodeEvent;
ULONG BytesReturned;
PAGED_CODE();
// initialize event for basic support query
RtlZeroMemory(&KsNodeEvent,sizeof(KSE_NODE));
KsNodeEvent.Event.Set = KSEVENTSETID_AudioControlChange;
KsNodeEvent.Event.Id = KSEVENT_CONTROL_CHANGE;
KsNodeEvent.Event.Flags = KSEVENT_TYPE_BASICSUPPORT | KSPROPERTY_TYPE_TOPOLOGY;
KsNodeEvent.NodeId = NodeId;
DPF(DL_TRACE|FA_SYSAUDIO,("IOCTL_KS_DISABLE_EVENT") );
Status = KsSynchronousIoControlDevice(
pfo, // The FILE_OBJECT for SysAudio
KernelMode, // Call originates in Kernel mode
IOCTL_KS_DISABLE_EVENT, // KS PROPERTY IOCTL
pksed, // Pointer to the buffer to store output
sizeof(KSEVENTDATA), // Size of the output buffer
NULL, // Pointer to the KSNODEPROPERTY struct
0, // Number or bytes input
&BytesReturned // Number of bytes returned from the call
);
if (!NT_SUCCESS(Status)) {
DPF(DL_WARNING|FA_HARDWAREEVENT,("KSEVENT_CONTROL_CHANGE Disable FAILED") );
RETURN( Status );
}
DPF(DL_TRACE|FA_HARDWAREEVENT,
("KSEVENT_CONTROL_CHANGE disabled on NodeId #%d",NodeId) );
return Status;
}
VOID
kmxlGrabNoteMutex(
)
{
//
// Turn off the APCDisable flag in the thread structure before going for our
// mutex. This will prevent us from getting suspeneded while holding this
// mutex.
//
KeEnterCriticalRegion();
KeWaitForMutexObject(&mtxNote, Executive, KernelMode, FALSE, NULL);
}
VOID
kmxlReleaseNoteMutex(
)
{
KeReleaseMutex(&mtxNote, FALSE);
KeLeaveCriticalRegion();
}
/////////////////////////////////////////////////////////////////////////////
//
// kmxlEnableControlChangeNotifications
//
// This routine gets called every time a new control is created. At that point
// we're going to query the node to see if it supports change notifications
// and enable them in this context.
//
NTSTATUS
kmxlEnableControlChangeNotifications(
IN PMIXEROBJECT pmxobj,
IN PMXLLINE pLine, // Line that owns control
IN PMXLCONTROL pControl // Control to Enable
)
{
PNOTENODE pnnode;
NTSTATUS Status;
LONG i;
PMIXERDEVICE pmxd;
PWDMACONTEXT pWdmaContext;
kmxlGrabNoteMutex();
DPFASSERT(IsValidMixerObject(pmxobj));
pmxd=pmxobj->pMixerDevice;
DPFASSERT(IsValidMixerDevice(pmxd));
pWdmaContext=pmxd->pWdmaContext;
PAGED_CODE();
//
// Never allow anything in the list if it's not valid!
//
DPFASSERT(IsValidControl(pControl));
//
// The first thing we do is look to see if a control of this ID is enabled in
// this context. If so, we'll get a PNOTENODE structure returned to us that
// contains that ID. All we should have to do is add our new pControl.
//
if( pnnode=kmxlFindIdInContextInNoteList(pWdmaContext,pmxd,pControl->Id) ) // Not pControl->Control.dwControlID
{
//
// yes there is. Add this pControl to this pnnode and we're done.
//
Status=kmxlAddControlToNoteList(pnnode,pControl);
} else {
//
// There is no Control with this ID in this Context. Let's try to
// Add one.
//
//
// This node is not in our list, we need to add it if and only if it
// supports change notifications
//
Status=kmxlQueryControlChange(pmxd->pfo,pControl->Id); //pLocfo
if( NT_SUCCESS(Status) )
{
//
// This control supports notifications, thus add info to our
// global list - if it's not already there...
//
if( (pnnode=kmxlNewNoteNode()) != NULL )
{
if( (pnnode->pcLink=kmxlNewControlLink(pControl)) != NULL )
{
pnnode->NodeId=pControl->Id;
//
// We have a new notification node to fill out.
//
pnnode->ControlID=pControl->Control.dwControlID;
pnnode->ControlType=pControl->Control.dwControlType;
pnnode->LineID=pLine->Line.dwLineID;
pnnode->pContext=pWdmaContext; //NOTENODE
pnnode->pmxd=pmxd;
DPF(DL_TRACE|FA_NOTE ,
("Init pnnode, NodeId=#%d: CtrlID=%X CtrlType=%X Context=%08X",
pnnode->NodeId, //pControl->Id
pnnode->ControlID, //pControl->Control.dwControlID,
pnnode->ControlType,
pnnode->pContext) ); //pControl->Control.dwControlType) );
//
// Now setup the DPC handling
//
KeInitializeDpc(&pnnode->NodeEventDPC,NodeEventDPCHandler,pnnode);
pnnode->NodeEventData.NotificationType=KSEVENTF_DPC;
pnnode->NodeEventData.Dpc.Dpc=&pnnode->NodeEventDPC;
//
// At this point, we've got a little window. We call and enable
// events on this control. From that time until the time we actually
// add it to the list, if an event fires, we will not find this node
// in the list - thus we will not process it.
//
Status=kmxlEnableControlChange(pnnode->pmxd->pfo,
pnnode->NodeId, //pControl,
&pnnode->NodeEventData);
//&NodeEvent[NumEventDPCs].NodeEventData);
if( NT_SUCCESS(Status) )
{
DPF(DL_TRACE|FA_HARDWAREEVENT,("Enabled Control #%d in context(%08X)!",pControl->Id,pWdmaContext) );
//
// Now let's add it to our global list
//
//
kmxlAddNoteNodeToList(pnnode);
DPFASSERT(IsValidNoteNode(pnnode));
} else {
DPF(DL_WARNING|FA_HARDWAREEVENT,("Failed to Enable Control #%d!",pControl->Id) );
DPFBTRAP();
//
// For some reason, this node failed to enable.
//
kmxlFreeControlLink(pnnode->pcLink);
kmxlFreeNoteNode(pnnode);
}
} else {
DPF(DL_ERROR|FA_NOTE,("kmxlNewControlLink failed") );
kmxlFreeNoteNode(pnnode);
}
} else {
DPF(DL_WARNING|FA_NOTE,("kmxlNewNoteNode failed") );
}
} else {
DPF(DL_MAX|FA_HARDWAREEVENT,("This control #%d doesn't support change notifications",pControl->Id) );
}
}
kmxlReleaseNoteMutex();
return Status;
}
/////////////////////////////////////////////////////////////////////////////
//
// kmxlDisableControlChangeNotifications
//
// This routine gets called every time a control is freed. We walk the list
// of enable controls and see if it's there. If so, we disable and clean up.
// if it's not in the list, it didn't support change notifications.
//
NTSTATUS
kmxlDisableControlChangeNotifications(
IN PMXLCONTROL pControl
)
{
NTSTATUS Status=STATUS_SUCCESS;
PNOTENODE pnnode;
PAGED_CODE();
kmxlGrabNoteMutex();
DPFASSERT(IsValidControl(pControl));
//
// Find this control in our list.
//
if(pnnode=kmxlFindControlInNoteList(pControl)) //pWdmaContext,
{
PCONTROLLINK pcLink;
#ifdef DEBUG
if( pControl->Id != pnnode->NodeId )
{
DPF(DL_ERROR|FA_NOTE,("Control NodeId Changed! CtrlId=%08X,pnnodeID=%08X",
pControl->Id,pnnode->NodeId) );
}
#endif
//
// This call removes pControl from this node. note that after this
// control is removed, pnnode->pcLink will be NULL if there are no
// more controls hanging on this Notification node. Thus, we need
// to disable it.
//
pcLink=kmxlRemoveControlFromNoteList(pnnode,pControl);
if( pnnode->pcLink == NULL )
{
//
// During cleanup, the mixer device structure will have already been
// cleaned up. This can be seen because the pmxd->Device entry will
// be UNUSED_DEVICE. Thus, we can't do anything on that mixerdevice.
//
if( ( pnnode->pmxd->Device != UNUSED_DEVICE ) &&
( pnnode->pmxd->pfo != NULL ) )
{
//
// There are no references to this node, we can free it. But, if
// this disable call fails, then the node was already distroyed.
//
Status=kmxlDisableControlChange(pnnode->pmxd->pfo,pnnode->NodeId,&pnnode->NodeEventData);
if( !NT_SUCCESS(Status) )
{
DPF(DL_WARNING|FA_NOTE,("Not able to disable! pnnode %08X",pnnode) );
}
} else {
DPF(DL_WARNING|FA_NOTE,("pmxd is invalid %08X",pnnode->pmxd) );
}
kmxlRemoveNoteNodeFromList(pnnode);
kmxlFreeNoteNode(pnnode);
}
DPF(DL_TRACE|FA_NOTE,("Removed PCONTROLLINK(%08X) for pControl(%08X)",pcLink,pcLink->pControl) );
kmxlFreeControlLink(pcLink);
} else {
//
// We get called on every control free. Thus, many will not be in our list.
//
DPF(DL_MAX|FA_NOTE,("Control=%d not in List!",pControl->Id) );
}
kmxlReleaseNoteMutex();
return Status;
}
/////////////////////////////////////////////////////////////////////////////
//
// kmxlRemoveContextFromNoteList
//
// This routine gets called when this context is going away. Thus, we need to
// remove it from our list.
//
VOID
kmxlRemoveContextFromNoteList(
IN PWDMACONTEXT pContext
)
{
NTSTATUS Status;
PNOTENODE pnnode;
PCONTROLLINK pcLink;
PAGED_CODE();
kmxlGrabNoteMutex();
//
// If we find this context is still alive in our list, someone leaked a control.
// Things should have been cleaned up when the controls went away! But, for
// some reasons they didn't.
//
// There could be multiple pContext nodes in list.
//
while( (pnnode=kmxlFindContextInNoteList(pContext)) != NULL )
{
DPFASSERT(IsValidNoteNode(pnnode));
kmxlRemoveNoteNodeFromList(pnnode);
//
// There can be multiple Controls on this Notification node.
//
while( (pnnode->pcLink != NULL) &&
( (pcLink=kmxlRemoveControlFromNoteList(pnnode,pnnode->pcLink->pControl)) != NULL) )
{
//
// To get here, pcLink is Valid. If it was the last pControl, then
// we want to turn off change notifications on it.
//
if( pnnode->pcLink == NULL )
{
//
// There are no references to this node, we can free it.
//
Status=kmxlDisableControlChange(pnnode->pmxd->pfo,pnnode->NodeId,&pnnode->NodeEventData);
DPFASSERT( Status == STATUS_SUCCESS );
DPFBTRAP();
}
kmxlFreeControlLink(pcLink);
DPFBTRAP();
}
kmxlFreeNoteNode(pnnode);
}
DPF(DL_TRACE|FA_NOTE,("pWdmaContext %08X going away",pContext) );
kmxlReleaseNoteMutex();
}
/////////////////////////////////////////////////////////////////////////////
//
// kmxlCleanupNotelist
//
// Driver is unloading, turn everything off and free the memory!
//
VOID
kmxlCleanupNoteList(
)
{
NTSTATUS Status;
PNOTENODE pnnode,pnnodeFree;
PCONTROLLINK pcLink;
PAGED_CODE();
kmxlGrabNoteMutex();
//
// If we find this context is still alive in our list, someone leaked a control.
// Things should have been cleaned up when the controls went away! But, for
// some reasons they didn't.
//
// There could be multiple pContext nodes in list.
//
pnnode=firstnotenode;
while( pnnode )
{
DPFASSERT(IsValidNoteNode(pnnode));
DPF(DL_ERROR|FA_NOTE,("pnnode(%08X) found in Notification List!",pnnode) );
kmxlRemoveNoteNodeFromList(pnnode);
//
// There can be multiple Controls on this Notification node.
//
while( (pnnode->pcLink != NULL) &&
( (pcLink=kmxlRemoveControlFromNoteList(pnnode,pnnode->pcLink->pControl)) != NULL) )
{
//
// To get here, pcLink is Valid. If it was the last pControl, then
// we want to turn off change notifications on it.
//
if( pnnode->pcLink == NULL )
{
//
// There are no references to this node, we can free it.
//
Status=kmxlDisableControlChange(pnnode->pmxd->pfo,pnnode->NodeId,&pnnode->NodeEventData);
DPFASSERT( Status == STATUS_SUCCESS );
DPFBTRAP();
}
kmxlFreeControlLink(pcLink);
DPFBTRAP();
}
pnnodeFree=pnnode;
pnnode=pnnode->pNext;
kmxlFreeNoteNode(pnnodeFree);
DPFBTRAP();
}
DPF(DL_TRACE|FA_NOTE,("Done with cleanup") );
kmxlReleaseNoteMutex();
}
/////////////////////////////////////////////////////////////////////////////
//
// kmxlPersistHWControlWorker
//
// When kmxlPersistHWControlWorker gets called, the pData value is a pointer
// to a globally allocated NOTENODE structure. Thus, we have all the context
// we need with regard to persisting the control. We just need to make sure
// that our node didn't go away between the time the evern was scheduled and
// when we got called.
//
VOID
kmxlPersistHWControlWorker(
PVOID pReference
)
{
NTSTATUS Status;
PMXLCONTROL pControl;
PVOID paDetails = NULL; // kmxlPersistSingleControl() allocates paDetails
// via kmxlGetCurrentControlValue()
PNOTENODE pnnode;
PHWLINK phwlink;
PLIST_ENTRY ple;
PAGED_CODE();
//
// We set HardwareCallbackSchedule to 0 here so that we can start adding new
// events for handling hardware notifications. Note: we do that here at the
// start of the routine so that there will not be a window where we have
// something in the list that we never get a event scheduled for. In other
// words, this routine handles empty lists.
//
HardwareCallbackScheduled=0;
//
// while we have events in our queue, get one and service it.
//
while((ple = ExInterlockedRemoveHeadList(&HardwareCallbackListHead,
&HardwareCallbackSpinLock)) != NULL)
{
phwlink = CONTAINING_RECORD(ple, HWLINK, Next);
DPFASSERT(phwlink->dwSig == HWLINK_SIGNATURE);
//
// Get our data for this event and then free the link that was allocated in
// the DPC handler.
//
pnnode=phwlink->pnnode;
AudioFreeMemory(sizeof(HWLINK),&phwlink);
//
// We are going to be working in this context for a while. Thus, we're going
// to enter our mtxNote mutex to make sure that our node doesn't go away
// while we're persisting the values!
//
kmxlGrabNoteMutex();
//
// Now our list can't chnage! Is this node still valid? If we don't find
// it in the list, it was removed before this event fired. Thus, there is
// nothing that we can do. --- Free mutex and leave.
//
Status=kmxlFindNodeInNoteList(pnnode);
if( NT_SUCCESS(Status) )
{
DPF( DL_TRACE|FA_HARDWAREEVENT ,
("Entering NodeId %d LineID %X ControlID %d ControlType = %X",
pnnode->NodeId, pnnode->LineID, pnnode->ControlID, pnnode->ControlType) );
//
// Yes. It's still valid. Persist the control.
//
pControl=kmxlFindControlTypeInList(pnnode,pnnode->ControlType);
if( pControl )
{
Status = kmxlPersistSingleControl(
pnnode->pmxd->pfo,
pnnode->pmxd,
pControl, // pControl here...
paDetails
);
}
if( !NT_SUCCESS(Status) )
{
//
// On shutdown, we might get an event that fires after things have
// been cleaned up.
//
if( Status != STATUS_TOO_LATE )
{
DPF(DL_WARNING|FA_NOTE, ("Failure from kmxlPersistSingleControl Status=%X",Status) );
}
}
else {
DPF(DL_TRACE|FA_HARDWAREEVENT ,("Done - success") );
}
} else {
DPF(DL_WARNING|FA_NOTE,("pnnode=%08X has been removed!",pnnode) );
}
//
// Persist this control!
//
kmxlReleaseNoteMutex();
}
DPF(DL_TRACE|FA_HARDWAREEVENT ,("exit") );
}
/////////////////////////////////////////////////////////////////////////////
//
// kmxlGetLineForControl
//
// For every line on this mixer device, look at every control to see if we
// can find this control. If found, return this line pointer.
//
NTSTATUS
kmxlEnableAllControls(
IN PMIXEROBJECT pmxobj
)
{
NTSTATUS Status=STATUS_SUCCESS;
PMIXERDEVICE pmxd;
PMXLLINE pLine;
PMXLCONTROL pControl;
PAGED_CODE();
//
// The first time through we will most likily not have a pfo in the MIXERDEVICE
// structure, thus fill it in!
//
DPFASSERT(pmxobj->dwSig == MIXEROBJECT_SIGNATURE );
DPFASSERT(pmxobj->pMixerDevice != NULL );
DPFASSERT(pmxobj->pMixerDevice->dwSig == MIXERDEVICE_SIGNATURE );
pmxd=pmxobj->pMixerDevice;
if( pmxd->pfo == NULL )
{
DPF(DL_WARNING|FA_NOTE,("fo is NULL, it should have been set!") );
//
// We need to assign a SysAudio FILE_OBJECT to this mixer device so that
// we can talk to it.
//
if( NULL==(pmxd->pfo=kmxlOpenSysAudio())) {
DPF(DL_WARNING|FA_NOTE,("OpenSysAudio failed") );
return STATUS_UNSUCCESSFUL;
}
Status = SetSysAudioProperty(
pmxd->pfo,
KSPROPERTY_SYSAUDIO_DEVICE_INSTANCE,
sizeof( pmxd->Device ),
&pmxd->Device
);
if( !NT_SUCCESS( Status ) ) {
kmxlCloseSysAudio( pmxd->pfo );
pmxd->pfo=NULL;
DPF(DL_WARNING|FA_NOTE,("SetSysAudioProperty failed %X",Status) );
return Status;
}
}
DPFASSERT(IsValidMixerObject(pmxobj));
for(pLine = kmxlFirstInList( pmxd->listLines );
pLine != NULL;
pLine = kmxlNextLine( pLine )
)
{
DPFASSERT(IsValidLine(pLine));
for(pControl = kmxlFirstInList( pLine->Controls );
pControl != NULL;
pControl = kmxlNextControl( pControl )
)
{
DPFASSERT(IsValidControl(pControl));
//
// Enable Notifications if it supports it here.
//
DPF(DL_TRACE|FA_NOTE,("pControl->Id=%d, pControl->Control.dwControlID=%d",
pControl->Id,pControl->Control.dwControlID) );
Status = kmxlEnableControlChangeNotifications(pmxobj,pLine,pControl);
}
}
return Status;
}
VOID
kmxlCloseMixerDevice(
IN OUT PMIXERDEVICE pmxd
)
{
if(pmxd->pfo)
{
kmxlCloseSysAudio( pmxd->pfo );
pmxd->pfo = NULL;
}
}
/////////////////////////////////////////////////////////////////////////////
//
// GetHardwareEventData
//
// Called by user mode driver to get the notification information.
//
VOID GetHardwareEventData(LPDEVICEINFO pDeviceInfo)
{
PAGED_CODE();
if (emptyindex!=loadindex) {
(pDeviceInfo->dwID)[0]=callbacks[emptyindex%CALLBACKARRAYSIZE].dwControlID;
pDeviceInfo->dwLineID=callbacks[emptyindex%CALLBACKARRAYSIZE].dwLineID;
pDeviceInfo->dwCallbackType=callbacks[emptyindex%CALLBACKARRAYSIZE].dwCallbackType;
pDeviceInfo->ControlCallbackCount=1;
emptyindex++;
}
pDeviceInfo->mmr=MMSYSERR_NOERROR;
}
///////////////////////////////////////////////////////////////////////
//
// kmxdInit
//
// Checks to see if the mixer lines have been built for the given
// index. If not, it calls kmxlBuildLines() to build up the lines.
//
// The topology information is kept around so that it can be dumped
// via a debugger command.
//
//
NTSTATUS
kmxlInit(
IN PFILE_OBJECT pfo, // Handle of the topology driver instance
IN PMIXERDEVICE pMixer
)
{
NTSTATUS Status = STATUS_SUCCESS;
HANDLE hKey;
ULONG ResultLength;
PAGED_CODE();
//
// Check to see if the lines have already been built for this device.
// If so, return success.
//
if( pMixer->listLines ) {
RETURN( STATUS_SUCCESS );
}
//
// Build the lines for this device.
//
Status = kmxlBuildLines(
pMixer,
pfo,
&pMixer->listLines,
&pMixer->cDestinations,
&pMixer->Topology
);
if( NT_SUCCESS( Status ) ) {
Status = kmxlOpenInterfaceKey( pfo, pMixer->Device, &hKey );
if( !NT_SUCCESS( Status ) ) {
pMixer->Mapping = MIXER_MAPPING_LOGRITHMIC;
Status = STATUS_SUCCESS;
goto exit;
}
Status = kmxlRegQueryValue( hKey,
L"CurveType",
&pMixer->Mapping,
sizeof( pMixer->Mapping ),
&ResultLength
);
if( !NT_SUCCESS( Status ) ) {
kmxlRegCloseKey( hKey );
pMixer->Mapping = MIXER_MAPPING_LOGRITHMIC;
Status = STATUS_SUCCESS;
goto exit;
}
kmxlRegCloseKey( hKey );
}
exit:
//
// Free up the topology allocated when the lines are built (RETAIL only).
//
#ifndef DEBUG
if(pMixer->Topology.Categories) {
ExFreePool(
( (( PKSMULTIPLE_ITEM )
pMixer->Topology.Categories )) - 1 );
pMixer->Topology.Categories = NULL;
}
if(pMixer->Topology.TopologyNodes) {
ExFreePool(
( (( PKSMULTIPLE_ITEM )
pMixer->Topology.TopologyNodes )) - 1 );
pMixer->Topology.TopologyNodes = NULL;
}
if(pMixer->Topology.TopologyConnections) {
ExFreePool(
( (( PKSMULTIPLE_ITEM )
pMixer->Topology.TopologyConnections )) - 1 );
pMixer->Topology.TopologyConnections = NULL;
}
#endif // !DEBUG
RETURN( Status );
}
////////////////////////////////////////////////////////////////////////
//
// kmxdDeInit
//
// Loops through each of the lines freeing the control structures and
// then the line structures.
//
//
NTSTATUS
kmxlDeInit(
PMIXERDEVICE pMixer
)
{
PMXLLINE pLine = NULL;
PMXLCONTROL pControl = NULL;
PAGED_CODE();
if( pMixer->Device != UNUSED_DEVICE ) {
while( pMixer->listLines ) {
pLine = kmxlRemoveFirstLine( pMixer->listLines );
while( pLine && pLine->Controls ) {
pControl = kmxlRemoveFirstControl( pLine->Controls );
kmxlFreeControl( pControl );
}
AudioFreeMemory( sizeof(MXLLINE),&pLine );
}
//
// Here we need to close sysaudio as used in this mixer device.
//
kmxlCloseMixerDevice(pMixer);
ASSERT( pMixer->listLines == NULL );
//
// Free up the topology (DEBUG only)
//
#ifdef DEBUG
if(pMixer->Topology.Categories) {
ExFreePool(( (( PKSMULTIPLE_ITEM )
pMixer->Topology.Categories )) - 1 );
pMixer->Topology.Categories = NULL;
}
if(pMixer->Topology.TopologyNodes) {
ExFreePool(( (( PKSMULTIPLE_ITEM )
pMixer->Topology.TopologyNodes )) - 1 );
pMixer->Topology.TopologyNodes = NULL;
}
if(pMixer->Topology.TopologyConnections) {
ExFreePool(( (( PKSMULTIPLE_ITEM )
pMixer->Topology.TopologyConnections )) - 1 );
pMixer->Topology.TopologyConnections = NULL;
}
#endif // !DEBUG
} // if
RETURN( STATUS_SUCCESS );
}
///////////////////////////////////////////////////////////////////////
//
// kmxlBuildLines
//
// Builds up the line structures and count of destinations for the
// given instance.
//
//
NTSTATUS
kmxlBuildLines(
IN PMIXERDEVICE pMixer, // The mixer
IN PFILE_OBJECT pfoInstance, // The FILE_OBJECT of a filter instance
IN OUT LINELIST* plistLines, // Pointer to the list of all lines
IN OUT PULONG pcDestinations, // Pointer to the number of dests
IN OUT PKSTOPOLOGY pTopology // Pointer to a topology structure
)
{
NTSTATUS Status = STATUS_SUCCESS;
MIXEROBJECT mxobj;
LINELIST listSourceLines = NULL;
NODELIST listSources = NULL;
NODELIST listDests = NULL;
PMXLNODE pTemp = NULL;
ULONG i;
PAGED_CODE();
ASSERT( pfoInstance );
ASSERT( plistLines );
ASSERT( pcDestinations );
ASSERT( pTopology );
RtlZeroMemory( &mxobj, sizeof( MIXEROBJECT ) );
// Set up the MIXEROBJECT. Note that this structure is used only within
// the scope of this function, so it is okay to simply copy the
// DeviceInterface pointer from the MIXERDEV structure.
mxobj.pfo = pfoInstance;
mxobj.pTopology = pTopology;
mxobj.pMixerDevice = pMixer;
mxobj.DeviceInterface = pMixer->DeviceInterface;
#ifdef DEBUG
mxobj.dwSig = MIXEROBJECT_SIGNATURE;
#endif
//
// Read the topology from the device
//
DPF(DL_TRACE|FA_MIXER,("Querying Topology") );
Status = kmxlQueryTopology( mxobj.pfo, mxobj.pTopology );
if( !NT_SUCCESS( Status ) ) {
goto exit;
}
//
// Build up the node table. The node table is the mixer line's internal
// representation of the topology for easier processing.
//
DPF(DL_TRACE|FA_MIXER,("Building Node Table") );
mxobj.pNodeTable = kmxlBuildNodeTable( mxobj.pTopology );
if( !mxobj.pNodeTable ) {
Status = STATUS_INSUFFICIENT_RESOURCES;
DPF(DL_WARNING|FA_MIXER,("kmxlBuildNodeTable failed") );
goto exit;
}
//
// Parse the topology and build the necessary data structures
// to walk the topology.
//
DPF(DL_TRACE|FA_MIXER,("Parsing Topology") );
Status = kmxlParseTopology(
&mxobj,
&listSources,
&listDests );
if( !NT_SUCCESS( Status ) ) {
DPF(DL_WARNING|FA_MIXER,("kmxlParseTopoloty failed Status=%X",Status) );
goto exit;
}
//
// Build up a list of destination lines.
//
DPF(DL_TRACE|FA_MIXER,("Building Destination lines") );
*plistLines = kmxlBuildDestinationLines(
&mxobj,
listDests
);
if( !(*plistLines) ) {
Status = STATUS_INSUFFICIENT_RESOURCES;
DPF(DL_WARNING|FA_MIXER,("kmxlBuildDestinationLines failed") );
goto exit;
}
//
// Assign the line Ids and the Control Ids for the destinations. Also,
// fill in the number of destinations.
//
kmxlAssignLineAndControlIds( &mxobj, (*plistLines), DESTINATION_LIST );
*pcDestinations = kmxlListLength( (*plistLines) );
//
// Build up a list of source lines
//
DPF(DL_TRACE|FA_MIXER,("Building Source lines") );
listSourceLines = kmxlBuildSourceLines(
&mxobj,
listSources,
listDests
);
if( !listSourceLines ) {
Status = STATUS_INSUFFICIENT_RESOURCES;
DPF(DL_WARNING|FA_MIXER,("kmxlBuildSourceLines failed") );
goto exit;
}
//
// Polish off the lines. First sort them by destination so that
// the source Ids will be assigned correctly.
//
DPF(DL_TRACE|FA_MIXER,("Sort By Destination") );
kmxlSortByDestination( &listSourceLines );
DPF(DL_TRACE|FA_MIXER,("Assign Line and Control Ids") );
kmxlAssignLineAndControlIds( &mxobj, listSourceLines, SOURCE_LIST );
//
// Now assign destinations to sources and construct the line Ids for
// the source lines.
//
DPF(DL_TRACE|FA_MIXER,("Assign Destinations to Sources") );
kmxlAssignDestinationsToSources( listSourceLines, (*plistLines) );
//
// Update the number of sources mapping to each of the destinations.
//
DPF(DL_TRACE|FA_MIXER,("Update Destination Connection Count") );
kmxlUpdateDestintationConnectionCount( listSourceLines, (*plistLines) );
//
// Assign the dwComponentIds for the source and destination lines.
//
DPF(DL_TRACE|FA_MIXER,("Assign Conponent IDs") );
kmxlAssignComponentIds( &mxobj, listSourceLines, (*plistLines) );
//
// Construct a single list of lines. Destinations will be first in
// increasing numerical order by line id, folowed by sources in
// increasing numerical order.
//
kmxlAppendListToEndOfList( (PSLIST*) plistLines, (PSLIST) listSourceLines );
//
// Eliminate any lines that are invalid.
//
DPF(DL_TRACE|FA_MIXER,("Eliminate Invalid Lines") );
kmxlEliminateInvalidLines( plistLines );
//
// Update the mux line IDs to match real line IDs
//
DPF(DL_TRACE|FA_MIXER,("Assign Mux IDs") );
kmxlAssignMuxIds( &mxobj, *plistLines );
//
// Here is where we want to Enable Change Notifications on all controls
// that support notifications.
//
DPF(DL_TRACE|FA_MIXER,("Enable All Controls") );
kmxlEnableAllControls(&mxobj);
exit:
//
// If we got here because of an error, clean up all the mixer lines
//
if( !NT_SUCCESS( Status ) ) {
PMXLLINE pLine;
PMXLCONTROL pControl;
while( (*plistLines) ) {
pLine = kmxlRemoveFirstLine( (*plistLines) );
while( pLine && pLine->Controls ) {
pControl = kmxlRemoveFirstControl( pLine->Controls );
kmxlFreeControl( pControl );
}
AudioFreeMemory( sizeof(MXLLINE),&pLine );
}
}
//
// Free up the mux control list. Note that we don't want to free
// the controls using kmxlFreeControl() because we need the special
// mux instance data to persist.
//
{
PMXLCONTROL pControl;
while( mxobj.listMuxControls ) {
pControl = kmxlRemoveFirstControl( mxobj.listMuxControls );
ASSERT( pControl->pChannelStepping == NULL);
AudioFreeMemory( sizeof(MXLCONTROL),&pControl );
}
}
//
// Free up the source and destination lists. Both types of these lists
// are allocated list nodes and allocated nodes. Both need to be freed.
// The Children and Parent lists, though, are only allocated list nodes.
// The actual nodes are contained in the node table and will be deallocated
// in one chunk in the next block of code.
//
while( listSources ) {
pTemp = kmxlRemoveFirstNode( listSources );
kmxlFreePeerList( pTemp->Children );
AudioFreeMemory( sizeof(MXLNODE),&pTemp );
}
while( listDests ) {
pTemp = kmxlRemoveFirstNode( listDests );
kmxlFreePeerList( pTemp->Parents );
AudioFreeMemory( sizeof(MXLNODE),&pTemp );
}
//
// Free up the peer lists for the children and parents inside the
// nodes of the node table. Finally, deallocate the array of nodes.
//
if( mxobj.pNodeTable ) {
for( i = 0; i < mxobj.pTopology->TopologyNodesCount; i++ ) {
kmxlFreePeerList( mxobj.pNodeTable[ i ].Children );
kmxlFreePeerList( mxobj.pNodeTable[ i ].Parents );
}
AudioFreeMemory_Unknown( &mxobj.pNodeTable );
}
RETURN( Status );
}
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
// //
// M I X E R L I N E F U N C T I O N S //
// //
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
//
// kmxlBuildDestinationLines
//
// Loops through each of the destination nodes, allocates a line
// structure for it, and calls kmxlBuildDestinationControls to
// build the controls for that line.
//
//
LINELIST
kmxlBuildDestinationLines(
IN PMIXEROBJECT pmxobj,
IN NODELIST listDests // The list of destination nodes
)
{
LINELIST listDestLines = NULL;
PMXLNODE pDest = NULL;
PMXLLINE pLine = NULL;
PMXLCONTROL pControl = NULL;
ULONG MaxChannelsForLine;
ASSERT( pmxobj );
ASSERT( listDests );
PAGED_CODE();
//
// Loop over all the destination node allocating a line structure
// for each.
//
pDest = kmxlFirstInList( listDests );
while( pDest ) {
//
// Allocate a new line structure and add it to the list of
// destination lines.
//
pLine = kmxlAllocateLine( TAG_AudL_LINE );
if( !pLine ) {
goto exit;
}
kmxlAddToList( listDestLines, pLine );
//
// Fill in the details of the line structure. Some fields will
// be filled in later.
//
pLine->DestId = pDest->Id;
pLine->Type = pDest->NodeType;
pLine->Communication = pDest->Communication;
pLine->Line.cbStruct = sizeof( MIXERLINE );
pLine->Line.dwSource = (DWORD) -1;
pLine->Line.dwDestination = (DWORD) -1;
kmxlGetPinName( pmxobj->pfo, pDest->Id, pLine );
//
// HACK! The ACTIVE flag should only be set when the line is active
// but then no lines show up in SNDVOL32. It works if the flag is
// always set to ACTIVE for destinations. Also, the number of channels
// should be queried not hard coded. WDM Audio does not provide a
// way to easily query this.
//
pLine->Line.fdwLine = MIXERLINE_LINEF_ACTIVE;
pLine->Line.cChannels = 1; // should this default to 1 or 2?
//
// Build up a list of the controls on this destination
//
if( !NT_SUCCESS( kmxlBuildDestinationControls(
pmxobj,
pDest,
pLine
) ) )
{
DPF(DL_WARNING|FA_MIXER,("kmxlBuildDestinationControls failed") );
goto exit;
}
pDest = kmxlNextNode( pDest );
}
pLine = kmxlFirstInList( listDestLines );
while( pLine ) {
MaxChannelsForLine = 1;
pControl = kmxlFirstInList( pLine->Controls );
while( pControl ) {
ASSERT( IsValidControl( pControl ) );
if ( pControl->NumChannels > MaxChannelsForLine) {
MaxChannelsForLine = pControl->NumChannels;
}
pControl = kmxlNextControl( pControl );
}
if( pLine->Controls == NULL ) {
pLine->Line.cChannels = 1; // should this default to 1 or 2?
} else {
pLine->Line.cChannels = MaxChannelsForLine;
}
pLine = kmxlNextLine( pLine );
}
return( listDestLines );
exit:
//
// A memory allocation failed. Clean up the destination lines and
// return failure.
//
while( listDestLines ) {
pLine = kmxlRemoveFirstLine( listDestLines );
while( pLine && pLine->Controls ) {
pControl = kmxlRemoveFirstControl( pLine->Controls );
kmxlFreeControl( pControl );
}
AudioFreeMemory_Unknown( &pLine );
}
return( NULL );
}
///////////////////////////////////////////////////////////////////////
//
// BuildDestinationControls
//
// Starts at the destination node and translates all the parent nodes
// to mixer line controls. This process stops when the first SUM node
// is encountered, indicating the end of a destination line.
//
//
NTSTATUS
kmxlBuildDestinationControls(
IN PMIXEROBJECT pmxobj,
IN PMXLNODE pDest, // The destination to built controls for
IN PMXLLINE pLine // The line to add the controls to
)
{
PPEERNODE pTemp = NULL;
PMXLCONTROL pControl;
PAGED_CODE();
ASSERT( pmxobj );
ASSERT( pLine );
//
// Start at the immediate parent of the node passed.
//
pTemp = kmxlFirstParentNode( pDest );
while( pTemp ) {
if( IsEqualGUID( &pTemp->pNode->NodeType, &KSNODETYPE_SUM ) ||
( pTemp->pNode->Type == SOURCE ) ||
( pTemp->pNode->Type == DESTINATION ) ) {
//
// We've found a SUM node. Discontinue the loop... we've
// found all the controls.
//
break;
}
if( IsEqualGUID( &pTemp->pNode->NodeType, &KSNODETYPE_MUX ) ) {
if (kmxlTranslateNodeToControl( pmxobj, pTemp->pNode, &pControl )) {
kmxlAppendListToList( (PSLIST*) &pLine->Controls, (PSLIST) pControl );
}
break;
}
if( ( kmxlParentListLength( pTemp->pNode ) > 1 ) ) {
//
// Found a node with multiple parents that is not a SUM node.
// Can't handle that here so add any controls for this node
// and discontinue the loop.
//
if( kmxlTranslateNodeToControl( pmxobj, pTemp->pNode, &pControl ) ) {
kmxlAppendListToList( (PSLIST*) &pLine->Controls, (PSLIST) pControl );
}
break;
}
//
// By going up through the parents and inserting nodes at
// the front of the list, the list will contain the controls
// in the right order.
//
if( kmxlTranslateNodeToControl( pmxobj, pTemp->pNode, &pControl ) ) {
kmxlAppendListToList( (PSLIST*) &pLine->Controls, (PSLIST) pControl );
}
pTemp = kmxlFirstParentNode( pTemp->pNode );
}
DPF(DL_TRACE|FA_MIXER,(
"Found %d controls on destination %d:",
kmxlListLength( pLine->Controls ),
pDest->Id
) );
RETURN( STATUS_SUCCESS );
}
///////////////////////////////////////////////////////////////////////
//
// kmxlBuildSourceLines
//
// Loops through each of the source nodes, allocating a new line
// structure, and calling kmxlBuildPath() to build the controls
// for the line (and possibly creating new lines if there are splits
// in the topology).
//
//
LINELIST
kmxlBuildSourceLines(
IN PMIXEROBJECT pmxobj,
IN NODELIST listSources, // The list of source nodes
IN NODELIST listDests // The list of dest. nodes
)
{
NTSTATUS Status;
LINELIST listSourceLines = NULL;
PMXLNODE pSource = NULL;
PMXLLINE pTemp = NULL;
PMXLCONTROL pControl;
ULONG MaxChannelsForLine;
ASSERT( pmxobj );
ASSERT( pmxobj->pfo );
ASSERT( pmxobj->pNodeTable );
ASSERT( listSources );
ASSERT( listDests );
PAGED_CODE();
pSource = kmxlFirstInList( listSources );
while( pSource ) {
//
// Allocate a new line structure and insert it into the list of
// source lines.
//
pTemp = kmxlAllocateLine( TAG_AudL_LINE );
if( !pTemp ) {
goto exit;
}
kmxlAddToEndOfList( listSourceLines, pTemp );
//
// Fill in the fields of the line structure. Some fields will need
// to be filled in later.
//
pTemp->SourceId = pSource->Id;
pTemp->Type = pSource->NodeType;
pTemp->Communication = pSource->Communication;
pTemp->Line.cbStruct = sizeof( MIXERLINE );
pTemp->Line.dwSource = (DWORD) -1;
pTemp->Line.dwDestination = (DWORD) -1;
pTemp->Line.fdwLine = MIXERLINE_LINEF_SOURCE |
MIXERLINE_LINEF_ACTIVE;
kmxlGetPinName( pmxobj->pfo, pSource->Id, pTemp );
// DPF(DL_TRACE|FA_MIXER,( "Building path for %s (%d).",
// PinCategoryToString( &pSource->NodeType ),
// pSource->Id
// ) );
//
// Build the controls for this line and identify the destination(s)
// it conntects to.
//
Status = kmxlBuildPath(
pmxobj,
pSource, // The source line to build controls for
pSource, // The node to start with
pTemp, // The line structure to add to
&listSourceLines, // The list of all source lines
listDests // THe list of all destinations
);
if( !NT_SUCCESS( Status ) ) {
DPF(DL_WARNING|FA_MIXER,("kmxlBuildPath failed Status=%X",Status) );
goto exit;
}
pSource = kmxlNextNode( pSource );
} // while( pSource )
pTemp = kmxlFirstInList( listSourceLines );
while( pTemp ) {
MaxChannelsForLine = 1;
pControl = kmxlFirstInList( pTemp->Controls );
while( pControl ) {
ASSERT( IsValidControl( pControl ) );
if ( pControl->NumChannels > MaxChannelsForLine) {
MaxChannelsForLine = pControl->NumChannels;
}
pControl = kmxlNextControl( pControl );
}
if( pTemp->Controls == NULL ) {
pTemp->Line.cChannels = 1; // should this default to 1 or 2?
} else {
pTemp->Line.cChannels = MaxChannelsForLine;
}
pTemp = kmxlNextLine( pTemp );
}
return( listSourceLines );
exit:
//
// Something went wrong. Clean up all memory allocated and return NULL
// to indicate the error.
//
while( listSourceLines ) {
pTemp = kmxlRemoveFirstLine( listSourceLines );
while( pTemp && pTemp->Controls ) {
pControl = kmxlRemoveFirstControl( pTemp->Controls );
kmxlFreeControl( pControl );
}
AudioFreeMemory_Unknown( &pTemp );
}
return( NULL );
}
///////////////////////////////////////////////////////////////////////
//
// kmxlBuildPath
//
// Builds the controls for a source line. A source line ends when a
// SUM node, a destination node, a node contained in a destination line
// is encountered. When splits are encountered in the topology, new
// lines need to be created and the controls on those lines enumerated.
//
// kmxlBuildPath will recurse to find the controls on subnodes.
//
//
NTSTATUS
kmxlBuildPath(
IN PMIXEROBJECT pmxobj,
IN PMXLNODE pSource, // The source node for this path
IN PMXLNODE pNode, // The current node in the path
IN PMXLLINE pLine, // The current line
IN OUT LINELIST* plistLines, // The list of lines build so far
IN NODELIST listDests // The list of the destinations
)
{
NTSTATUS Status;
PMXLCONTROL pControl = NULL;
PMXLLINE pNewLine = NULL;
ULONG nControls;
PPEERNODE pChild = NULL;
ASSERT( pmxobj );
ASSERT( pSource );
ASSERT( pNode );
ASSERT( pLine );
ASSERT( plistLines );
PAGED_CODE();
DPF(DL_TRACE|FA_MIXER,( "Building path for %d(0x%x) (%s) NODE=%08x",
pNode->Id,pNode->Id,
NodeTypeToString( &pNode->NodeType ),
pNode ) );
//
// Check to see if this is the end of this line.
//
if( ( IsEqualGUID( &pNode->NodeType, &KSNODETYPE_SUM ) ) ||
( IsEqualGUID( &pNode->NodeType, &KSNODETYPE_MUX ) ) ||
( pNode->Type == DESTINATION ) ||
( kmxlIsDestinationNode( listDests, pNode ) ) )
{
//
// Find the destination node and update the line structure.
// If this IS the destination node, then set the ID in the line
// structure and return. There is no need to check the children,
// since there won't be any.
//
if( pNode->Type == DESTINATION ) {
pLine->DestId = pNode->Id;
RETURN( STATUS_SUCCESS );
}
//
// Find the destination node for the source. It is possible to
// have branches in the topology, so this may recurse.
//
pLine->DestId = kmxlFindDestinationForNode(
pmxobj,
pNode,
pNode,
pLine,
plistLines
);
RETURN( STATUS_SUCCESS );
}
//
// Retrieve and translate the node for the first child, appending any
// controls created onto the list of controls for this line.
//
pChild = kmxlFirstChildNode( pNode );
if( pChild == NULL ) {
RETURN( STATUS_SUCCESS );
}
//
// Save the number of controls here. If a split occurs beneath this
// node, we don't want to include children followed on the first
// child's path.
//
nControls = kmxlListLength( pLine->Controls );
if (kmxlTranslateNodeToControl(pmxobj, pChild->pNode, &pControl) ) {
if( pControl && IsEqualGUID( pControl->NodeType, &KSNODETYPE_MUX ) ) {
if( kmxlIsDestinationNode( listDests, pChild->pNode ) ) {
pControl->Parameters.bPlaceholder = TRUE;
}
}
kmxlAppendListToEndOfList( (PSLIST*) &pLine->Controls, (PSLIST) pControl );
}
//
// Recurse to build the controls for this child.
//
Status = kmxlBuildPath(
pmxobj,
pSource,
pChild->pNode,
pLine,
plistLines,
listDests
);
if( !NT_SUCCESS( Status ) ) {
RETURN( Status );
}
//
// For the rest of the children
//
// Create a new line based on pSource.
// Duplicate the list of controls in pLine.
// Recurse over the child node.
//
pChild = kmxlNextPeerNode( pChild );
while( pChild ) {
pNewLine = kmxlAllocateLine( TAG_AudL_LINE );
if( pNewLine == NULL ) {
RETURN( STATUS_INSUFFICIENT_RESOURCES );
}
//
// Insert this new node into the list of source lines
//
RtlCopyMemory( pNewLine, pLine, sizeof( MXLLINE ) );
pNewLine->List.Next = NULL;
pNewLine->Controls = NULL;
kmxlAddToEndOfList( *plistLines, pNewLine );
//
// Since this is a new line, the control structures also need to be
// duplicated.
//
Status = kmxlDuplicateLineControls( pNewLine, pLine, nControls );
if( !NT_SUCCESS( Status ) ) {
RETURN( Status );
}
//
// Just as for the first child, translate the node, append the
// controls to the list of controls for this list, and recurse
// to build the controls for its children.
//
if (kmxlTranslateNodeToControl(
pmxobj,
pChild->pNode,
&pControl ) ) {
kmxlAppendListToEndOfList( (PSLIST*) &pNewLine->Controls, (PSLIST) pControl );
}
Status = kmxlBuildPath(
pmxobj,
pSource,
pChild->pNode,
pNewLine,
plistLines,
listDests
);
if( !NT_SUCCESS( Status ) ) {
RETURN( Status );
}
pChild = kmxlNextPeerNode( pChild );
} // while( pChild )
RETURN( STATUS_SUCCESS );
}
///////////////////////////////////////////////////////////////////////
//
// kmxlIsDestinationNode
//
// Searches all the list of controls on the given list of destinations
// to see if the node appears in any of those lists.
//
//
BOOL
kmxlIsDestinationNode(
IN NODELIST listDests, // The list of destinations
IN PMXLNODE pNode // The node to check
)
{
PMXLNODE pTemp;
PPEERNODE pParent;
PAGED_CODE();
if( pNode->Type == SOURCE ) {
return( FALSE );
}
if( pNode->Type == DESTINATION ) {
return( TRUE );
}
ASSERT(pNode->Type == NODE);
//
// Loop over each of the destinations
//
pTemp = kmxlFirstInList( listDests );
while( pTemp ) {
//
// Loop over the parent.
//
pParent = kmxlFirstParentNode( pTemp );
while( pParent ) {
if( ( pParent->pNode->Type == NODE ) &&
( pParent->pNode->Id == pNode->Id) ) {
return( TRUE );
}
if( ( IsEqualGUID( &pParent->pNode->NodeType, &KSNODETYPE_SUM ) ) ||
( IsEqualGUID( &pParent->pNode->NodeType, &KSNODETYPE_MUX ) ) ||
( pParent->pNode->Type == SOURCE ) )
{
break;
}
//
// Check for the node Ids matching.
//
pParent = kmxlFirstParentNode( pParent->pNode );
}
pTemp = kmxlNextNode( pTemp );
}
return( FALSE );
}
///////////////////////////////////////////////////////////////////////
//
// kmxlDuplicateLine
//
// Duplicates a line and the associated controls.
//
//
NTSTATUS
kmxlDuplicateLine(
IN PMXLLINE* ppTargetLine, // Pointer to the new line
IN PMXLLINE pSourceLine // The line to duplicate
)
{
PAGED_CODE();
ASSERT( ppTargetLine );
ASSERT( pSourceLine );
DPF(DL_TRACE|FA_MIXER,( "Duplicated line with source=%d.",
pSourceLine->SourceId ) );
//
// Allocate a new line structure and copy the information from the
// source line.
//
*ppTargetLine = kmxlAllocateLine( TAG_AudL_LINE );
if( *ppTargetLine == NULL ) {
RETURN( STATUS_INSUFFICIENT_RESOURCES );
}
ASSERT( *ppTargetLine );
// DPF(DL_TRACE|FA_MIXER,( "Duplicated %s (%d).",
// PinCategoryToString( &pSourceLine->Type ),
// pSourceLine->SourceId
// ) );
RtlCopyMemory( *ppTargetLine, pSourceLine, sizeof( MXLLINE ) );
//
// Null out the controls and next pointer. This line does not have
// either of its own yet.
//
(*ppTargetLine)->List.Next = NULL;
(*ppTargetLine)->Controls = NULL;
//
// Duplicate all the controls for the source line.
//
return( kmxlDuplicateLineControls(
*ppTargetLine,
pSourceLine,
kmxlListLength( pSourceLine->Controls )
)
);
}
///////////////////////////////////////////////////////////////////////
//
// kmxlDuplicateLineControls
//
// Duplicates the controls for a line by allocating a new control
// structure for each and copying the information to the new node.
//
//
NTSTATUS
kmxlDuplicateLineControls(
IN PMXLLINE pTargetLine, // The line to put the controls into
IN PMXLLINE pSourceLine, // The line with the controls to dup
IN ULONG nCount // The number of controls to dup
)
{
PMXLCONTROL pControl,
pNewControl;
NTSTATUS Status;
PAGED_CODE();
ASSERT( pTargetLine->Controls == NULL );
if( nCount == 0 ) {
RETURN( STATUS_SUCCESS );
}
//
// Iterate over the list allocating and copying the controls
//
pControl = kmxlFirstInList( pSourceLine->Controls );
while( pControl ) {
ASSERT( IsValidControl( pControl ) );
//
// Allocate a new control structure.
//
pNewControl = kmxlAllocateControl( TAG_AudC_CONTROL );
if( pNewControl == NULL ) {
goto exit;
}
//
// Copy the entire MXLCONTROL structure and NULL out the
// List.Next field. This control will be part of a different
// list.
//
RtlCopyMemory( pNewControl, pControl, sizeof( MXLCONTROL ) );
pNewControl->List.Next = NULL;
pNewControl->pChannelStepping = NULL;
//
// Copy the channel steppings from the original control
//
ASSERT(pControl->NumChannels > 0);
Status = AudioAllocateMemory_Paged(pNewControl->NumChannels * sizeof( CHANNEL_STEPPING ),
TAG_AuDD_CHANNEL,
DEFAULT_MEMORY,
&pNewControl->pChannelStepping );
if( !NT_SUCCESS( Status ) ) {
pNewControl->NumChannels = 0;
goto exit;
}
RtlCopyMemory( pNewControl->pChannelStepping,
pControl->pChannelStepping,
pNewControl->NumChannels * sizeof( CHANNEL_STEPPING ) );
//
// We just made a copy of a MUX node. Mark the datastructures
// is has as a copy so it doesn't get freed from underneath
// somebody else.
//
if( IsEqualGUID( pNewControl->NodeType, &KSNODETYPE_MUX ) ) {
pNewControl->Parameters.bHasCopy = TRUE;
}
kmxlAddToList( pTargetLine->Controls, pNewControl );
//
// Decrement and check the number of controls copied. If we copied
// the requested number, stop.
//
--nCount;
if( nCount == 0 ) {
break;
}
pControl = kmxlNextControl( pControl );
}
RETURN( STATUS_SUCCESS );
exit:
//
// Failed to allocate the control structure. Free up all the
// controls already allocated and return an error.
//
while( pTargetLine->Controls ) {
pControl = kmxlRemoveFirstControl( pTargetLine->Controls );
kmxlFreeControl( pControl );
}
RETURN( STATUS_INSUFFICIENT_RESOURCES );
}
///////////////////////////////////////////////////////////////////////
//
// kmxlFindDestinationForNode
//
// Finds a destination for the given node, duplicating lines if splits
// are found in the topology.
//
//
ULONG
kmxlFindDestinationForNode(
IN PMIXEROBJECT pmxobj,
IN PMXLNODE pNode, // The node to find dest for
IN PMXLNODE pParent, // The original parent
IN PMXLLINE pLine, // The current line it's on
IN OUT LINELIST* plistLines // The list of all lines
)
{
PPEERNODE pChild, pPeerChild;
PMXLLINE pNewLine;
PMXLNODE pShadow = pNode;
PAGED_CODE();
DPF(DL_TRACE|FA_MIXER,( "Finding destination for node %d(0x%x) (%s), parent %d(0x%x) (%s).",
pNode->Id,pNode->Id,
NodeTypeToString( &pNode->NodeType ),
pParent->Id,pParent->Id,
NodeTypeToString( &pNode->NodeType ) ) );
ASSERT( pmxobj ) ;
ASSERT( pNode );
ASSERT( pParent );
ASSERT( pLine );
ASSERT( plistLines );
if( pNode->Type == DESTINATION ) {
return( pNode->Id );
}
//
// Loop over the first children.
//
pChild = kmxlFirstChildNode( pNode );
while( pChild ) {
DPF(DL_TRACE|FA_MIXER,( "First child is %d(0x%x) (%s) NODE:%08x.",
pChild->pNode->Id,
pChild->pNode->Id,
NodeTypeToString( &pChild->pNode->NodeType ),
pChild->pNode ) );
if( pChild->pNode == pParent ) {
DPF(DL_TRACE|FA_MIXER,( "Child node is same as original parent!" ) );
return( INVALID_ID );
}
//
// Loop over the rest of the children.
//
pPeerChild = kmxlNextPeerNode( pChild );
while( pPeerChild ) {
if( pPeerChild->pNode == pParent ) {
DPF(DL_TRACE|FA_MIXER,( "Child node is same as original parent!" ) );
return( INVALID_ID );
}
DPF(DL_TRACE|FA_MIXER,( "Peer node of %d(0x%x) (%s) is %d(0x%x) (%s).",
pChild->pNode->Id,pChild->pNode->Id,
NodeTypeToString( &pChild->pNode->NodeType ),
pPeerChild->pNode->Id,pPeerChild->pNode->Id,
NodeTypeToString( &pPeerChild->pNode->NodeType ) ) );
//
// This line has more than 1 child. Duplicate this line
// and add it to the list of lines.
//
if( !NT_SUCCESS( kmxlDuplicateLine( &pNewLine, pLine ) ) ) {
DPF(DL_WARNING|FA_MIXER,("kmxlDuplicateLine failed") );
continue;
}
kmxlAddToEndOfList( *plistLines, pNewLine );
if( IsEqualGUID( &pPeerChild->pNode->NodeType, &KSNODETYPE_MUX ) ) {
//
// We've found a MUX after a SUM or another MUX node. Mark
// the current line as invalid and build a new, virtual
// line that feeds into the MUX.
//
pNewLine->DestId = INVALID_ID;
kmxlBuildVirtualMuxLine(
pmxobj,
pShadow,
pPeerChild->pNode,
plistLines
);
} else {
//
// Now to find the destination for this new line. Recurse
// on the node of this child.
//
pNewLine->DestId = kmxlFindDestinationForNode(
pmxobj,
pPeerChild->pNode,
pParent,
pNewLine,
plistLines
);
}
DPF(DL_TRACE|FA_MIXER,( "Found %x as dest for %d(0x%x) (%s).",
pNewLine->DestId, pPeerChild->pNode->Id,pPeerChild->pNode->Id,
NodeTypeToString( &pPeerChild->pNode->NodeType ),
pPeerChild->pNode ) );
pPeerChild = kmxlNextPeerNode( pPeerChild );
}
if( IsEqualGUID( &pChild->pNode->NodeType, &KSNODETYPE_MUX ) ) {
//
// We've found a MUX after a SUM or another MUX node. Mark
// the current line as invalid and build a new, virtual
// line that feeds into the MUX.
//
kmxlBuildVirtualMuxLine(
pmxobj,
pShadow,
pChild->pNode,
plistLines
);
return( INVALID_ID );
}
//
// Found the destination!
//
if( pChild->pNode->Type == DESTINATION ) {
DPF(DL_TRACE|FA_MIXER,( "Found %x as dest for %d.",
pChild->pNode->Id,
pNode->Id ) );
return( pChild->pNode->Id );
}
pShadow = pChild->pNode;
pChild = kmxlFirstChildNode( pChild->pNode );
}
DPF(DL_WARNING|FA_MIXER,("returning INVALID_ID") );
return( INVALID_ID );
}
///////////////////////////////////////////////////////////////////////
//
// kmxlBuildVirtualMuxLine
//
//
NTSTATUS
kmxlBuildVirtualMuxLine(
IN PMIXEROBJECT pmxobj,
IN PMXLNODE pParent,
IN PMXLNODE pMux,
IN OUT LINELIST* plistLines
)
{
PMXLLINE pLine, pTemp;
PMXLNODE pNode;
PMXLCONTROL pControl;
MXLCONTROL Control;
PAGED_CODE();
//
// Allocate a new line to represent the virtual mux input line.
//
pLine = kmxlAllocateLine( TAG_AudL_LINE );
if( pLine == NULL ) {
RETURN( STATUS_INSUFFICIENT_RESOURCES );
}
DPF(DL_TRACE|FA_MIXER,("Virtual line %08x for Parent NODE:%08x",pLine,pParent) );
//
// Translate the mux control so that it will appear in this line.
//
if (kmxlTranslateNodeToControl(
pmxobj,
pMux,
&pControl
) ) {
pControl->Parameters.bPlaceholder = TRUE;
kmxlAppendListToList( (PSLIST*) &pLine->Controls, (PSLIST) pControl );
}
//
// Now start searching up from the parent.
//
pNode = pParent;
while( pNode ) {
//
// Translate the control.
//
if (kmxlTranslateNodeToControl(
pmxobj,
pNode,
&pControl
) ) {
kmxlAppendListToList( (PSLIST*) &pLine->Controls, (PSLIST) pControl );
}
//
// If we found a node with multiple parents, then this will be the
// "pin" for this line.
//
if( ( kmxlParentListLength( pNode ) > 1 ) ||
( pNode->Type == SOURCE ) ||
( IsEqualGUID( &pNode->NodeType, &KSNODETYPE_MUX ) ) ||
( IsEqualGUID( &pNode->NodeType, &KSNODETYPE_SUM ) ) ) {
//
// Check to see if this node has already been used in a virtual
// line.
//
pTemp = kmxlFirstInList( *plistLines );
while( pTemp ) {
if( pTemp->SourceId == ( 0x8000 + pNode->Id ) ) {
while( pLine->Controls ) {
pControl = kmxlRemoveFirstControl( pLine->Controls );
kmxlFreeControl( pControl );
}
AudioFreeMemory_Unknown( &pLine );
RETURN( STATUS_SUCCESS );
}
pTemp = kmxlNextLine( pTemp );
}
//
// Set up the pin. The name will be the name of the node.
//
pLine->SourceId = 0x8000 + pNode->Id;
Control.NodeType = &pNode->NodeType;
kmxlGetNodeName( pmxobj->pfo, pNode->Id, &Control );
RtlCopyMemory(
pLine->Line.szShortName,
Control.Control.szShortName,
min(
sizeof( pLine->Line.szShortName ),
sizeof( Control.Control.szShortName )
)
);
RtlCopyMemory(
pLine->Line.szName,
Control.Control.szName,
min(
sizeof( pLine->Line.szName ),
sizeof( Control.Control.szName )
)
);
break;
}
pNode = (kmxlFirstParentNode( pNode ))->pNode;
}
//
// By making this line type of "SUM" (which technically it is), it
// will guarantee that this line gets a target type of UNDEFINED.
//
pLine->Type = KSNODETYPE_SUM;
pLine->Communication = KSPIN_COMMUNICATION_NONE;
pLine->Line.cbStruct = sizeof( MIXERLINE );
pLine->Line.dwSource = (DWORD) -1;
pLine->Line.dwDestination = (DWORD) -1;
pLine->Line.fdwLine = MIXERLINE_LINEF_SOURCE |
MIXERLINE_LINEF_ACTIVE;
kmxlAddToEndOfList( plistLines, pLine );
pLine->DestId = kmxlFindDestinationForNode(
pmxobj, pMux, pMux, pLine, plistLines
);
RETURN( STATUS_SUCCESS );
}
///////////////////////////////////////////////////////////////////////
//
// kmxlTranslateNodeToControl
//
//
// Translates a NodeType GUID into a mixer line control. The memory
// for the control(s) is allocated and as much information about the
// control is filled in.
//
// NOTES
// This function returns the number of controls added to the ppControl
// array.
//
// Returns the number of controls actually created.
//
//
ULONG
kmxlTranslateNodeToControl(
IN PMIXEROBJECT pmxobj,
IN PMXLNODE pNode, // The node to translate into a control
OUT PMXLCONTROL* ppControl // The control to fill in
)
{
PMXLCONTROL pControl;
NTSTATUS Status = STATUS_SUCCESS;
ASSERT( pmxobj );
ASSERT( pNode );
ASSERT( ppControl );
PAGED_CODE();
//
// Bug fix. The caller might not clear this. This needs to be NULL do
// the caller doesn't think controls were created when the function
// fails.
//
*ppControl = NULL;
//
// If the node is NULL, there's nothing to do.
//
if( pNode == NULL ) {
*ppControl = NULL;
return( 0 );
}
DPF(DL_TRACE|FA_MIXER,( "Translating %d(0x%x) ( %s ) NODE:%08x",
pNode->Id,pNode->Id,
NodeTypeToString( &pNode->NodeType ),
pNode ) );
///////////////////////////////////////////////////////////////////
if( IsEqualGUID( &pNode->NodeType, &KSNODETYPE_AGC ) ) {
///////////////////////////////////////////////////////////////////
//
// AGC is represented by an ONOFF control.
//
// AGC is a UNIFORM (mono) control.
//
///////////////////////////////////////////////////////////////////
//
// Check to see if the node properly supports AGC.
//
Status = kmxlSupportsControl( pmxobj->pfo, pNode->Id, KSPROPERTY_AUDIO_AGC );
if (!NT_SUCCESS(Status)) {
DPF(DL_TRACE|FA_MIXER,( "AGC node fails property!" ) );
goto exit;
}
//
// Allocate the new control structure.
//
*ppControl = kmxlAllocateControl( TAG_AudC_CONTROL );
if( *ppControl == NULL ) {
goto exit;
}
//
// Fill in as much information as possible.
//
(*ppControl)->NodeType = &KSNODETYPE_AGC;
(*ppControl)->Id = pNode->Id;
(*ppControl)->PropertyId = KSPROPERTY_AUDIO_AGC;
(*ppControl)->bScaled = FALSE;
(*ppControl)->Control.cbStruct = sizeof( MIXERCONTROL );
(*ppControl)->Control.dwControlType = MIXERCONTROL_CONTROLTYPE_ONOFF;
(*ppControl)->Control.cMultipleItems = 0;
(*ppControl)->Control.Bounds.dwMinimum = 0;
(*ppControl)->Control.Bounds.dwMaximum = 1;
(*ppControl)->Control.Metrics.cSteps = 0;
Status = kmxlGetControlChannels( pmxobj->pfo, *ppControl );
if (!NT_SUCCESS(Status))
{
kmxlFreeControl( *ppControl );
*ppControl = NULL;
goto exit;
} else {
kmxlGetNodeName( pmxobj->pfo, pNode->Id, (*ppControl));
ASSERT( IsValidControl( *ppControl ) );
}
///////////////////////////////////////////////////////////////////
} else if( IsEqualGUID( &pNode->NodeType, &KSNODETYPE_LOUDNESS ) ) {
///////////////////////////////////////////////////////////////////
//
// LOUNDNESS is represented by an ONOFF-type control.
//
// LOUDNESS is a UNIFORM (mono) control.
//
///////////////////////////////////////////////////////////////////
//
// Check to see if the node properly supports LOUDNESS.
//
Status = kmxlSupportsControl( pmxobj->pfo, pNode->Id, KSPROPERTY_AUDIO_LOUDNESS );
if (!NT_SUCCESS(Status)) {
DPF(DL_TRACE|FA_MIXER,( "Loudness node fails property!" ) );
goto exit;
}
//
// Allocate the new control structure
//
*ppControl = kmxlAllocateControl( TAG_AudC_CONTROL );
if( *ppControl == NULL ) {
goto exit;
}
//
// Fill in as much information as possible.
//
(*ppControl)->NodeType = &KSNODETYPE_LOUDNESS;
(*ppControl)->Id = pNode->Id;
(*ppControl)->PropertyId = KSPROPERTY_AUDIO_LOUDNESS;
(*ppControl)->bScaled = FALSE;
(*ppControl)->Control.cbStruct = sizeof( MIXERCONTROL );
(*ppControl)->Control.dwControlType = MIXERCONTROL_CONTROLTYPE_LOUDNESS;
(*ppControl)->Control.cMultipleItems = 0;
(*ppControl)->Control.Bounds.dwMinimum = 0;
(*ppControl)->Control.Bounds.dwMaximum = 1;
(*ppControl)->Control.Metrics.cSteps = 0;
Status = kmxlGetControlChannels( pmxobj->pfo, *ppControl );
if (!NT_SUCCESS(Status))
{
kmxlFreeControl( *ppControl );
*ppControl = NULL;
goto exit;
} else {
kmxlGetNodeName( pmxobj->pfo, pNode->Id, (*ppControl));
ASSERT( IsValidControl( *ppControl ) );
}
///////////////////////////////////////////////////////////////////
} else if( IsEqualGUID( &pNode->NodeType, &KSNODETYPE_MUTE ) ) {
///////////////////////////////////////////////////////////////////
//
// MUTE is represented by an ONOFF-type control.
//
// MUTE is a UNIFORM (mono) control.
//
///////////////////////////////////////////////////////////////////
//
// Check to see if the node properly supports MUTE.
//
Status = kmxlSupportsControl(
pmxobj->pfo,
pNode->Id,
KSPROPERTY_AUDIO_MUTE );
if (!NT_SUCCESS(Status)) {
DPF(DL_TRACE|FA_MIXER,( "Mute node fails property!" ) );
goto exit;
}
//
// Allocate the new control structure
//
*ppControl = kmxlAllocateControl( TAG_AudC_CONTROL );
if( *ppControl == NULL ) {
goto exit;
}
//
// Fill in as much information as possible.
//
(*ppControl)->NodeType = &KSNODETYPE_MUTE;
(*ppControl)->Id = pNode->Id;
(*ppControl)->PropertyId = KSPROPERTY_AUDIO_MUTE;
(*ppControl)->bScaled = FALSE;
(*ppControl)->Control.cbStruct = sizeof( MIXERCONTROL );
(*ppControl)->Control.dwControlType = MIXERCONTROL_CONTROLTYPE_MUTE;
(*ppControl)->Control.cMultipleItems = 0;
(*ppControl)->Control.Bounds.dwMinimum = 0;
(*ppControl)->Control.Bounds.dwMaximum = 1;
(*ppControl)->Control.Metrics.cSteps = 0;
Status = kmxlGetControlChannels( pmxobj->pfo, *ppControl );
if (!NT_SUCCESS(Status))
{
kmxlFreeControl( *ppControl );
*ppControl = NULL;
goto exit;
} else {
kmxlGetNodeName( pmxobj->pfo, pNode->Id, (*ppControl));
ASSERT( IsValidControl( *ppControl ) );
}
///////////////////////////////////////////////////////////////////
} else if( IsEqualGUID( &pNode->NodeType, &KSNODETYPE_TONE ) ) {
///////////////////////////////////////////////////////////////////
//
// A TONE node can represent up to 3 controls:
// Treble: A fader control
// Bass: A fader control
// Bass Boost: A OnOff control
//
// Both Treble and Bass are UNIFORM (mono) controls.
//
// To determine which control(s) the TONE node represents, a helper
// function is called to query the particular property. If the
// helper function succeeds, a control is created for that property.
//
///////////////////////////////////////////////////////////////////
Status = kmxlSupportsControl( pmxobj->pfo,
pNode->Id,
KSPROPERTY_AUDIO_BASS_BOOST );
if (NT_SUCCESS(Status)) {
//
// Bass boost control is supported. Allocate a new structure.
//
pControl = kmxlAllocateControl( TAG_AudC_CONTROL );
if( pControl == NULL ) {
goto exit;
}
//
// Fill in as much information as possible.
//
pControl->NodeType = &KSNODETYPE_TONE;
pControl->Id = pNode->Id;
pControl->PropertyId = KSPROPERTY_AUDIO_BASS_BOOST;
pControl->bScaled = FALSE;
pControl->Control.cbStruct = sizeof( MIXERCONTROL );
pControl->Control.dwControlType = MIXERCONTROL_CONTROLTYPE_ONOFF;
pControl->Control.cMultipleItems = 0;
pControl->Control.Bounds.dwMinimum = 0;
pControl->Control.Bounds.dwMaximum = 1;
pControl->Control.Metrics.cSteps = 0;
Status = kmxlGetControlChannels( pmxobj->pfo, pControl );
if (!NT_SUCCESS(Status))
{
kmxlFreeControl( pControl );
pControl = NULL;
goto exit;
}
kmxlGetNodeName( pmxobj->pfo, pNode->Id, pControl);
ASSERT( IsValidControl( pControl ) );
//
// Add this new control to the list.
//
kmxlAddToList( *ppControl, pControl );
pControl = kmxlAllocateControl( TAG_AudC_CONTROL );
if( pControl ) {
RtlCopyMemory( pControl, *ppControl, sizeof( MXLCONTROL ) );
//
// Copy the channel steppings from the original control
//
//
// Sense we copied the control above, we might have gotten
// a pChannelStepping pointer in the copy. We'll NULL that out
// for the memory allocation.
//
pControl->pChannelStepping = NULL;
ASSERT(pControl->NumChannels > 0);
Status = AudioAllocateMemory_Paged(pControl->NumChannels * sizeof( CHANNEL_STEPPING ),
TAG_AuDC_CHANNEL,
DEFAULT_MEMORY,
&pControl->pChannelStepping );
if( !NT_SUCCESS( Status ) ) {
pControl->NumChannels = 0;
kmxlFreeControl( pControl );
pControl = NULL;
goto exit;
}
RtlCopyMemory( pControl->pChannelStepping,
(*ppControl)->pChannelStepping,
pControl->NumChannels * sizeof( CHANNEL_STEPPING ) );
pControl->Control.dwControlType = MIXERCONTROL_CONTROLTYPE_BASS_BOOST;
kmxlAddToList( *ppControl, pControl );
ASSERT( IsValidControl( pControl ) );
}
}
Status = kmxlSupportsBassControl( pmxobj->pfo, pNode->Id );
if (NT_SUCCESS(Status)) {
//
// Bass control is supported. Allocate a new structure.
//
pControl = kmxlAllocateControl( TAG_AudC_CONTROL );
if( pControl == NULL ) {
goto exit;
}
//
// Fill in as much information as possible.
//
pControl->NodeType = &KSNODETYPE_TONE;
pControl->Id = pNode->Id;
pControl->PropertyId = KSPROPERTY_AUDIO_BASS;
pControl->bScaled = TRUE;
pControl->Control.cbStruct = sizeof( MIXERCONTROL );
pControl->Control.dwControlType = MIXERCONTROL_CONTROLTYPE_BASS;
pControl->Control.fdwControl = MIXERCONTROL_CONTROLF_UNIFORM;
pControl->Control.cMultipleItems = 0;
pControl->Control.Bounds.dwMinimum = DEFAULT_STATICBOUNDS_MIN;
pControl->Control.Bounds.dwMaximum = DEFAULT_STATICBOUNDS_MAX;
pControl->Control.Metrics.cSteps = DEFAULT_STATICMETRICS_CSTEPS;
Status = kmxlGetControlRange( pmxobj->pfo, pControl );
if (!NT_SUCCESS(Status))
{
kmxlFreeControl( pControl );
pControl = NULL;
goto exit;
} else {
kmxlGetNodeName( pmxobj->pfo, pNode->Id, pControl);
//
// Add this new control to the list.
//
ASSERT( IsValidControl( pControl ) );
kmxlAddToList( *ppControl, pControl );
}
}
Status = kmxlSupportsTrebleControl( pmxobj->pfo, pNode->Id );
if (NT_SUCCESS(Status)) {
//
// Treble is supported. Allocate a new control structure.
//
pControl = kmxlAllocateControl( TAG_AudC_CONTROL );
if( pControl == NULL ) {
goto exit;
}
//
// Fill in as much information as possible.
//
pControl->NodeType = &KSNODETYPE_TONE;
pControl->Id = pNode->Id;
pControl->PropertyId = KSPROPERTY_AUDIO_TREBLE;
pControl->bScaled = TRUE;
pControl->Control.cbStruct = sizeof( MIXERCONTROL );
pControl->Control.dwControlType = MIXERCONTROL_CONTROLTYPE_TREBLE;
pControl->Control.fdwControl = MIXERCONTROL_CONTROLF_UNIFORM;
pControl->Control.cMultipleItems = 0;
pControl->Control.Bounds.dwMinimum = DEFAULT_STATICBOUNDS_MIN;
pControl->Control.Bounds.dwMaximum = DEFAULT_STATICBOUNDS_MAX;
pControl->Control.Metrics.cSteps = DEFAULT_STATICMETRICS_CSTEPS;
Status = kmxlGetControlRange( pmxobj->pfo, pControl );
if (!NT_SUCCESS(Status))
{
kmxlFreeControl( pControl );
pControl = NULL;
goto exit;
} else {
kmxlGetNodeName( pmxobj->pfo, pNode->Id, pControl);
//
// Add this new control to the list.
//
ASSERT( IsValidControl( pControl ) );
kmxlAddToList( *ppControl, pControl );
}
}
///////////////////////////////////////////////////////////////////
} else if( IsEqualGUID( &pNode->NodeType, &KSNODETYPE_VOLUME ) ) {
///////////////////////////////////////////////////////////////////
//
// A VOLUME is a fader-type control
//
// To determine if a node supports volume changes
//
///////////////////////////////////////////////////////////////////
//
// Check to see if the node properly supports volume
//
Status = kmxlSupportsControl(
pmxobj->pfo,
pNode->Id,
KSPROPERTY_AUDIO_VOLUMELEVEL
);
if (!NT_SUCCESS(Status)) {
DPF(DL_TRACE|FA_MIXER,( "Volume node fails property!" ) );
goto exit;
}
//
// Allocate the new control structure
//
*ppControl = kmxlAllocateControl( TAG_AudC_CONTROL );
if( *ppControl == NULL ) {
goto exit;
}
//
// Fill in as much information as possible.
//
(*ppControl)->NodeType = &KSNODETYPE_VOLUME;
(*ppControl)->Id = pNode->Id;
(*ppControl)->PropertyId = KSPROPERTY_AUDIO_VOLUMELEVEL;
(*ppControl)->bScaled = TRUE;
(*ppControl)->Control.cbStruct = sizeof( MIXERCONTROL );
(*ppControl)->Control.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME;
(*ppControl)->Control.Bounds.dwMinimum = DEFAULT_STATICBOUNDS_MIN;
(*ppControl)->Control.Bounds.dwMaximum = DEFAULT_STATICBOUNDS_MAX;
(*ppControl)->Control.Metrics.cSteps = DEFAULT_STATICMETRICS_CSTEPS;
(*ppControl)->Control.cMultipleItems = 0;
Status = kmxlGetControlRange( pmxobj->pfo, (*ppControl) );
if (!NT_SUCCESS(Status))
{
kmxlFreeControl( *ppControl );
*ppControl = NULL;
goto exit;
}
kmxlGetNodeName( pmxobj->pfo, pNode->Id, (*ppControl));
ASSERT( IsValidControl( *ppControl ) );
///////////////////////////////////////////////////////////////////
} else if( IsEqualGUID( &pNode->NodeType, &KSNODETYPE_PEAKMETER ) ) {
///////////////////////////////////////////////////////////////////
//
// To determine if a node supports peak meter properties
//
///////////////////////////////////////////////////////////////////
//
// Check to see if the node properly supports peakmeter
//
Status = kmxlSupportsControl(
pmxobj->pfo,
pNode->Id,
KSPROPERTY_AUDIO_PEAKMETER
);
if (!NT_SUCCESS(Status)) {
DPF(DL_TRACE|FA_MIXER,( "Peakmeter node fails property!" ) );
goto exit;
}
//
// Allocate the new control structure
//
*ppControl = kmxlAllocateControl( TAG_AudC_CONTROL );
if( *ppControl == NULL ) {
goto exit;
}
//
// Fill in as much information as possible.
//
(*ppControl)->NodeType = &KSNODETYPE_PEAKMETER;
(*ppControl)->Id = pNode->Id;
(*ppControl)->PropertyId = KSPROPERTY_AUDIO_PEAKMETER;
(*ppControl)->bScaled = FALSE;
(*ppControl)->Control.cbStruct = sizeof( MIXERCONTROL );
(*ppControl)->Control.dwControlType = MIXERCONTROL_CONTROLTYPE_PEAKMETER;
(*ppControl)->Control.Bounds.dwMinimum = DEFAULT_STATICBOUNDS_MIN;
(*ppControl)->Control.Bounds.dwMaximum = DEFAULT_STATICBOUNDS_MAX;
(*ppControl)->Control.Metrics.cSteps = DEFAULT_STATICMETRICS_CSTEPS;
(*ppControl)->Control.cMultipleItems = 0;
Status = kmxlGetControlRange( pmxobj->pfo, (*ppControl) );
if (!NT_SUCCESS(Status))
{
kmxlFreeControl( *ppControl );
*ppControl = NULL;
goto exit;
}
kmxlGetNodeName( pmxobj->pfo, pNode->Id, (*ppControl));
ASSERT( IsValidControl( *ppControl ) );
///////////////////////////////////////////////////////////////////
} else if( IsEqualGUID( &pNode->NodeType, &KSNODETYPE_MUX ) ) {
///////////////////////////////////////////////////////////////////
//
// A MUX is a single select type control.
//
///////////////////////////////////////////////////////////////////
{
ULONG Line;
//
// Do a quick check and see if the mux responds properly.
// If not, just get out of here quick.
//
if( !NT_SUCCESS( kmxlGetNodeProperty(
pmxobj->pfo,
&KSPROPSETID_Audio,
KSPROPERTY_AUDIO_MUX_SOURCE,
pNode->Id,
0,
NULL,
&Line,
sizeof( Line ) ) ) )
{
goto exit;
}
//
// Look to see if a control has already been generated for this
// node. If so, the control information can be used from it
// instead of creating a new one.
//
pControl = kmxlFirstInList( pmxobj->listMuxControls );
while( pControl ) {
ASSERT( IsValidControl( pControl ) );
if( pControl->Id == pNode->Id ) {
break;
}
pControl = kmxlNextControl( pControl );
}
//
// Allocate the new control structure
//
*ppControl = kmxlAllocateControl( TAG_AudC_CONTROL );
if( *ppControl == NULL ) {
goto exit;
}
if( pControl == NULL ) {
//
// This node has not been seen before. Fill in as much info as
// possible.
//
(*ppControl)->NodeType = &KSNODETYPE_MUX;
(*ppControl)->Id = pNode->Id;
(*ppControl)->PropertyId = KSPROPERTY_AUDIO_MUX_SOURCE;
(*ppControl)->bScaled = FALSE;
(*ppControl)->Control.cbStruct = sizeof( MIXERCONTROL );
(*ppControl)->Control.dwControlType = MIXERCONTROL_CONTROLTYPE_MUX;
(*ppControl)->Control.cMultipleItems = kmxlGetNumMuxLines(
pmxobj->pTopology,
pNode->Id
);
(*ppControl)->Control.fdwControl = MIXERCONTROL_CONTROLF_MULTIPLE |
MIXERCONTROL_CONTROLF_UNIFORM;
(*ppControl)->Control.Bounds.dwMinimum = 0;
(*ppControl)->Control.Bounds.dwMaximum = (*ppControl)->Control.cMultipleItems - 1;
(*ppControl)->Control.Metrics.cSteps = (*ppControl)->Control.cMultipleItems;
kmxlGetNodeName( pmxobj->pfo, pNode->Id, (*ppControl));
kmxlGetMuxLineNames( pmxobj, *ppControl );
pControl = kmxlAllocateControl( TAG_AudC_CONTROL );
if( pControl == NULL ) {
kmxlFreeControl( *ppControl );
*ppControl = NULL;
goto exit;
}
//
// Make a copy of this control for the mux list
//
(*ppControl)->Control.dwControlID = pmxobj->dwControlId++;
RtlCopyMemory( pControl, *ppControl, sizeof( MXLCONTROL ) );
ASSERT( IsValidControl( pControl ) );
pControl->Parameters.bHasCopy = TRUE;
(*ppControl)->Parameters.bHasCopy = FALSE;
kmxlAddToList( pmxobj->listMuxControls, pControl );
} else {
RtlCopyMemory( *ppControl, pControl, sizeof( MXLCONTROL ) );
ASSERT( IsValidControl( *ppControl ) );
(*ppControl)->Parameters.bHasCopy = TRUE;
(*ppControl)->List.Next = NULL;
}
}
#ifdef STEREO_ENHANCE
///////////////////////////////////////////////////////////////////
} else if( IsEqualGUID( &pNode->NodeType, &KSNODETYPE_STEREO_WIDE ) ) {
///////////////////////////////////////////////////////////////////
//
// Stereo Enhance is a boolean control.
//
///////////////////////////////////////////////////////////////////
//
// Check to see if the node properly supports stereo wide
//
Status = kmxlSupportsControl(
pfoInstance,
pNode->Id,
KSPROPERTY_AUDIO_WIDE_MODE
);
if (!NT_SUCCESS(Status)) {
DPF(DL_TRACE|FA_MIXER,( "Stereo Wide node fails property!" ) );
goto exit;
}
//
// Allocate the new control structure
//
*ppControl = kmxlAllocateControl( TAG_AudC_CONTROL );
if( *ppControl == NULL ) {
goto exit;
}
//
// Fill in as much information as possible.
//
(*ppControl)->NodeType = &KSNODETYPE_STEREO_ENHANCE;
(*ppControl)->Id = pNode->Id;
(*ppControl)->PropertyId = KSPROPERTY_AUDIO_WIDE_MODE;
(*ppControl)->bScaled = FALSE;
(*ppControl)->Control.cbStruct = sizeof( MIXERCONTROL );
(*ppControl)->Control.dwControlType = MIXERCONTROL_CONTROLTYPE_STEREOENH;
(*ppControl)->Control.cMultipleItems = 0;
(*ppControl)->Control.Bounds.dwMinimum = 0;
(*ppControl)->Control.Bounds.dwMaximum = 1;
(*ppControl)->Control.Metrics.cSteps = 0;
Status = kmxlGetControlChannels( pfoInstance, *ppControl );
if (!NT_SUCCESS(Status))
{
kmxlFreeControl( *ppControl );
*ppControl = NULL;
goto exit;
}
kmxlGetNodeName( pfoInstance, pNode->Id, (*ppControl));
#endif
///////////////////////////////////////////////////////////////////
} else if( IsEqualGUID( &pNode->NodeType, &KSNODETYPE_STEREO_WIDE ) ) {
///////////////////////////////////////////////////////////////////
//
// Check to see if the node properly supports stereo wide
//
Status = kmxlSupportsControl(
pmxobj->pfo,
pNode->Id,
KSPROPERTY_AUDIO_WIDENESS
);
if (!NT_SUCCESS(Status)) {
DPF(DL_TRACE|FA_MIXER,( "Stereo wide node fails property!" ) );
goto exit;
}
//
// Allocate the new control structure
//
*ppControl = kmxlAllocateControl( TAG_AudC_CONTROL );
if( *ppControl == NULL ) {
goto exit;
}
//
// Fill in as much information as possible.
//
(*ppControl)->NodeType = &KSNODETYPE_STEREO_WIDE;
(*ppControl)->Id = pNode->Id;
(*ppControl)->PropertyId = KSPROPERTY_AUDIO_WIDENESS;
(*ppControl)->bScaled = FALSE;
(*ppControl)->Control.cbStruct = sizeof( MIXERCONTROL );
(*ppControl)->Control.dwControlType = MIXERCONTROL_CONTROLTYPE_FADER;
(*ppControl)->Control.cMultipleItems = 0;
(*ppControl)->Control.Bounds.dwMinimum = DEFAULT_STATICBOUNDS_MIN;
(*ppControl)->Control.Bounds.dwMaximum = DEFAULT_STATICBOUNDS_MAX;
(*ppControl)->Control.Metrics.cSteps = DEFAULT_STATICMETRICS_CSTEPS;
Status = kmxlGetControlRange( pmxobj->pfo, (*ppControl) );
if (!NT_SUCCESS(Status))
{
kmxlFreeControl( *ppControl );
*ppControl = NULL;
goto exit;
}
kmxlGetNodeName( pmxobj->pfo, pNode->Id, (*ppControl));
ASSERT( IsValidControl( *ppControl ) );
///////////////////////////////////////////////////////////////////
} else if( IsEqualGUID( &pNode->NodeType, &KSNODETYPE_CHORUS ) ) {
///////////////////////////////////////////////////////////////////
//
// Check to see if the node properly supports chorus
//
Status = kmxlSupportsControl(
pmxobj->pfo,
pNode->Id,
KSPROPERTY_AUDIO_CHORUS_LEVEL
);
if (!NT_SUCCESS(Status)) {
DPF(DL_TRACE|FA_MIXER,( "Chorus node fails property!" ) );
goto exit;
}
//
// Allocate the new control structure
//
*ppControl = kmxlAllocateControl( TAG_AudC_CONTROL );
if( *ppControl == NULL ) {
goto exit;
}
//
// Fill in as much information as possible.
//
(*ppControl)->NodeType = &KSNODETYPE_CHORUS;
(*ppControl)->Id = pNode->Id;
(*ppControl)->PropertyId = KSPROPERTY_AUDIO_CHORUS_LEVEL;
(*ppControl)->bScaled = FALSE;
(*ppControl)->Control.cbStruct = sizeof( MIXERCONTROL );
(*ppControl)->Control.dwControlType = MIXERCONTROL_CONTROLTYPE_FADER;
(*ppControl)->Control.cMultipleItems = 0;
(*ppControl)->Control.Bounds.dwMinimum = DEFAULT_STATICBOUNDS_MIN;
(*ppControl)->Control.Bounds.dwMaximum = DEFAULT_STATICBOUNDS_MAX;
(*ppControl)->Control.Metrics.cSteps = DEFAULT_STATICMETRICS_CSTEPS;
// (*ppControl)->Control.Metrics.cSteps = 0xFFFF;
Status = kmxlGetControlChannels( pmxobj->pfo, *ppControl ); // Should we also get the range?
if (!NT_SUCCESS(Status))
{
kmxlFreeControl( *ppControl );
*ppControl = NULL;
goto exit;
} else {
kmxlGetNodeName( pmxobj->pfo, pNode->Id, (*ppControl));
ASSERT( IsValidControl( *ppControl ) );
}
///////////////////////////////////////////////////////////////////
} else if( IsEqualGUID( &pNode->NodeType, &KSNODETYPE_REVERB ) ) {
///////////////////////////////////////////////////////////////////
//
// Check to see if the node properly supports reverb
//
Status = kmxlSupportsControl(
pmxobj->pfo,
pNode->Id,
KSPROPERTY_AUDIO_REVERB_LEVEL
);
if (!NT_SUCCESS(Status)) {
DPF(DL_TRACE|FA_MIXER,( "Reverb node fails property!" ) );
goto exit;
}
//
// Allocate the new control structure
//
*ppControl = kmxlAllocateControl( TAG_AudC_CONTROL );
if( *ppControl == NULL ) {
goto exit;
}
//
// Fill in as much information as possible.
//
(*ppControl)->NodeType = &KSNODETYPE_REVERB;
(*ppControl)->Id = pNode->Id;
(*ppControl)->PropertyId = KSPROPERTY_AUDIO_REVERB_LEVEL;
(*ppControl)->bScaled = FALSE;
(*ppControl)->Control.cbStruct = sizeof( MIXERCONTROL );
(*ppControl)->Control.dwControlType = MIXERCONTROL_CONTROLTYPE_FADER;
(*ppControl)->Control.cMultipleItems = 0;
(*ppControl)->Control.Bounds.dwMinimum = DEFAULT_STATICBOUNDS_MIN;
(*ppControl)->Control.Bounds.dwMaximum = DEFAULT_STATICBOUNDS_MAX;
(*ppControl)->Control.Metrics.cSteps = DEFAULT_STATICMETRICS_CSTEPS;
// (*ppControl)->Control.Metrics.cSteps = 0xFFFF;
Status = kmxlGetControlChannels( pmxobj->pfo, *ppControl ); // Should we also get the range?
if (!NT_SUCCESS(Status))
{
kmxlFreeControl( *ppControl );
*ppControl = NULL;
goto exit;
} else {
kmxlGetNodeName( pmxobj->pfo, pNode->Id, (*ppControl));
ASSERT( IsValidControl( *ppControl ) );
}
///////////////////////////////////////////////////////////////////
} else if( IsEqualGUID( &pNode->NodeType, &KSNODETYPE_SUPERMIX ) ) {
///////////////////////////////////////////////////////////////////
//
// SuperMix nodes can be supported as MUTE controls if the MUTE
// property is supported.
//
///////////////////////////////////////////////////////////////////
PKSAUDIO_MIXCAP_TABLE pMixCaps;
PLONG pReferenceCount = NULL;
ULONG i,
Size;
BOOL bMutable;
BOOL bVolume = FALSE;
PKSAUDIO_MIXLEVEL pMixLevels = NULL;
#ifdef SUPERMIX_AS_VOL
ULONG Channels;
#endif
if( !NT_SUCCESS( kmxlGetSuperMixCaps( pmxobj->pfo, pNode->Id, &pMixCaps ) ) ) {
goto exit;
}
Status = AudioAllocateMemory_Paged(sizeof( LONG ),
TAG_AudS_SUPERMIX,
ZERO_FILL_MEMORY,
&pReferenceCount );
if( !NT_SUCCESS( Status ) ) {
AudioFreeMemory_Unknown( &pMixCaps );
*ppControl = NULL;
goto exit;
}
*pReferenceCount=0;
Size = pMixCaps->InputChannels * pMixCaps->OutputChannels;
Status = AudioAllocateMemory_Paged(Size * sizeof( KSAUDIO_MIXLEVEL ),
TAG_Audl_MIXLEVEL,
ZERO_FILL_MEMORY,
&pMixLevels );
if( !NT_SUCCESS( Status ) ) {
AudioFreeMemory_Unknown( &pMixCaps );
AudioFreeMemory( sizeof(LONG),&pReferenceCount );
*ppControl = NULL;
goto exit;
}
Status = kmxlGetNodeProperty(
pmxobj->pfo,
&KSPROPSETID_Audio,
KSPROPERTY_AUDIO_MIX_LEVEL_TABLE,
pNode->Id,
0,
NULL,
pMixLevels,
Size * sizeof( KSAUDIO_MIXLEVEL )
);
if( !NT_SUCCESS( Status ) ) {
AudioFreeMemory_Unknown( &pMixCaps );
AudioFreeMemory( sizeof(LONG),&pReferenceCount );
AudioFreeMemory_Unknown( &pMixLevels );
DPF(DL_WARNING|FA_MIXER,("kmxlGetNodeProperty failed Status=%X",Status) );
*ppControl = NULL;
goto exit;
}
bMutable = TRUE;
for( i = 0; i < Size; i++ ) {
//
// If the channel is mutable, then all is well for this entry.
//
if( pMixCaps->Capabilities[ i ].Mute ) {
continue;
}
//
// The the entry is not mutable but is fully attenuated,
// this will work too.
//
if( ( pMixCaps->Capabilities[ i ].Minimum == LONG_MIN ) &&
( pMixCaps->Capabilities[ i ].Maximum == LONG_MIN ) &&
( pMixCaps->Capabilities[ i ].Reset == LONG_MIN ) )
{
continue;
}
bMutable = FALSE;
break;
}
#ifdef SUPERMIX_AS_VOL
bVolume = TRUE;
Channels = 0;
for( i = 0; i < Size; i += pMixCaps->OutputChannels + 1 ) {
if( ( pMixCaps->Capabilities[ i ].Maximum -
pMixCaps->Capabilities[ i ].Minimum ) > 0 )
{
++Channels;
continue;
}
bVolume = FALSE;
break;
}
#endif
//
// This node cannot be used as a MUTE control.
//
if( !bMutable && !bVolume ) {
AudioFreeMemory_Unknown( &pMixCaps );
AudioFreeMemory( sizeof(LONG),&pReferenceCount );
AudioFreeMemory_Unknown( &pMixLevels );
*ppControl = NULL;
goto exit;
}
if( bMutable ) {
//
// The Supermix is verifiably usable as a MUTE. Fill in all the
// details.
//
pControl = kmxlAllocateControl( TAG_AudC_CONTROL );
if( pControl != NULL ) {
pControl->NodeType = &KSNODETYPE_SUPERMIX;
pControl->Id = pNode->Id;
pControl->PropertyId = KSPROPERTY_AUDIO_MIX_LEVEL_TABLE;
pControl->bScaled = FALSE;
pControl->Control.cbStruct = sizeof( MIXERCONTROL );
pControl->Control.dwControlType = MIXERCONTROL_CONTROLTYPE_MUTE;
pControl->Control.fdwControl = MIXERCONTROL_CONTROLF_UNIFORM;
pControl->Control.cMultipleItems = 0;
pControl->Control.Bounds.dwMinimum = 0;
pControl->Control.Bounds.dwMaximum = 1;
pControl->Control.Metrics.cSteps = 0;
InterlockedIncrement(pReferenceCount);
pControl->Parameters.pReferenceCount = pReferenceCount;
pControl->Parameters.Size = pMixCaps->InputChannels *
pMixCaps->OutputChannels;
pControl->Parameters.pMixCaps = pMixCaps;
pControl->Parameters.pMixLevels = pMixLevels;
Status = AudioAllocateMemory_Paged(sizeof( CHANNEL_STEPPING ),
TAG_AuDE_CHANNEL,
ZERO_FILL_MEMORY,
&pControl->pChannelStepping );
if( !NT_SUCCESS( Status ) ) {
AudioFreeMemory_Unknown( &pMixCaps );
AudioFreeMemory( sizeof(LONG),&pReferenceCount );
AudioFreeMemory_Unknown( &pMixLevels );
*ppControl = NULL;
goto exit;
}
pControl->NumChannels = 1;
pControl->pChannelStepping->MinValue = pMixCaps->Capabilities[ 0 ].Minimum;
pControl->pChannelStepping->MaxValue = pMixCaps->Capabilities[ 0 ].Maximum;
pControl->pChannelStepping->Steps = 32;
kmxlGetNodeName( pmxobj->pfo, pNode->Id, pControl);
kmxlAddToList( *ppControl, pControl );
ASSERT( IsValidControl( pControl ) );
}
}
#ifdef SUPERMIX_AS_VOL
if( bVolume ) {
pControl = kmxlAllocateControl( TAG_AudC_CONTROL );
if( pControl != NULL ) {
pControl->NodeType = &KSNODETYPE_SUPERMIX;
pControl->Id = pNode->Id;
pControl->PropertyId = KSPROPERTY_AUDIO_MIX_LEVEL_TABLE;
pControl->bScaled = TRUE;
pControl->Control.cbStruct = sizeof( MIXERCONTROL );
pControl->Control.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME;
pControl->Control.cMultipleItems = 0;
pControl->Control.Bounds.dwMinimum = DEFAULT_STATICBOUNDS_MIN;
pControl->Control.Bounds.dwMaximum = DEFAULT_STATICBOUNDS_MAX;
pControl->Control.Metrics.cSteps = 32;
InterlockedIncrement(pReferenceCount);
pControl->Parameters.pReferenceCount = pReferenceCount;
pControl->Parameters.Size = pMixCaps->InputChannels *
pMixCaps->OutputChannels;
pControl->Parameters.pMixCaps = pMixCaps;
pControl->Parameters.pMixLevels = pMixLevels;
if( Channels == 1 ) {
pControl->Control.fdwControl = MIXERCONTROL_CONTROLF_UNIFORM;
} else {
pControl->Control.fdwControl = 0;
}
kmxlGetNodeName( pmxobj->pfo, pNode->Id, pControl );
kmxlAddToList( *ppControl, pControl );
ASSERT( IsValidControl( pControl ) );
}
}
#endif // SUPERMIX_AS_VOL
if( *ppControl == NULL ) {
AudioFreeMemory_Unknown( &pMixCaps );
AudioFreeMemory( sizeof(LONG),&pReferenceCount );
AudioFreeMemory_Unknown( &pMixLevels );
}
}
exit:
if( *ppControl ) {
DPF(DL_TRACE|FA_MIXER,( "Translated %d controls.", kmxlListLength( *ppControl ) ) );
return( kmxlListLength( *ppControl ) );
} else {
DPF(DL_TRACE|FA_MIXER,( "Translated no controls." ) );
return( 0 );
}
}
#define KsAudioPropertyToString( Property ) \
Property == KSPROPERTY_AUDIO_VOLUMELEVEL ? "Volume" : \
Property == KSPROPERTY_AUDIO_MUTE ? "Mute" : \
Property == KSPROPERTY_AUDIO_BASS ? "Bass" : \
Property == KSPROPERTY_AUDIO_TREBLE ? "Treble" : \
Property == KSPROPERTY_AUDIO_AGC ? "AGC" : \
Property == KSPROPERTY_AUDIO_LOUDNESS ? "Loudness" : \
Property == KSPROPERTY_AUDIO_PEAKMETER ? "Peakmeter" : \
"Unknown"
///////////////////////////////////////////////////////////////////////
//
// kmxlSupportsControl
//
// Queries for property on control to see if it is actually supported
//
//
NTSTATUS
kmxlSupportsControl(
IN PFILE_OBJECT pfoInstance, // The instance to check for
IN ULONG Node, // The node id to query
IN ULONG Property // The property to check for
)
{
NTSTATUS Status;
LONG Level;
ASSERT( pfoInstance );
PAGED_CODE();
//
// Check to see if the property works on the first channel.
//
Status = kmxlGetAudioNodeProperty(
pfoInstance,
Property,
Node,
0, // Channel 0 - first channel
NULL, 0,
&Level, sizeof( Level )
);
if( !NT_SUCCESS( Status ) ) {
DPF(DL_WARNING|FA_MIXER,( "SupportsControl for (%d,%X) failed on first channel with %x.",
Node, Property, Status ) );
}
RETURN( Status );
}
///////////////////////////////////////////////////////////////////////
//
// kmxlSupportsMultiChannelControl
//
// Queries for property on the second channel of the control to see
// independent levels can be set. It is assumed that the first channel
// already succeeded in kmxlSupportsControl
//
//
NTSTATUS
kmxlSupportsMultiChannelControl(
IN PFILE_OBJECT pfoInstance, // The instance to check for
IN ULONG Node, // The node id to query
IN ULONG Property // The property to check for
)
{
NTSTATUS Status;
LONG Level;
ASSERT( pfoInstance );
PAGED_CODE();
//
// Just check the property on the second channel because we have already checked
// the first channel already.
//
Status = kmxlGetAudioNodeProperty(
pfoInstance,
Property,
Node,
1, // Second channel equals a channel value of 1
NULL, 0,
&Level, sizeof( Level )
);
RETURN( Status );
}
NTSTATUS
kmxlAssignLineAndControlIdsWorker(
IN PMIXEROBJECT pmxobj,
IN LINELIST listLines, // The list to assign ids for
IN ULONG ListType, // LIST_SOURCE or LIST_DESTINATION
IN OUT ULONG *pLineID,
IN GUID *pDestGuid
)
{
NTSTATUS Status = STATUS_SUCCESS;
PMXLLINE pLine = NULL;
PMXLCONTROL pControl = NULL;
ULONG LineID = 0;
ULONG Dest;
PAGED_CODE();
ASSERT ( ListType==SOURCE_LIST || ListType==DESTINATION_LIST );
if (pLineID!=NULL) {
LineID=*pLineID;
}
//
// Loop through each of the line structures
//
pLine = kmxlFirstInList( listLines );
if( pLine == NULL ) {
RETURN( Status );
}
Dest = pLine->DestId;
while( pLine ) {
//
// For destinations, set the dwDestination field and set
// the dwSource field for sources.
//
if( ListType == DESTINATION_LIST ) {
// Check if this line has already been assigned an ID.
// If so, then go to next line in list.
if (pLine->Line.dwDestination!=(DWORD)(-1)) {
pLine = kmxlNextLine( pLine );
continue;
}
// Now if we can only number lines of a particular GUID,
// then make sure this destination line type matches that guid.
if (pDestGuid!=NULL && !IsEqualGUID( pDestGuid, &pLine->Type )) {
pLine = kmxlNextLine( pLine );
continue;
}
//
// Assign the destination Id. Create the line Id by
// using -1 for the source in the highword and the
// destination in the loword.
//
pLine->Line.dwDestination = LineID++;
pLine->Line.dwLineID = MAKELONG(
pLine->Line.dwDestination,
-1
);
if (pLineID!=NULL) {
*pLineID=LineID;
}
} else if( ListType == SOURCE_LIST ) {
pLine->Line.dwSource = LineID++;
} else {
RETURN( STATUS_INVALID_PARAMETER );
}
//
// Set up the number of controls on this line.
//
pLine->Line.cControls = kmxlListLength( pLine->Controls );
//
// Loop through the controls, assigning them a control ID
// that is a pointer to the MXLCONTROL structure for that
// control.
//
pControl = kmxlFirstInList( pLine->Controls );
while( pControl ) {
if( pControl->Control.dwControlType == MIXERCONTROL_CONTROLTYPE_MUX ) {
//
// MUX controls are already numbered by this point. Just skip
// it and go onto the next one.
//
pControl = kmxlNextControl( pControl );
continue;
}
pControl->Control.dwControlID = pmxobj->dwControlId++;
pControl = kmxlNextControl( pControl );
}
pLine = kmxlNextLine( pLine );
if( pLine == NULL ) {
continue;
}
if( ( ListType == SOURCE_LIST ) && ( pLine->DestId != Dest ) ) {
LineID = 0;
Dest = pLine->DestId;
}
}
RETURN( Status );
}
#define GUIDCOUNT 13
///////////////////////////////////////////////////////////////////////
//
// kmxlAssignLineAndControlIds
//
// Loops through the list of lines and assigns ids for those line.
// For destinations, the Id starts a 0 and is incremented each time.
// The line id is a long of -1 and the dest id. For sources, the
// line Ids will need to be specified elsewhere so only dwSource
// field is assigned.
//
// For controls, each control is given an Id of the address to the
// MXLCONTROL structure.
//
//
NTSTATUS
kmxlAssignLineAndControlIds(
IN PMIXEROBJECT pmxobj,
IN LINELIST listLines, // The list to assign ids for
IN ULONG ListType // LIST_SOURCE or LIST_DESTINATION
)
{
PAGED_CODE();
ASSERT ( ListType==SOURCE_LIST || ListType==DESTINATION_LIST );
if (SOURCE_LIST==ListType) {
return( kmxlAssignLineAndControlIdsWorker(pmxobj, listLines, ListType, NULL, NULL) );
}
else if (DESTINATION_LIST==ListType) {
// In order to help sndvol32 do the right thing as far as which
// lines displayed as the default playback and record lines, we
// number lines based on what their destinations are.
// We use guid the pLine->Type field to decide how to number lines.
// Lines are prioritized in the following way: speakers, then
// headphones, then telephones. Non prioritized guids are assigned
// last in whatever order they appear in the list.
ULONG LineID=0;
ULONG i;
GUID prioritizeddestinationguids[GUIDCOUNT]= {
STATIC_KSNODETYPE_ROOM_SPEAKER,
STATIC_KSNODETYPE_DESKTOP_SPEAKER,
STATIC_KSNODETYPE_SPEAKER,
STATIC_KSNODETYPE_COMMUNICATION_SPEAKER,
STATIC_KSNODETYPE_HEAD_MOUNTED_DISPLAY_AUDIO,
STATIC_KSNODETYPE_ANALOG_CONNECTOR,
STATIC_KSNODETYPE_SPDIF_INTERFACE,
STATIC_KSNODETYPE_HEADPHONES,
STATIC_KSNODETYPE_TELEPHONE,
STATIC_KSNODETYPE_PHONE_LINE,
STATIC_KSNODETYPE_DOWN_LINE_PHONE,
STATIC_PINNAME_CAPTURE,
STATIC_KSCATEGORY_AUDIO,
};
// Cycle through the list for each prioritized guid and number
// those lines that match that particular guid.
for (i=0; i<GUIDCOUNT; i++) {
kmxlAssignLineAndControlIdsWorker(pmxobj, listLines, ListType,
&LineID, &prioritizeddestinationguids[i]);
}
// Now, number anything left over with a number that depends solely on
// its random order in the list.
return( kmxlAssignLineAndControlIdsWorker(pmxobj, listLines, ListType, &LineID, NULL) );
}
else {
RETURN( STATUS_INVALID_PARAMETER );
}
}
///////////////////////////////////////////////////////////////////////
//
// kmxlAssignDestinationsToSources
//
// Loops through each source looking for a destination lines that
// have a matching destination id. Source line Ids are assigned
// by putting the source id in the hiword and the dest id in the
// loword.
//
//
NTSTATUS
kmxlAssignDestinationsToSources(
IN LINELIST listSourceLines, // The list of all source lines
IN LINELIST listDestLines // The list of all dest lines
)
{
PMXLLINE pSource = NULL,
pDest = NULL;
PAGED_CODE();
//
// For each source line, loop throught the destinations until a
// line is found matching the Id. The dwDestination field will
// be the zero-index Id of the destination.
//
pSource = kmxlFirstInList( listSourceLines );
while( pSource ) {
pDest = kmxlFirstInList( listDestLines );
while( pDest ) {
if( pSource->DestId == pDest->DestId ) {
//
// Heh, whatchya know?
//
pSource->Line.dwDestination = pDest->Line.dwDestination;
pSource->Line.dwLineID = MAKELONG(
(WORD) pSource->Line.dwDestination,
(WORD) pSource->Line.dwSource
);
break;
}
pDest = kmxlNextLine( pDest );
}
pSource = kmxlNextLine( pSource );
}
RETURN( STATUS_SUCCESS );
}
///////////////////////////////////////////////////////////////////////
//
// kmxlUpdateDestinationConnectionCount
//
// For each of the destinations, loop through each of the sources
// and find those that connect to this destination. That count is
// then stored in the MIXERLINE.cConnections for the line.
//
//
NTSTATUS
kmxlUpdateDestintationConnectionCount(
IN LINELIST listSourceLines, // The list of source lines
IN LINELIST listDestLines // The list of destination lines
)
{
PMXLLINE pDest,
pSource;
ULONG Count;
PAGED_CODE();
//
// Loop through each destination finding all the sources that connect
// to it. The total number of sources connecting to a destination
// is sourced in the cConnections field of the MIXERLINE struct.
//
pDest = kmxlFirstInList( listDestLines );
while( pDest ) {
//
// Initialize the source ID. This will mark this as a valid
// destination.
//
pDest->SourceId = (ULONG) -1;
Count = 0;
//
// Loop through the sources looking for sources that connect to
// the current destination.
//
pSource = kmxlFirstInList( listSourceLines );
while( pSource ) {
//
// Found a match. Increment the count.
//
if( pSource->DestId == pDest->DestId ) {
++Count;
}
pSource = kmxlNextLine( pSource );
}
pDest->Line.cConnections = Count;
pDest = kmxlNextLine( pDest );
}
RETURN( STATUS_SUCCESS );
}
VOID
CleanupLine(
PMXLLINE pLine
)
{
PMXLCONTROL pControl;
while( pLine->Controls ) {
pControl = kmxlRemoveFirstControl( pLine->Controls );
kmxlFreeControl( pControl );
}
AudioFreeMemory( sizeof(MXLLINE),&pLine );
}
///////////////////////////////////////////////////////////////////////
//
// kmxlEliminateInvalidLines
//
// Loops through the lines removing lines that are invalid. Refer
// to the function for IsValidLine() for details on what is an invalid
// line.
//
//
NTSTATUS
kmxlEliminateInvalidLines(
IN LINELIST* listLines // The list of lines
)
{
PMXLLINE pLine, pTemp, pShadow;
PAGED_CODE();
//
// Eliminate all invalid lines at the start of the list.
//
pLine = kmxlFirstInList( *listLines );
while( pLine ) {
//
// Found the first valid line. Break out of this loop.
//
if( Is_Valid_Line( pLine ) ) {
break;
}
//
// This is an invalid line. Remove it from the list, free up
// all its control structures, and free the line structure.
//
pTemp = kmxlRemoveFirstLine( pLine );
CleanupLine(pTemp);
}
//
// Assign listLines to point to the first valid line.
//
*listLines = pLine;
if( pLine == NULL ) {
RETURN( STATUS_SUCCESS );
}
//
// At this point, pLine is a valid line. Keeping a hold on the prev
// line, loop through the lines eliminating the invalid ones.
//
pShadow = pLine;
while( pShadow && kmxlNextLine( pShadow ) ) {
pLine = kmxlNextLine( pShadow );
if( pLine && !Is_Valid_Line( pLine ) ) {
//
// Remove the invalid line from the list
//
pShadow->List.Next = pLine->List.Next;
pLine->List.Next = NULL;
CleanupLine(pLine);
continue;
}
pShadow = kmxlNextLine( pShadow );
}
// All the invalid lines have been eliminated. Now eliminate bad
// duplicates.
pShadow = kmxlFirstInList( *listLines );
while( pShadow ) {
//
// Walk all the lines looking for a match.
//
pLine = kmxlNextLine( pShadow );
pTemp = NULL;
while( pLine ) {
if( ( pShadow->SourceId == pLine->SourceId ) &&
( pShadow->DestId == pLine->DestId ) )
{
DPF(DL_TRACE|FA_MIXER,( "Line %x is equal to line %x!",
pShadow->Line.dwLineID,
pLine->Line.dwLineID
) );
//
// Found a match.
//
if( pTemp == NULL )
{
//
// pShadow is our previous line. Remove this line from the
// list.
//
pShadow->List.Next = pLine->List.Next;
pLine->List.Next = NULL;
CleanupLine(pLine);
//
// Now adjust pLine to the next line and loop
//
pLine = kmxlNextLine( pShadow );
continue;
} else {
//
// pTemp is our previous line. Remove this line from the
// list.
//
pTemp->List.Next = pLine->List.Next;
pLine->List.Next = NULL;
CleanupLine(pLine);
//
// Now adjust pLine to the next line and loop
//
pLine = kmxlNextLine( pTemp );
continue;
}
}
pTemp = pLine; //temp is previous line
pLine = kmxlNextLine( pLine );
}
pShadow = kmxlNextLine( pShadow );
}
RETURN( STATUS_SUCCESS );
}
///////////////////////////////////////////////////////////////////////
//
// kmxlAssignComponentIds
//
// Loops through all the destinations then the sources and determines
// their component type and target types.
//
//
VOID
kmxlAssignComponentIds(
IN PMIXEROBJECT pmxobj,
IN LINELIST listSourceLines,
IN LINELIST listDestLines
)
{
PMXLLINE pLine;
PAGED_CODE();
//
// Loop through the destinations...
//
pLine = kmxlFirstInList( listDestLines );
while( pLine ) {
pLine->Line.dwComponentType = kmxlDetermineDestinationType(
pmxobj,
pLine
);
pLine = kmxlNextLine( pLine );
}
//
// Loop through the sources...
//
pLine = kmxlFirstInList( listSourceLines );
while( pLine ) {
pLine->Line.dwComponentType = kmxlDetermineSourceType(
pmxobj,
pLine
);
pLine = kmxlNextLine( pLine );
}
}
///////////////////////////////////////////////////////////////////////
//
// kmxlUpdateMuxLines
//
// Updates the name, line ID, and componenttype of a line that has
// a mux control on it. The MixerControlDetails array is searched for
// an entry that has a matching source id and replaced with the info
// from this line.
//
//
VOID
kmxlUpdateMuxLines(
IN PMXLLINE pLine,
IN PMXLCONTROL pControl
)
{
ULONG i;
PAGED_CODE();
for( i = 0; i < pControl->Parameters.Count; i++ ) {
if( ( pLine->SourceId == pControl->Parameters.lpmcd_lt[ i ].dwParam1 ) &&
( pControl->Parameters.lpmcd_lt[ i ].dwParam2 == (DWORD) -1 ) )
{
wcscpy(
pControl->Parameters.lpmcd_lt[ i ].szName,
pLine->Line.szName
);
pControl->Parameters.lpmcd_lt[ i ].dwParam1 =
pLine->Line.dwLineID;
pControl->Parameters.lpmcd_lt[ i ].dwParam2 =
pLine->Line.dwComponentType;
}
}
}
///////////////////////////////////////////////////////////////////////
//
// kmxlAssignMuxIds
//
// Updates the source IDs stored in the MixerControlDetails array of
// the muxes and removes the muxes placed in lines as place holders.
//
//
NTSTATUS
kmxlAssignMuxIds(
IN PMIXEROBJECT pmxobj,
IN LINELIST listLines
)
{
PMXLLINE pLine;
PMXLCONTROL pControl;
CONTROLLIST listControls = NULL;
PAGED_CODE();
pLine = kmxlFirstInList( listLines );
while( pLine ) {
//
// Loop through the controls by removing them from the line's
// control list and building a new control list. This new
// control list will have the extra mux controls removed.
//
pControl = kmxlRemoveFirstControl( pLine->Controls );
while( pControl ) {
if( IsEqualGUID( pControl->NodeType, &KSNODETYPE_MUX ) ) {
kmxlUpdateMuxLines( pLine, pControl );
if( pControl->Parameters.bPlaceholder ) {
//
// This mux was here only to mark this line. Free
// up only the control memory and leave the parameters
// memeory alone.
//
ASSERT( pControl->pChannelStepping == NULL);
AudioFreeMemory_Unknown( &pControl );
--pLine->Line.cControls;
} else {
//
// This is a real mux control. Add it back into the
// list.
//
kmxlAddToEndOfList( listControls, pControl );
}
} else {
//
// Wasn't a mux. Put it onto the end of the new control
// list.
kmxlAddToEndOfList( listControls, pControl );
}
//
// Remove the next one!
//
pControl = kmxlRemoveFirstControl( pLine->Controls );
}
//
// Reassign the new control list back into this line.
//
pLine->Controls = listControls;
pLine = kmxlNextLine( pLine );
listControls = NULL;
}
RETURN( STATUS_SUCCESS );
}
///////////////////////////////////////////////////////////////////////
//
// TargetCommon
//
// Fills in the common fields of the target function.
//
//
VOID
TargetCommon(
IN PMIXEROBJECT pmxobj,
IN PMXLLINE pLine,
IN DWORD DeviceType
)
{
PWDMACONTEXT pWdmaContext;
PWAVEDEVICE paWaveOutDevs, paWaveInDevs;
PMIDIDEVICE paMidiOutDevs, paMidiInDevs;
ULONG i;
PAGED_CODE();
pWdmaContext = pmxobj->pMixerDevice->pWdmaContext;
paWaveOutDevs = pWdmaContext->WaveOutDevs;
paWaveInDevs = pWdmaContext->WaveInDevs;
paMidiOutDevs = pWdmaContext->MidiOutDevs;
paMidiInDevs = pWdmaContext->MidiInDevs;
for( i = 0; i < MAXNUMDEVS; i++ ) {
if( DeviceType == WaveOutDevice ) {
if( (paWaveOutDevs[i].Device != UNUSED_DEVICE) &&
!MyWcsicmp(pmxobj->DeviceInterface, paWaveOutDevs[ i ].DeviceInterface) ) {
WAVEOUTCAPS wc;
((PWAVEOUTCAPSA)(PVOID)&wc)->wMid=UNICODE_TAG;
wdmaudGetDevCaps( pWdmaContext, WaveOutDevice, i, (BYTE*) &wc, sizeof( WAVEOUTCAPS ) );
wcsncpy( pLine->Line.Target.szPname, wc.szPname, MAXPNAMELEN );
pLine->Line.Target.wMid = wc.wMid;
pLine->Line.Target.wPid = wc.wPid;
pLine->Line.Target.vDriverVersion = wc.vDriverVersion;
return;
}
}
if( DeviceType == WaveInDevice ) {
if( (paWaveInDevs[i].Device != UNUSED_DEVICE) &&
!MyWcsicmp(pmxobj->DeviceInterface, paWaveInDevs[ i ].DeviceInterface) ) {
WAVEINCAPS wc;
((PWAVEINCAPSA)(PVOID)&wc)->wMid=UNICODE_TAG;
wdmaudGetDevCaps( pWdmaContext, WaveInDevice, i, (BYTE*) &wc, sizeof( WAVEINCAPS ) );
wcsncpy( pLine->Line.Target.szPname, wc.szPname, MAXPNAMELEN );
pLine->Line.Target.wMid = wc.wMid;
pLine->Line.Target.wPid = wc.wPid;
pLine->Line.Target.vDriverVersion = wc.vDriverVersion;
return;
}
}
if( DeviceType == MidiOutDevice ) {
if( (paMidiOutDevs[i].Device != UNUSED_DEVICE) &&
!MyWcsicmp(pmxobj->DeviceInterface, paMidiOutDevs[ i ].DeviceInterface) ) {
MIDIOUTCAPS mc;
((PMIDIOUTCAPSA)(PVOID)&mc)->wMid=UNICODE_TAG;
wdmaudGetDevCaps( pWdmaContext, MidiOutDevice, i, (BYTE*) &mc, sizeof( MIDIOUTCAPS ) );
wcsncpy( pLine->Line.Target.szPname, mc.szPname, MAXPNAMELEN );
pLine->Line.Target.wMid = mc.wMid;
pLine->Line.Target.wPid = mc.wPid;
pLine->Line.Target.vDriverVersion = mc.vDriverVersion;
return;
}
}
if( DeviceType == MidiInDevice ) {
if( (paMidiInDevs[i].Device != UNUSED_DEVICE) &&
!MyWcsicmp(pmxobj->DeviceInterface, paMidiInDevs[ i ].DeviceInterface) ) {
MIDIINCAPS mc;
((PMIDIINCAPSA)(PVOID)&mc)->wMid=UNICODE_TAG;
wdmaudGetDevCaps( pWdmaContext, MidiInDevice, i, (BYTE*) &mc, sizeof( MIDIINCAPS ) );
wcsncpy( pLine->Line.Target.szPname, mc.szPname, MAXPNAMELEN) ;
pLine->Line.Target.wMid = mc.wMid;
pLine->Line.Target.wPid = mc.wPid;
pLine->Line.Target.vDriverVersion = mc.vDriverVersion;
return;
}
}
}
}
///////////////////////////////////////////////////////////////////////
//
// TargetTypeWaveOut
//
// Fills in the fields of aLine's target structure to be a waveout
// target.
//
//
VOID
TargetTypeWaveOut(
IN PMIXEROBJECT pmxobj,
IN PMXLLINE pLine
)
{
PAGED_CODE();
pLine->Line.Target.dwType = MIXERLINE_TARGETTYPE_WAVEOUT;
TargetCommon( pmxobj, pLine, WaveOutDevice );
}
///////////////////////////////////////////////////////////////////////
//
// TargetTypeWaveIn
//
// Fills in the fields of aLine's target structure to be a wavein
// target.
//
//
#define TargetTypeWaveIn( pmxobj, pLine ) \
(pLine)->Line.Target.dwType = MIXERLINE_TARGETTYPE_WAVEIN; \
(pLine)->Line.Target.wPid = MM_MSFT_WDMAUDIO_WAVEIN; \
TargetCommon( pmxobj, pLine, WaveInDevice )
///////////////////////////////////////////////////////////////////////
//
// TargetTypeMidiOut
//
// Fills in the fields of aLine's target structure to be a midi out
// target.
//
//
#define TargetTypeMidiOut( pmxobj, pLine ) \
(pLine)->Line.Target.dwType = MIXERLINE_TARGETTYPE_MIDIOUT; \
(pLine)->Line.Target.wPid = MM_MSFT_WDMAUDIO_MIDIOUT; \
TargetCommon( pmxobj, pLine, MidiOutDevice )
///////////////////////////////////////////////////////////////////////
//
// TargetTypeMidiIn
//
// Fills in the fields of aLine's target structure to be a midi in
// target.
//
//
#define TargetTypeMidiIn( pmxobj, pLine ) \
(aLine)->Line.Target.dwType = MIXERLINE_TARGETTYPE_MIDIOUT; \
(aLine)->Line.Target.wPid = MM_MSFT_WDMAUDIO_MIDIIN; \
TargetCommon( pmxobj, pLine, MidiInDevice )
///////////////////////////////////////////////////////////////////////
//
// TargetTypeAuxCD
//
// Fills in the fields of aLine's target structure to be a CD
// target.
//
//
#define TargetTypeAuxCD( pmxobj, pLine ) \
(pLine)->Line.Target.dwType = MIXERLINE_TARGETTYPE_AUX; \
TargetCommon( pmxobj, pLine, WaveOutDevice ); \
(pLine)->Line.Target.wPid = MM_MSFT_SB16_AUX_CD
///////////////////////////////////////////////////////////////////////
//
// TargetTypeAuxLine
//
// Fills in the fields of aLine's target structure to be a aux line
// target.
//
//
#define TargetTypeAuxLine( pmxobj, pLine ) \
(pLine)->Line.Target.dwType = MIXERLINE_TARGETTYPE_AUX; \
TargetCommon( pmxobj, pLine, WaveOutDevice );\
(pLine)->Line.Target.wPid = MM_MSFT_SB16_AUX_LINE
///////////////////////////////////////////////////////////////////////
//
// kmxlDetermineDestinationType
//
// Determines the destination and target types by using the Type
// GUID stored in the line structure.
//
//
ULONG
kmxlDetermineDestinationType(
IN PMIXEROBJECT pmxobj, // Instance data
IN PMXLLINE pLine // The line to determine type of
)
{
PAGED_CODE();
//
// Speaker type destinations
//
if( IsEqualGUID( &pLine->Type, &KSNODETYPE_SPEAKER ) ||
IsEqualGUID( &pLine->Type, &KSNODETYPE_DESKTOP_SPEAKER ) ||
IsEqualGUID( &pLine->Type, &KSNODETYPE_ROOM_SPEAKER ) ||
IsEqualGUID( &pLine->Type, &KSNODETYPE_COMMUNICATION_SPEAKER ) ) {
TargetTypeWaveOut( pmxobj, pLine );
return( MIXERLINE_COMPONENTTYPE_DST_SPEAKERS );
}
//
// WaveIn type destinations
//
if( IsEqualGUID( &pLine->Type, &KSCATEGORY_AUDIO )
|| IsEqualGUID( &pLine->Type, &PINNAME_CAPTURE )
) {
TargetTypeWaveIn( pmxobj, pLine );
return( MIXERLINE_COMPONENTTYPE_DST_WAVEIN );
}
//
// Headphone destination
//
if( IsEqualGUID( &pLine->Type, &KSNODETYPE_HEADPHONES ) ||
IsEqualGUID( &pLine->Type, &KSNODETYPE_HEAD_MOUNTED_DISPLAY_AUDIO ) ) {
TargetTypeWaveOut( pmxobj, pLine );
return( MIXERLINE_COMPONENTTYPE_DST_HEADPHONES );
}
//
// Telephone destination
//
if( IsEqualGUID( &pLine->Type, &KSNODETYPE_TELEPHONE ) ||
IsEqualGUID( &pLine->Type, &KSNODETYPE_PHONE_LINE ) ||
IsEqualGUID( &pLine->Type, &KSNODETYPE_DOWN_LINE_PHONE ) )
{
pLine->Line.Target.dwType = MIXERLINE_TARGETTYPE_UNDEFINED;
return( MIXERLINE_COMPONENTTYPE_DST_TELEPHONE );
}
//
// Ambiguous destination type. Figure out the destination type by looking
// at the Communication.
//
if( IsEqualGUID( &pLine->Type, &KSNODETYPE_ANALOG_CONNECTOR ) ||
IsEqualGUID( &pLine->Type, &KSNODETYPE_SPDIF_INTERFACE ) ) {
if (pLine->Communication == KSPIN_COMMUNICATION_BRIDGE) {
TargetTypeWaveOut( pmxobj, pLine );
return( MIXERLINE_COMPONENTTYPE_DST_SPEAKERS );
} else {
TargetTypeWaveIn( pmxobj, pLine );
return( MIXERLINE_COMPONENTTYPE_DST_WAVEIN );
}
}
//
// Does not match the others. Default to Undefined destination.
//
pLine->Line.Target.dwType = MIXERLINE_TARGETTYPE_UNDEFINED;
return( MIXERLINE_COMPONENTTYPE_DST_UNDEFINED );
}
///////////////////////////////////////////////////////////////////////
//
// kmxlDetermineSourceType
//
// Determines the destination and target types by using the Type
// GUID stored in the line structure.
//
//
ULONG
kmxlDetermineSourceType(
IN PMIXEROBJECT pmxobj, // Instance data
IN PMXLLINE pLine // The line to determine type of
)
{
PAGED_CODE();
//
// All microphone type sources are a microphone source.
//
//
// We are only checking two microphone GUIDs here. We may
// want to consider the rest of the microphone types in
// ksmedia.h
//
if( IsEqualGUID( &pLine->Type, &KSNODETYPE_MICROPHONE )
|| IsEqualGUID( &pLine->Type, &KSNODETYPE_DESKTOP_MICROPHONE )
)
{
TargetTypeWaveIn( pmxobj, pLine );
return( MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE );
}
//
// Legacy audio connector and the speaker type sources represent a
// waveout source.
//
if( IsEqualGUID( &pLine->Type, &KSNODETYPE_LEGACY_AUDIO_CONNECTOR )
|| IsEqualGUID( &pLine->Type, &KSNODETYPE_SPEAKER )
|| IsEqualGUID( &pLine->Type, &KSCATEGORY_AUDIO )
)
{
TargetTypeWaveOut( pmxobj, pLine );
return( MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT );
}
//
// CD player is a compact disc source.
//
if( IsEqualGUID( &pLine->Type, &KSNODETYPE_CD_PLAYER ) ) {
TargetTypeAuxCD( pmxobj, pLine );
pLine->Line.Target.dwType = MIXERLINE_TARGETTYPE_UNDEFINED;
return( MIXERLINE_COMPONENTTYPE_SRC_COMPACTDISC );
}
//
// Synthesizer is a sythesizer source.
//
if( IsEqualGUID( &pLine->Type, &KSNODETYPE_SYNTHESIZER ) ) {
TargetTypeMidiOut( pmxobj, pLine );
return( MIXERLINE_COMPONENTTYPE_SRC_SYNTHESIZER );
}
if( IsEqualGUID( &pLine->Type, &KSNODETYPE_LINE_CONNECTOR ) ) {
TargetTypeAuxLine( pmxobj, pLine );
pLine->Line.Target.dwType = MIXERLINE_TARGETTYPE_UNDEFINED;
return( MIXERLINE_COMPONENTTYPE_SRC_LINE );
}
if( IsEqualGUID( &pLine->Type, &KSNODETYPE_PHONE_LINE ) ||
IsEqualGUID( &pLine->Type, &KSNODETYPE_TELEPHONE ) ||
IsEqualGUID( &pLine->Type, &KSNODETYPE_DOWN_LINE_PHONE ) )
{
pLine->Line.Target.dwType = MIXERLINE_TARGETTYPE_UNDEFINED;
return( MIXERLINE_COMPONENTTYPE_SRC_TELEPHONE );
}
if( IsEqualGUID( &pLine->Type, &KSNODETYPE_ANALOG_CONNECTOR ) ) {
//
// Ambiguous src type. Figure out the destination type by looking
// at the Communication.
//
if (pLine->Communication == KSPIN_COMMUNICATION_BRIDGE) {
TargetTypeWaveIn( pmxobj, pLine );
}
else {
TargetTypeWaveOut( pmxobj, pLine );
}
return( MIXERLINE_COMPONENTTYPE_SRC_ANALOG );
}
//
// Digital in/out (SPDIF) source
//
if( IsEqualGUID( &pLine->Type, &KSNODETYPE_SPDIF_INTERFACE ) ) {
//
// Ambiguous src type. Figure out the destination type by looking
// at the Communication.
//
if (pLine->Communication == KSPIN_COMMUNICATION_BRIDGE) {
TargetTypeWaveIn( pmxobj, pLine );
}
else {
TargetTypeWaveOut( pmxobj, pLine );
}
return( MIXERLINE_COMPONENTTYPE_SRC_DIGITAL );
}
//
// All others are lumped under Undefined source.
//
pLine->Line.Target.dwType = MIXERLINE_TARGETTYPE_UNDEFINED;
return( MIXERLINE_COMPONENTTYPE_SRC_UNDEFINED );
}
///////////////////////////////////////////////////////////////////////
//
// PinCategoryToString
//
// Converts the Pin category GUIDs to a string.
#ifdef DEBUG
#pragma LOCKED_CODE
#endif
#define _EG_(x,y) if (IsEqualGUID( NodeType, &x)) { return y; }
const char*
PinCategoryToString
(
IN CONST GUID* NodeType // The GUID to translate
)
{
_EG_(KSNODETYPE_MICROPHONE,"Microphone");
_EG_(KSNODETYPE_DESKTOP_MICROPHONE,"Desktop Microphone");
_EG_(KSNODETYPE_SPEAKER,"Speaker");
_EG_(KSNODETYPE_HEADPHONES,"Headphones");
_EG_(KSNODETYPE_LEGACY_AUDIO_CONNECTOR,"Wave");
_EG_(KSNODETYPE_CD_PLAYER,"CD Player");
_EG_(KSNODETYPE_SYNTHESIZER,"Synthesizer");
_EG_(KSCATEGORY_AUDIO,"Wave");
_EG_(PINNAME_CAPTURE,"Wave In");
_EG_(KSNODETYPE_LINE_CONNECTOR,"Aux Line");
_EG_(KSNODETYPE_TELEPHONE,"Telephone");
_EG_(KSNODETYPE_PHONE_LINE,"Phone Line");
_EG_(KSNODETYPE_DOWN_LINE_PHONE,"Downline Phone");
_EG_(KSNODETYPE_ANALOG_CONNECTOR,"Analog connector");
//New debug names...
_EG_(KSAUDFNAME_MONO_OUT,"Mono Out");
_EG_(KSAUDFNAME_STEREO_MIX,"Stereo Mix");
_EG_(KSAUDFNAME_MONO_MIX,"Mono Mix");
_EG_(KSAUDFNAME_AUX,"Aux");
_EG_(KSAUDFNAME_VIDEO,"Video");
_EG_(KSAUDFNAME_LINE_IN,"Line In");
DPF(DL_WARNING|FA_MIXER,("Path Trap send me GUID - dt %08X _GUID",NodeType) );
return "Unknown Pin Category";
}
///////////////////////////////////////////////////////////////////////
//
// NodeTypeToString
//
// Converts a NodeType GUID to a string
//
//
const char*
NodeTypeToString
(
IN CONST GUID* NodeType // The GUID to translate
)
{
_EG_(KSNODETYPE_DAC,"DAC");
_EG_(KSNODETYPE_ADC,"ADC");
_EG_(KSNODETYPE_SRC,"SRC");
_EG_(KSNODETYPE_SUPERMIX,"SuperMIX");
_EG_(KSNODETYPE_SUM,"Sum");
_EG_(KSNODETYPE_MUTE,"Mute");
_EG_(KSNODETYPE_VOLUME,"Volume");
_EG_(KSNODETYPE_TONE,"Tone");
_EG_(KSNODETYPE_AGC,"AGC");
_EG_(KSNODETYPE_DELAY,"Delay");
_EG_(KSNODETYPE_LOUDNESS,"LOUDNESS");
_EG_(KSNODETYPE_3D_EFFECTS,"3D Effects");
_EG_(KSNODETYPE_DEV_SPECIFIC,"Dev Specific");
_EG_(KSNODETYPE_STEREO_WIDE,"Stereo Wide");
_EG_(KSNODETYPE_REVERB,"Reverb");
_EG_(KSNODETYPE_CHORUS,"Chorus");
_EG_(KSNODETYPE_ACOUSTIC_ECHO_CANCEL,"AEC");
_EG_(KSNODETYPE_EQUALIZER,"Equalizer");
_EG_(KSNODETYPE_MUX,"Mux");
_EG_(KSNODETYPE_DEMUX,"Demux");
_EG_(KSNODETYPE_STEREO_ENHANCE,"Stereo Enhance");
_EG_(KSNODETYPE_SYNTHESIZER,"Synthesizer");
_EG_(KSNODETYPE_PEAKMETER,"Peakmeter");
_EG_(KSNODETYPE_LINE_CONNECTOR,"Line Connector");
_EG_(KSNODETYPE_SPEAKER,"Speaker");
_EG_(KSNODETYPE_DESKTOP_SPEAKER,"");
_EG_(KSNODETYPE_ROOM_SPEAKER,"Room Speaker");
_EG_(KSNODETYPE_COMMUNICATION_SPEAKER,"Communication Speaker");
_EG_(KSNODETYPE_LOW_FREQUENCY_EFFECTS_SPEAKER,"? Whatever...");
_EG_(KSNODETYPE_HANDSET,"Handset");
_EG_(KSNODETYPE_HEADSET,"Headset");
_EG_(KSNODETYPE_SPEAKERPHONE_NO_ECHO_REDUCTION,"Speakerphone no echo reduction");
_EG_(KSNODETYPE_ECHO_SUPPRESSING_SPEAKERPHONE,"Echo Suppressing Speakerphone");
_EG_(KSNODETYPE_ECHO_CANCELING_SPEAKERPHONE,"Echo Canceling Speakerphone");
_EG_(KSNODETYPE_CD_PLAYER,"CD Player");
_EG_(KSNODETYPE_MICROPHONE,"Microphone");
_EG_(KSNODETYPE_DESKTOP_MICROPHONE,"Desktop Microphone");
_EG_(KSNODETYPE_PERSONAL_MICROPHONE,"Personal Microphone");
_EG_(KSNODETYPE_OMNI_DIRECTIONAL_MICROPHONE,"Omni Directional Microphone");
_EG_(KSNODETYPE_MICROPHONE_ARRAY,"Microphone Array");
_EG_(KSNODETYPE_PROCESSING_MICROPHONE_ARRAY,"Processing Microphone Array");
_EG_(KSNODETYPE_ANALOG_CONNECTOR,"Analog Connector");
_EG_(KSNODETYPE_PHONE_LINE,"Phone Line");
_EG_(KSNODETYPE_HEADPHONES,"Headphones");
_EG_(KSNODETYPE_HEAD_MOUNTED_DISPLAY_AUDIO,"Head Mounted Display Audio");
_EG_(KSNODETYPE_LEGACY_AUDIO_CONNECTOR,"Legacy Audio Connector");
// _EG_(KSNODETYPE_SURROUND_ENCODER,"Surround Encoder");
_EG_(KSNODETYPE_NOISE_SUPPRESS,"Noise Suppress");
_EG_(KSNODETYPE_DRM_DESCRAMBLE,"DRM Descramble");
_EG_(KSNODETYPE_SWMIDI,"SWMidi");
_EG_(KSNODETYPE_SWSYNTH,"SWSynth");
_EG_(KSNODETYPE_MULTITRACK_RECORDER,"Multitrack Recorder");
_EG_(KSNODETYPE_RADIO_TRANSMITTER,"Radio Transmitter");
_EG_(KSNODETYPE_TELEPHONE,"Telephone");
_EG_(KSAUDFNAME_MONO_OUT,"Mono Out");
_EG_(KSAUDFNAME_LINE_IN,"Line in");
_EG_(KSAUDFNAME_VIDEO,"Video");
_EG_(KSAUDFNAME_AUX,"Aux");
_EG_(KSAUDFNAME_MONO_MIX,"Mono Mix");
_EG_(KSAUDFNAME_STEREO_MIX,"Stereo Mix");
_EG_(KSCATEGORY_AUDIO,"Audio");
_EG_(PINNAME_VIDEO_CAPTURE,"Video Capture");
DPF(DL_WARNING|FA_MIXER,("Path Trap send me GUID - dt %08X _GUID",NodeType) );
return "Unknown NodeType";
}
|
yiliuchen/TarsJava | core/src/main/java/com/qq/tars/protocol/tars/TarsStructBase.java | <gh_stars>100-1000
/**
* Tencent is pleased to support the open source community by making Tars available.
*
* Copyright (C) 2016 THL A29 Limited, a Tencent company. 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.
*/
package com.qq.tars.protocol.tars;
@SuppressWarnings("serial")
public abstract class TarsStructBase implements java.io.Serializable {
public static final byte BYTE = 0;
public static final byte SHORT = 1;
public static final byte INT = 2;
public static final byte LONG = 3;
public static final byte FLOAT = 4;
public static final byte DOUBLE = 5;
public static final byte STRING1 = 6;
public static final byte STRING4 = 7;
public static final byte MAP = 8;
public static final byte LIST = 9;
public static final byte STRUCT_BEGIN = 10;
public static final byte STRUCT_END = 11;
public static final byte ZERO_TAG = 12;
public static final byte SIMPLE_LIST = 13;
public static final int MAX_STRING_LENGTH = 100 * 1024 * 1024;
public abstract void writeTo(TarsOutputStream os);
public abstract void readFrom(TarsInputStream is);
public void display(StringBuilder sb, int level) {
}
public void displaySimple(StringBuilder sb, int level) {
}
public TarsStructBase newInit() {
return null;
}
public void recycle() {
}
public boolean containField(String name) {
return false;
}
public Object getFieldByName(String name) {
return null;
}
public void setFieldByName(String name, Object value) {
}
public byte[] toByteArray() {
TarsOutputStream os = new TarsOutputStream();
writeTo(os);
return os.toByteArray();
}
public byte[] toByteArray(String encoding) {
TarsOutputStream os = new TarsOutputStream();
os.setServerEncoding(encoding);
writeTo(os);
return os.toByteArray();
}
public String toString() {
StringBuilder sb = new StringBuilder();
display(sb, 0);
return sb.toString();
}
public static String toDisplaySimpleString(TarsStructBase struct) {
if (struct == null) {
return null;
}
StringBuilder sb = new StringBuilder();
struct.displaySimple(sb, 0);
return sb.toString();
}
}
|
Autoafterdarkphx/payflow-gateway | java/src/sdk/dataobjects/paypal/payflow/ECDoResponse.java | <gh_stars>10-100
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package paypal.payflow;
import paypal.payflow.ECGetResponse;
import java.util.Hashtable;
/**
* UUsed for ExpressCheckout Do operation.
* {@link ExpressCheckoutResponse}
* {@link ECGetResponse}
*/
public class ECDoResponse extends ExpressCheckoutResponse {
private String amt;
private String settleAmt;
private String taxAmt;
private String exchangeRate;
private String paymentDate;
private String paymentStatus;
private String baId;
/**
* Gets the Amt parameter
*
* @return - String
* <p>Maps to Payflow Parameter: AMT
*/
public String getAmt() {
return amt;
}
/**
* Gets the settleamt parameter
*
* @return - String
* <p>Maps to Payflow Parameter: SETTLEAMT
*/
public String getSettleAmt() {
return settleAmt;
}
/**
* Gets the tax amt parameter
*
* @return - String
* <p>Maps to Payflow Parameter: TAXAMT
*/
public String getTaxAmt() {
return taxAmt;
}
/**
* Gets the exchange rate parameter
*
* @return - String
* <p>Maps to Payflow Parameter: EXCHANGERATE
*/
public String getExchangeRate() {
return exchangeRate;
}
/**
* Gets the payment date parameter
*
* @return - String
* <p>Maps to Payflow Parameter: PAYMENTDATE
*/
public String getPaymentDate() {
return paymentDate;
}
/**
* Gets the Payment status parameter
*
* @return - String
* <p>Maps to Payflow Parameter: PAYMENTSTATUS
*/
public String getPaymentStatus() {
return paymentStatus;
}
/**
* Gets the BAID parameter
*
* @return - String
* <p>Maps to Payflow Parameter: BAID
*/
public String getbaId() {
return baId;
}
protected ECDoResponse() {
}
protected void setParams(Hashtable ResponseHashTable) {
amt = (String) ResponseHashTable.get(PayflowConstants.PARAM_AMT);
settleAmt = (String) ResponseHashTable.get(PayflowConstants.PARAM_SETTLEAMT);
taxAmt = (String) ResponseHashTable.get(PayflowConstants.PARAM_TAXAMT);
exchangeRate = (String) ResponseHashTable.get(PayflowConstants.PARAM_EXCHANGERATE);
paymentDate = (String) ResponseHashTable.get(PayflowConstants.PARAM_PAYMENTDATE);
paymentStatus = (String) ResponseHashTable.get(PayflowConstants.PARAM_PAYMENTSTATUS);
baId = (String) ResponseHashTable.get(PayflowConstants.PARAM_BAID);
ResponseHashTable.remove(PayflowConstants.PARAM_AMT);
ResponseHashTable.remove(PayflowConstants.PARAM_SETTLEAMT);
ResponseHashTable.remove(PayflowConstants.PARAM_TAXAMT);
ResponseHashTable.remove(PayflowConstants.PARAM_EXCHANGERATE);
ResponseHashTable.remove(PayflowConstants.PARAM_PAYMENTDATE);
ResponseHashTable.remove(PayflowConstants.PARAM_PAYMENTSTATUS);
ResponseHashTable.remove(PayflowConstants.PARAM_BAID);
}
}
|
wjiec/packages | java/effective-java/src/test/java/com/wjiec/learn/effectivejava/random/RandomNumberTest.java | <filename>java/effective-java/src/test/java/com/wjiec/learn/effectivejava/random/RandomNumberTest.java<gh_stars>0
package com.wjiec.learn.effectivejava.random;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
public class RandomNumberTest {
public static void main(String[] args) {
int n = 2 * (Integer.MAX_VALUE / 3);
int low = 0;
for (int i = 0; i < 1000000; i++) {
if (RandomNumber.random(n) < n / 2) {
low++;
}
}
System.out.println(low); // near 666666 why?
low = 0;
Random random = new Random();
for (int i = 0; i < 1000000; i++) {
if (random.nextInt(n) < n / 2) {
low++;
}
}
System.out.println(low); // it's ok
low = 0;
ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
for (int i = 0; i < 1000000; i++) {
if (threadLocalRandom.nextInt(n) < n / 2) {
low++;
}
}
System.out.println(low); // it's faster
}
}
|
aanciaes/secure-redis-container | prod/attestation_server/include/C_CkAuthAzureAD.h | // This is a generated source file for Chilkat version 9.5.0.83
#ifndef _C_CkAuthAzureAD_H
#define _C_CkAuthAzureAD_H
#include "chilkatDefs.h"
#include "Chilkat_C.h"
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_setAbortCheck(HCkAuthAzureAD cHandle, BOOL (*fnAbortCheck)(void));
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_setPercentDone(HCkAuthAzureAD cHandle, BOOL (*fnPercentDone)(int pctDone));
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_setProgressInfo(HCkAuthAzureAD cHandle, void (*fnProgressInfo)(const char *name, const char *value));
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_setTaskCompleted(HCkAuthAzureAD cHandle, void (*fnTaskCompleted)(HCkTask hTask));
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_setAbortCheck2(HCkAuthAzureAD cHandle, BOOL (*fnAbortCheck2)(void *pContext));
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_setPercentDone2(HCkAuthAzureAD cHandle, BOOL (*fnPercentDone2)(int pctDone, void *pContext));
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_setProgressInfo2(HCkAuthAzureAD cHandle, void (*fnProgressInfo2)(const char *name, const char *value, void *pContext));
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_setTaskCompleted2(HCkAuthAzureAD cHandle, void (*fnTaskCompleted2)(HCkTask hTask, void *pContext));
// setExternalProgress is for C callback functions defined in the external programming language (such as Go)
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_setExternalProgress(HCkAuthAzureAD cHandle, BOOL on);
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_setCallbackContext(HCkAuthAzureAD cHandle, void *pContext);
CK_C_VISIBLE_PUBLIC HCkAuthAzureAD CkAuthAzureAD_Create(void);
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_Dispose(HCkAuthAzureAD handle);
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_getAccessToken(HCkAuthAzureAD cHandle, HCkString retval);
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_putAccessToken(HCkAuthAzureAD cHandle, const char *newVal);
CK_C_VISIBLE_PUBLIC const char *CkAuthAzureAD_accessToken(HCkAuthAzureAD cHandle);
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_getClientId(HCkAuthAzureAD cHandle, HCkString retval);
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_putClientId(HCkAuthAzureAD cHandle, const char *newVal);
CK_C_VISIBLE_PUBLIC const char *CkAuthAzureAD_clientId(HCkAuthAzureAD cHandle);
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_getClientSecret(HCkAuthAzureAD cHandle, HCkString retval);
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_putClientSecret(HCkAuthAzureAD cHandle, const char *newVal);
CK_C_VISIBLE_PUBLIC const char *CkAuthAzureAD_clientSecret(HCkAuthAzureAD cHandle);
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_getDebugLogFilePath(HCkAuthAzureAD cHandle, HCkString retval);
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_putDebugLogFilePath(HCkAuthAzureAD cHandle, const char *newVal);
CK_C_VISIBLE_PUBLIC const char *CkAuthAzureAD_debugLogFilePath(HCkAuthAzureAD cHandle);
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_getLastErrorHtml(HCkAuthAzureAD cHandle, HCkString retval);
CK_C_VISIBLE_PUBLIC const char *CkAuthAzureAD_lastErrorHtml(HCkAuthAzureAD cHandle);
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_getLastErrorText(HCkAuthAzureAD cHandle, HCkString retval);
CK_C_VISIBLE_PUBLIC const char *CkAuthAzureAD_lastErrorText(HCkAuthAzureAD cHandle);
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_getLastErrorXml(HCkAuthAzureAD cHandle, HCkString retval);
CK_C_VISIBLE_PUBLIC const char *CkAuthAzureAD_lastErrorXml(HCkAuthAzureAD cHandle);
CK_C_VISIBLE_PUBLIC BOOL CkAuthAzureAD_getLastMethodSuccess(HCkAuthAzureAD cHandle);
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_putLastMethodSuccess(HCkAuthAzureAD cHandle, BOOL newVal);
CK_C_VISIBLE_PUBLIC int CkAuthAzureAD_getNumSecondsRemaining(HCkAuthAzureAD cHandle);
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_getResource(HCkAuthAzureAD cHandle, HCkString retval);
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_putResource(HCkAuthAzureAD cHandle, const char *newVal);
CK_C_VISIBLE_PUBLIC const char *CkAuthAzureAD_resource(HCkAuthAzureAD cHandle);
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_getTenantId(HCkAuthAzureAD cHandle, HCkString retval);
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_putTenantId(HCkAuthAzureAD cHandle, const char *newVal);
CK_C_VISIBLE_PUBLIC const char *CkAuthAzureAD_tenantId(HCkAuthAzureAD cHandle);
CK_C_VISIBLE_PUBLIC BOOL CkAuthAzureAD_getUtf8(HCkAuthAzureAD cHandle);
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_putUtf8(HCkAuthAzureAD cHandle, BOOL newVal);
CK_C_VISIBLE_PUBLIC BOOL CkAuthAzureAD_getValid(HCkAuthAzureAD cHandle);
CK_C_VISIBLE_PUBLIC BOOL CkAuthAzureAD_getVerboseLogging(HCkAuthAzureAD cHandle);
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_putVerboseLogging(HCkAuthAzureAD cHandle, BOOL newVal);
CK_C_VISIBLE_PUBLIC void CkAuthAzureAD_getVersion(HCkAuthAzureAD cHandle, HCkString retval);
CK_C_VISIBLE_PUBLIC const char *CkAuthAzureAD_version(HCkAuthAzureAD cHandle);
CK_C_VISIBLE_PUBLIC BOOL CkAuthAzureAD_LoadTaskCaller(HCkAuthAzureAD cHandle, HCkTask task);
CK_C_VISIBLE_PUBLIC BOOL CkAuthAzureAD_ObtainAccessToken(HCkAuthAzureAD cHandle, HCkSocket connection);
CK_C_VISIBLE_PUBLIC HCkTask CkAuthAzureAD_ObtainAccessTokenAsync(HCkAuthAzureAD cHandle, HCkSocket connection);
CK_C_VISIBLE_PUBLIC BOOL CkAuthAzureAD_SaveLastError(HCkAuthAzureAD cHandle, const char *path);
#endif
|
cybergarage/CyberLink4CC | std/include/cybergarage/upnp/media/server/object/format/JPEGFormat.h | <reponame>cybergarage/CyberLink4CC
/******************************************************************
*
* MediaServer for CyberLink
*
* Copyright (C) <NAME> 2003
*
* File : JPEGFormat.h
*
* Revision:
*
* 04/18/04
* - first revision.
*
******************************************************************/
#ifndef _CLINK_MEDIA_JPEGFORMT_H_
#define _CLINK_MEDIA_JPEGFORMT_H_
#include <cybergarage/upnp/media/server/object/format/ImageFormat.h>
namespace CyberLink {
class JPEGFormat : public ImageFormat
{
////////////////////////////////////////////////
// Constroctor
////////////////////////////////////////////////
public:
JPEGFormat();
JPEGFormat(CyberIO::File *file);
////////////////////////////////////////////////
// Abstract Methods
////////////////////////////////////////////////
public:
bool equals(CyberIO::File *file);
FormatObject *createObject(CyberIO::File *file)
{
return new JPEGFormat(file);
}
const char *getMimeType()
{
return "image/jpeg";
}
};
}
#endif
|
anistarafdar/gbdk-2020 | docs/api/search/defines_a.js | var searchData=
[
['j_5fa_1136',['J_A',['../gb_8h.html#a31af766e3b598eb7a6b63f55a4988e7a',1,'gb.h']]],
['j_5fb_1137',['J_B',['../gb_8h.html#ae47e59a309120f9420993f26816b5e6d',1,'gb.h']]],
['j_5fdown_1138',['J_DOWN',['../gb_8h.html#ae032c5c544196e37ec0432f6cfad7904',1,'gb.h']]],
['j_5fleft_1139',['J_LEFT',['../gb_8h.html#ac70894fecac30c1ca9917f07373cf81c',1,'gb.h']]],
['j_5fright_1140',['J_RIGHT',['../gb_8h.html#a3bad91d11ae09ffcbb3cb0a81873d325',1,'gb.h']]],
['j_5fselect_1141',['J_SELECT',['../gb_8h.html#ab416a9d96d1582490828f4bac78a8b5b',1,'gb.h']]],
['j_5fstart_1142',['J_START',['../gb_8h.html#ab769c6e20778298be8bc3321476ceb53',1,'gb.h']]],
['j_5fup_1143',['J_UP',['../gb_8h.html#a05ca817ab32f6da612c3ae26db5abf02',1,'gb.h']]],
['joy_5fiflag_1144',['JOY_IFLAG',['../gb_8h.html#a2f829cf27d6e3e24c875e9b82dfcb280',1,'gb.h']]]
];
|
Anonym0uz/VKPreferences | VKHDHeaders/MRAsyncCommandDelegate-Protocol.h | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
@class MRAsyncCommand, MRAsyncCommandResult;
@protocol MRAsyncCommandDelegate
- (void)commandFinished:(MRAsyncCommand *)arg1 withResult:(MRAsyncCommandResult *)arg2;
@end
|
csga31971/testbot | src/com/moebuff/discord/utils/URLUtils.java | <reponame>csga31971/testbot<filename>src/com/moebuff/discord/utils/URLUtils.java
package com.moebuff.discord.utils;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.net.URLCodec;
import java.io.File;
import java.io.IOException;
import java.net.*;
import java.util.jar.JarFile;
/**
* URL 工具类
*
* @author muto
*/
public class URLUtils {
/**
* 为 Lambda 而生,它允许你通过表达式来代替功能接口。
*/
public interface URLGetter {
String getURL();//获取URL字符串
}
private static final URLCodec codec = new URLCodec();
/**
* 使用默认的编码机制对 application/x-www-form-urlencoded 字符串解码。
*
* @param url 要解码的字符串
* @return 新解码的字符串
*/
public static String decode(String url) {
try {
return codec.decode(url);
} catch (DecoderException e) {
throw new UnhandledException(e);
}
}
/**
* 原则上和 {@link #decode(String)} 没有区别,主要针对 Lambda 表达式,
* 通过 {@code 方法引用::} 简化调用嵌套,从而增强代码的可读性。
*/
public static String decode(URLGetter getter) {
return decode(getter.getURL());
}
/**
* 使用默认的编码机制将字符串转换为 application/x-www-form-urlencoded 格式。
*
* @param url 要转换的字符串
* @return 已转换的字符串
*/
public static String encode(String url) {
try {
return codec.encode(url);
} catch (EncoderException e) {
throw new UnhandledException(e);
}
}
/**
* 将 URL 转换成 URI
*/
public static URI toURI(URL url) {
try {
return url.toURI();
} catch (URISyntaxException e) {
throw new UnhandledException(e);
}
}
/**
* 用 url 创建一个 file 对象
*/
public static File toFile(URL url) {
return new File(toURI(url));
}
/**
* 返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。
*
* @param <T> 便于类型转换,必须是 URLConnection 的子类
*/
public static <T extends URLConnection> T openConnection(URL url) {
try {
//noinspection unchecked
return (T) url.openConnection();
} catch (IOException e) {
throw new UnhandledException(e);
}
}
/**
* 返回此连接的 JAR 文件。需要保证指定的 URL,其协议名为 jar,否则将触发类型转换错误。
*/
public static JarFile getJarFile(URL url) {
JarURLConnection connection = openConnection(url);
try {
return connection.getJarFile();
} catch (IOException e) {
throw new UnhandledException(e);
}
}
/**
* 根据 String 表示形式创建 URL 对象
*
* @param spec 将作为 URL 解析的 String
* @return 新创建的 URL 对象
* @throws UnhandledException 如果字符串指定未知协议
*/
public static URL create(String spec) {
try {
return new URL(spec);
} catch (MalformedURLException e) {
throw new UnhandledException(e);
}
}
}
|
ThinkingXuan/chat-room-go | api/router/router.go | package router
import (
"chat-room-go/api/router/handlers"
"chat-room-go/api/router/middleware"
"github.com/gin-gonic/gin"
)
// Load load the middlewares, routers
func Load(e *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine {
// use middlewares
//e.Use(gin.Recovery())
//e.Use(gin.Logger())
e.Use(mw...)
// user router
user := e.Group("/")
{
user.POST("/user", handlers.CreateUser) // Create user
user.GET("/userLogin", handlers.UserLogin) // Logs user into the system
user.GET("/user/:username", handlers.GetUser) // Get user by user name
}
// room router
room := e.Group("/")
{
room.POST("/room", handlers.CreateRoom) // Create a new room
room.PUT("/room/:roomid/enter", middleware.JWTAuth(), handlers.EnterRoom) // Enter a room
room.PUT("/roomLeave", middleware.JWTAuth(), handlers.LeaveRoom) // Leave a root
room.GET("/room/:roomid", handlers.GetOneRoomInfo) // Get the room info
room.GET("/room/:roomid/users", handlers.RoomAllUser) // Get user list in a room, only username in list
room.POST("/roomList", handlers.GetRoomList) // Get the room list
}
// message router
message := e.Group("/", middleware.JWTAuth())
{
message.POST("/message/send", handlers.SendMessage) // After enter a room, the user can send the message to the current room.
message.POST("/message/retrieve", handlers.GetMessageList) // After enter a room, the user can retrieve the message in the current room
}
return e
}
|
UCLALibrary/bucketeer | src/main/java/edu/ucla/library/bucketeer/HTTP.java |
package edu.ucla.library.bucketeer;
/**
* A set of HTTP related constants.
*/
public final class HTTP {
/** Success response */
public static final int OK = 200;
/** Created response */
public static final int CREATED = 201;
/** Success, no content */
public static final int NO_CONTENT = 204;
/** Temporary redirect */
public static final int TEMP_REDIRECT = 307;
/** Too many requests */
public static final int TOO_MANY_REQUESTS = 429;
/** Not found response */
public static final int NOT_FOUND = 404;
/** Method not allowed */
public static final int METHOD_NOT_ALLOWED = 405;
/** An empty or other unsupported media type */
public static final int UNSUPPORTED_MEDIA_TYPE = 415;
/** Generic internal server error */
public static final int INTERNAL_SERVER_ERROR = 500;
/** Bad request */
public static final int BAD_REQUEST = 400;
/**
* A private constructor for the constants class.
*/
private HTTP() {
}
}
|
lockie/HiveGame | HiveGame/MyGUI/MyGUIEngine/include/MyGUI_ResourceManager.h | <gh_stars>1-10
/*!
@file
@author <NAME>
@date 09/2008
*/
/*
This file is part of MyGUI.
MyGUI is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MyGUI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with MyGUI. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __MYGUI_RESOURCE_MANAGER_H__
#define __MYGUI_RESOURCE_MANAGER_H__
#include "MyGUI_Prerequest.h"
#include "MyGUI_Singleton.h"
#include "MyGUI_Enumerator.h"
#include "MyGUI_XmlDocument.h"
#include "MyGUI_IResource.h"
#include "MyGUI_Delegate.h"
#include "MyGUI_BackwardCompatibility.h"
namespace MyGUI
{
class MYGUI_EXPORT ResourceManager :
public Singleton<ResourceManager>,
public MemberObsolete<ResourceManager>
{
public:
ResourceManager();
void initialise();
void shutdown();
public:
/** Load additional MyGUI *_resource.xml file */
bool load(const std::string& _file);
void loadFromXmlNode(xml::ElementPtr _node, const std::string& _file, Version _version);
/** Add resource item to resources */
void addResource(IResourcePtr _item);
/** Remove resource item from resources */
void removeResource(IResourcePtr _item);
typedef delegates::CDelegate3<xml::ElementPtr, const std::string&, Version> LoadXmlDelegate;
/** Register delegate that parse XML node with specified tag (_key) */
LoadXmlDelegate& registerLoadXmlDelegate(const std::string& _key);
/** Unregister delegate that parse XML node with specified tag (_key) */
void unregisterLoadXmlDelegate(const std::string& _key);
/** Check is resource exist */
bool isExist(const std::string& _name) const;
/** Find resource by name*/
IResource* findByName(const std::string& _name) const;
/** Get resource by name*/
IResource* getByName(const std::string& _name, bool _throw = true) const;
bool removeByName(const std::string& _name);
void clear();
typedef std::map<std::string, IResource*> MapResource;
typedef Enumerator<MapResource> EnumeratorPtr;
EnumeratorPtr getEnumerator() const;
size_t getCount();
private:
void _loadList(xml::ElementPtr _node, const std::string& _file, Version _version);
bool _loadImplement(const std::string& _file, bool _match, const std::string& _type, const std::string& _instance);
private:
// карта с делегатами для парсинга хмл блоков
typedef std::map<std::string, LoadXmlDelegate> MapLoadXmlDelegate;
MapLoadXmlDelegate mMapLoadXmlDelegate;
MapResource mResources;
typedef std::vector<IResource*> VectorResource;
VectorResource mRemovedResoures;
bool mIsInitialise;
};
} // namespace MyGUI
#endif // __MYGUI_RESOURCE_MANAGER_H__
|
BrassGoggledCoders/SteamAgeRevolution | unused/code/guideapi/CategoryTransportStorage.java | package xyz.brassgoggledcoders.steamagerevolution.compat.guideapi;
import java.util.*;
import amerifrance.guideapi.api.IPage;
import amerifrance.guideapi.api.impl.abstraction.EntryAbstract;
import amerifrance.guideapi.api.util.PageHelper;
import amerifrance.guideapi.entry.EntryItemStack;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.translation.I18n;
import xyz.brassgoggledcoders.steamagerevolution.SteamAgeRevolution;
public class CategoryTransportStorage {
public static Map<ResourceLocation, EntryAbstract> buildCategory() {
Map<ResourceLocation, EntryAbstract> entries = new LinkedHashMap<ResourceLocation, EntryAbstract>();
String keyBase = "guide." + SteamAgeRevolution.MODID + ".entry.transportstorage.";
List<IPage> canisterEntry = new ArrayList<IPage>();
canisterEntry.addAll(PageHelper.pagesForLongText(I18n.translateToLocalFormatted(keyBase + "canister.info")));
// canisterEntry.add(new PageJsonRecipe(new
// ResourceLocation(SteamAgeRevolution.MODID, "canister")));
// TODO Recipe handling
entries.put(new ResourceLocation(SteamAgeRevolution.MODID, "canister_entry"),
new EntryItemStack(canisterEntry, keyBase + "canister", new ItemStack(BookObjectHolder.canister)));
List<IPage> fluidHopperEntry = new ArrayList<IPage>();
fluidHopperEntry
.addAll(PageHelper.pagesForLongText(I18n.translateToLocalFormatted(keyBase + "fluid_hopper.info")));
// fluidHopperEntry.add(new PageJsonRecipe(new
// ResourceLocation(SteamAgeRevolution.MODID, "fluid_hopper")));
entries.put(new ResourceLocation(SteamAgeRevolution.MODID, "fluid_hopper_entry"), new EntryItemStack(
fluidHopperEntry, keyBase + "fluid_hopper", new ItemStack(BookObjectHolder.fluid_hopper)));
List<IPage> pneumaticsEntry = new ArrayList<IPage>();
pneumaticsEntry
.addAll(PageHelper.pagesForLongText(I18n.translateToLocalFormatted(keyBase + "pneumatics.info")));
entries.put(new ResourceLocation(SteamAgeRevolution.MODID, "pneumatics_entry"), new EntryItemStack(
pneumaticsEntry, keyBase + "pneumatics", new ItemStack(BookObjectHolder.pneumatic_tube)));
List<IPage> basicTankEntry = new ArrayList<IPage>();
basicTankEntry.addAll(PageHelper.pagesForLongText(I18n.translateToLocalFormatted(keyBase + "basic_tank.info")));
entries.put(new ResourceLocation(SteamAgeRevolution.MODID, "basic_tank_entry"), new EntryItemStack(
basicTankEntry, keyBase + "basic_tank", new ItemStack(BookObjectHolder.basic_fluid_tank)));
List<IPage> tankEntry = new ArrayList<IPage>();
tankEntry.addAll(PageHelper.pagesForLongText(I18n.translateToLocalFormatted(keyBase + "tank.info")));
entries.put(new ResourceLocation(SteamAgeRevolution.MODID, "tank_entry"),
new EntryItemStack(tankEntry, keyBase + "tank", new ItemStack(BookObjectHolder.tank_valve)));
for (EntryAbstract entry : entries.values()) {
PageHelper.setPagesToUnicode(entry.pageList);
}
return entries;
}
}
|
aapotts/3akai-ux | dev/lib/jquery/plugins/jquery.autolink.js | <gh_stars>1-10
/*
jQuery AutoLink
MIT License
Sakai OAE Notes: below
This was originally taken from here: https://gist.github.com/47317
on July 29, 2011.
We have made a few changes, such as fixing a syntax error, changing the
replace link to use Sakai OAE styles, and adding a check for if parent is
undefined.
Eventually, given some time, I would like to see the url_regexp expanded to
included other schemes, and www. style links with no scheme. ( Such as in
the O'Reilly Regular Expression Cookbook 7.2 ).
*/
require(['jquery'], function (jQuery) {
(function($) {
var url_regexp = /(https?:\/\/[\u007F-\uFFFF-A-Za-z0-9\~\/._\?\&=\-%#\+:\;,\@\'\(\)]+)/;
$.fn.autolink = function() {
return this.each(function(){
var desc = $(this);
desc.textNodes().each(function(){
var text = $(this);
var parent = text.parent();
if(parent && parent.get(0).nodeName != 'A') {
text.replaceWith(this.data.replace(url_regexp, function($0, $1) {
return '<a class=\'my_link s3d-regular-links s3d-bold\' target=\'_blank\' href="' + $1 +'">' + $1 + '</a>';
}));
}
});
});
};
$.fn.textNodes = function() {
var ret = [];
(function(el) {
if (!el) {
return;
}
if ((el.nodeType == 3)) {
ret.push(el);
} else {
for (var i=0; i < el.childNodes.length; ++i) {
arguments.callee(el.childNodes[i]);
}
}
})(this[0]);
return $(ret);
};
})(jQuery);
});
|
asad-awadia/swim | swim-system-java/swim-core-java/swim.csv/src/main/java/swim/csv/structure/ArrayStructure.java | <filename>swim-system-java/swim-core-java/swim.csv/src/main/java/swim/csv/structure/ArrayStructure.java<gh_stars>0
// Copyright 2015-2021 Swim 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 swim.csv.structure;
import swim.csv.schema.CsvCol;
import swim.structure.Item;
import swim.structure.Record;
import swim.structure.Value;
import swim.util.Builder;
final class ArrayStructure extends CsvStructureHeader {
final CsvCol<? extends Item> col;
final int colCount;
ArrayStructure(CsvCol<? extends Item> col, int colCount) {
this.col = col;
this.colCount = colCount;
}
@Override
public int colCount() {
return this.colCount;
}
@Override
public CsvCol<? extends Item> getCol(int index) {
return this.col;
}
@Override
public CsvCol<? extends Item> overflowCol() {
return this.col;
}
@Override
public CsvStructureHeader col(int index, CsvCol<? extends Item> col) {
throw new UnsupportedOperationException();
}
@Override
public CsvStructureHeader col(int index, String name) {
throw new UnsupportedOperationException();
}
@Override
public CsvStructureHeader col(CsvCol<? extends Item> col) {
throw new UnsupportedOperationException();
}
@Override
public CsvStructureHeader col(String name) {
throw new UnsupportedOperationException();
}
@Override
public CsvStructureHeader cols(CsvStructureCol... cols) {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unchecked")
@Override
public Builder<Item, Value> rowBuilder() {
return (Builder<Item, Value>) (Builder<?, ?>) Record.create();
}
@SuppressWarnings("unchecked")
@Override
public Builder<Value, Record> tableBuilder() {
return (Builder<Value, Record>) (Builder<?, ?>) Record.create();
}
}
|
backo880607/pisces | integration/src/main/java/com/pisces/integration/bean/DsStream.java | package com.pisces.integration.bean;
import javax.persistence.Table;
import com.pisces.integration.enums.STREAM_TYPE;
@Table(name = "INTEGRATION_DS_STREAM")
public class DsStream extends DataSource {
private STREAM_TYPE type;
@Override
public void init() {
super.init();
type = STREAM_TYPE.TABLE;
}
public STREAM_TYPE getType() {
return type;
}
public void setType(STREAM_TYPE type) {
this.type = type;
}
}
|
pdv-ru/ClickHouse | src/Functions/JSONPath/Parsers/ParserJSONPathStar.cpp | <reponame>pdv-ru/ClickHouse
#include <Functions/JSONPath/Parsers/ParserJSONPathStar.h>
#include <Functions/JSONPath/ASTs/ASTJSONPathStar.h>
namespace DB
{
bool ParserJSONPathStar::parseImpl(Pos & pos, ASTPtr & node, Expected & expected)
{
if (pos->type != TokenType::OpeningSquareBracket)
{
return false;
}
++pos;
if (pos->type != TokenType::Asterisk)
{
return false;
}
++pos;
if (pos->type != TokenType::ClosingSquareBracket)
{
expected.add(pos, "Closing square bracket");
return false;
}
++pos;
node = std::make_shared<ASTJSONPathStar>();
return true;
}
}
|
my-personal-forks/Vintageous | ex_motions.py | import sublime
import sublime_plugin
class _vi_cmd_line_a(sublime_plugin.TextCommand):
def run(self, edit):
self.view.sel().clear()
self.view.sel().add(sublime.Region(1))
class _vi_cmd_line_k(sublime_plugin.TextCommand):
def run(self, edit):
text = self.view.substr(sublime.Region(0, self.view.sel()[0].b))
self.view.replace(edit, sublime.Region(0, self.view.size()), text)
self.view.sel().clear()
self.view.sel().add(sublime.Region(self.view.size()))
|
kstrat2001/greedyshot-ios | Classes/GameParticles.h | <reponame>kstrat2001/greedyshot-ios<filename>Classes/GameParticles.h
//
// GameParticles.h
// collector
//
// Created by <NAME> on 3/12/11.
// Copyright 2011 C-Stick Run. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import "CCParticleExamples.h"
@interface OrbitExplosionParticles : CCParticleExplosion {
}
@end
@interface PlayerExplosionParticles : CCParticleExplosion {
}
@end
@interface PlayerTrailParticles : CCParticleFire {
}
@end
@interface OrbitTrailParticles : CCParticleFire {
}
@end
@interface AsteroidExplodeParticles : CCParticleFire {
}
@end
@interface FieroParticles : CCParticleFire {
}
@end
@interface OrbitPickupParticles : CCParticleFire {
}
@end
@interface FieroPickupParticles : CCParticleFire {
}
@end
|
BlizzedRu/OpenSongKick | src/main/java/ru/blizzed/opensongkick/methods/gigography/ArtistGigography.java | <reponame>BlizzedRu/OpenSongKick
package ru.blizzed.opensongkick.methods.gigography;
import ru.blizzed.opensongkick.ApiCaller;
import ru.blizzed.opensongkick.models.Event;
import ru.blizzed.opensongkick.models.ResultsPage;
import ru.blizzed.opensongkick.params.Param;
import ru.blizzed.opensongkick.params.ParamsConverter;
public class ArtistGigography {
private ArtistGigographyCaller artistGigographyCaller;
public ArtistGigography(ArtistGigographyCaller artistGigographyCaller) {
this.artistGigographyCaller = artistGigographyCaller;
}
public ApiCaller<ResultsPage<Event>> byId(String id) {
return new ApiCaller<>(artistGigographyCaller.byId(id));
}
public ApiCaller<ResultsPage<Event>> byId(String id, Param... params) {
return new ApiCaller<>(artistGigographyCaller.byId(id, ParamsConverter.asMap(params)));
}
public ApiCaller<ResultsPage<Event>> byMbid(String mbid) {
return new ApiCaller<>(artistGigographyCaller.byMbid(mbid));
}
public ApiCaller<ResultsPage<Event>> byMbid(String mbid, Param... params) {
return new ApiCaller<>(artistGigographyCaller.byMbid(mbid, ParamsConverter.asMap(params)));
}
}
|
sheisters/doc-parser-proffix | _result/golang/Dokumentstatus.go | <filename>_result/golang/Dokumentstatus.go
package golang
type Dokumentstatus struct {
DokumentstatusNr string `json:DokumentstatusNr`
Bezeichnung string `json:Bezeichnung`
Sperren bool `json:Sperren`
}
|
bdaw/keycloak | forms/common-freemarker/src/main/java/org/keycloak/freemarker/FreeMarkerUtil.java | package org.keycloak.freemarker;
import freemarker.cache.URLTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public class FreeMarkerUtil {
public static String processTemplate(Object data, String templateName, Theme theme) throws FreeMarkerException {
Writer out = new StringWriter();
Configuration cfg = new Configuration();
try {
cfg.setTemplateLoader(new ThemeTemplateLoader(theme));
Template template = cfg.getTemplate(templateName);
template.process(data, out);
} catch (Exception e) {
throw new FreeMarkerException("Failed to process template " + templateName, e);
}
return out.toString();
}
public static class ThemeTemplateLoader extends URLTemplateLoader {
private Theme theme;
public ThemeTemplateLoader(Theme theme) {
this.theme = theme;
}
@Override
protected URL getURL(String name) {
try {
return theme.getTemplate(name);
} catch (IOException e) {
return null;
}
}
}
}
|
vrushank-agrawal/video_editor_BX23 | src/audio/aubio/python/demos/demo_yin_compare.py | <gh_stars>0
#! /usr/bin/env python
# -*- coding: utf8 -*-
""" Pure python implementation of the sum of squared difference
sqd_yin: original sum of squared difference [0]
d_t(tau) = x ⊗ kernel
sqd_yinfast: sum of squared diff using complex domain [0]
sqd_yinfftslow: tappered squared diff [1]
sqd_yinfft: modified squared diff using complex domain [1]
[0]:http://audition.ens.fr/adc/pdf/2002_JASA_YIN.pdf
[1]:https://aubio.org/phd/
"""
import sys
import numpy as np
import matplotlib.pyplot as plt
def sqd_yin(samples):
""" compute original sum of squared difference
Brute-force computation (cost o(N**2), slow)."""
B = len(samples)
W = B//2
yin = np.zeros(W)
for j in range(W):
for tau in range(1, W):
yin[tau] += (samples[j] - samples[j+tau])**2
return yin
def sqd_yinfast(samples):
""" compute approximate sum of squared difference
Using complex convolution (fast, cost o(n*log(n)) )"""
# yin_t(tau) = (r_t(0) + r_(t+tau)(0)) - 2r_t(tau)
B = len(samples)
W = B//2
yin = np.zeros(W)
sqdiff = np.zeros(W)
kernel = np.zeros(B)
# compute r_(t+tau)(0)
squares = samples**2
for tau in range(W):
sqdiff[tau] = squares[tau:tau+W].sum()
# add r_t(0)
sqdiff += sqdiff[0]
# compute r_t(tau) using kernel convolution in complex domain
samples_fft = np.fft.fft(samples)
kernel[1:W+1] = samples[W-1::-1] # first half, reversed
kernel_fft = np.fft.fft(kernel)
r_t_tau = np.fft.ifft(samples_fft * kernel_fft).real[W:]
# compute yin_t(tau)
yin = sqdiff - 2 * r_t_tau
return yin
def sqd_yintapered(samples):
""" compute tappered sum of squared difference
Brute-force computation (cost o(N**2), slow)."""
B = len(samples)
W = B//2
yin = np.zeros(W)
for tau in range(1, W):
for j in range(W - tau):
yin[tau] += (samples[j] - samples[j+tau])**2
return yin
def sqd_yinfft(samples):
""" compute yinfft modified sum of squared differences
Very fast, improved performance in transients.
FIXME: biased."""
B = len(samples)
W = B//2
yin = np.zeros(W)
def hanningz(W):
return .5 * (1. - np.cos(2. * np.pi * np.arange(W) / W))
#win = np.ones(B)
win = hanningz(B)
sqrmag = np.zeros(B)
fftout = np.fft.fft(win*samples)
sqrmag[0] = fftout[0].real**2
for l in range(1, W):
sqrmag[l] = fftout[l].real**2 + fftout[l].imag**2
sqrmag[B-l] = sqrmag[l]
sqrmag[W] = fftout[W].real**2
fftout = np.fft.fft(sqrmag)
sqrsum = 2.*sqrmag[:W + 1].sum()
yin[0] = 0
yin[1:] = sqrsum - fftout.real[1:W]
return yin / B
def cumdiff(yin):
""" compute the cumulative mean normalized difference """
W = len(yin)
yin[0] = 1.
cumsum = 0.
for tau in range(1, W):
cumsum += yin[tau]
if cumsum != 0:
yin[tau] *= tau/cumsum
else:
yin[tau] = 1
return yin
def compute_all(x):
import time
now = time.time()
yin = sqd_yin(x)
t1 = time.time()
print ("yin took %.2fms" % ((t1-now) * 1000.))
yinfast = sqd_yinfast(x)
t2 = time.time()
print ("yinfast took: %.2fms" % ((t2-t1) * 1000.))
yintapered = sqd_yintapered(x)
t3 = time.time()
print ("yintapered took: %.2fms" % ((t3-t2) * 1000.))
yinfft = sqd_yinfft(x)
t4 = time.time()
print ("yinfft took: %.2fms" % ((t4-t3) * 1000.))
return yin, yinfast, yintapered, yinfft
def plot_all(yin, yinfast, yintapered, yinfft):
fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True, sharey='col')
axes[0, 0].plot(yin, label='yin')
axes[0, 0].plot(yintapered, label='yintapered')
axes[0, 0].set_ylim(bottom=0)
axes[0, 0].legend()
axes[1, 0].plot(yinfast, '-', label='yinfast')
axes[1, 0].plot(yinfft, label='yinfft')
axes[1, 0].legend()
axes[0, 1].plot(cumdiff(yin), label='yin')
axes[0, 1].plot(cumdiff(yintapered), label='yin tapered')
axes[0, 1].set_ylim(bottom=0)
axes[0, 1].legend()
axes[1, 1].plot(cumdiff(yinfast), '-', label='yinfast')
axes[1, 1].plot(cumdiff(yinfft), label='yinfft')
axes[1, 1].legend()
fig.tight_layout()
testfreqs = [441., 800., 10000., 40.]
if len(sys.argv) > 1:
testfreqs = map(float,sys.argv[1:])
for f in testfreqs:
print ("Comparing yin implementations for sine wave at %.fHz" % f)
samplerate = 44100.
win_s = 4096
x = np.cos(2.*np.pi * np.arange(win_s) * f / samplerate)
n_times = 1#00
for n in range(n_times):
yin, yinfast, yinfftslow, yinfft = compute_all(x)
if 0: # plot difference
plt.plot(yin-yinfast)
plt.tight_layout()
plt.show()
if 1:
plt.plot(yinfftslow-yinfft)
plt.tight_layout()
plt.show()
plot_all(yin, yinfast, yinfftslow, yinfft)
plt.show()
|
Gnatnaituy/leetcode | leetcode-java/src/others/easy/ltwenty/SortArrayByParity.java | <filename>leetcode-java/src/others/easy/ltwenty/SortArrayByParity.java
package others.easy.ltwenty;
/**
* 905 Sort Array by Parity
*/
public class SortArrayByParity {
private int[] sortArrayByParity(int[] A) {
int head = 0, tail = A.length - 1;
while (head < tail) {
if (A[head] % 2 == 1) {
while (A[tail] % 2 == 1 && tail >= head)
tail--;
if (head < tail) {
int temp = A[head];
A[head] = A[tail];
A[tail] = temp;
} else return A;
} else head++;
}
return A;
}
}
|
paviliondev/invoices | spec/views/payment_receivers/new.html.erb_spec.rb | require 'rails_helper'
RSpec.describe "payment_receivers/new", type: :view do
before(:each) do
assign(:payment_receiver, PaymentReceiver.new(
:payment_provider => nil,
:payment_type => 1,
:instructions => "MyString",
:currency => "MyString"
))
end
it "renders new payment_receiver form" do
render
assert_select "form[action=?][method=?]", payment_receivers_path, "post" do
assert_select "input[name=?]", "payment_receiver[payment_provider_id]"
assert_select "input[name=?]", "payment_receiver[payment_type]"
assert_select "input[name=?]", "payment_receiver[instructions]"
assert_select "input[name=?]", "payment_receiver[currency]"
end
end
end
|
danielogen/msc_research | selected projects/mobile/Signal-Android-4.60.5/app/src/main/java/org/thoughtcrime/securesms/preferences/widgets/ContactPreference.java | <filename>selected projects/mobile/Signal-Android-4.60.5/app/src/main/java/org/thoughtcrime/securesms/preferences/widgets/ContactPreference.java
package org.thoughtcrime.securesms.preferences.widgets;
import android.content.Context;
import android.graphics.PorterDuff;
import androidx.preference.Preference;
import androidx.preference.PreferenceViewHolder;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import org.thoughtcrime.securesms.R;
public class ContactPreference extends Preference {
private ImageView messageButton;
private ImageView callButton;
private ImageView secureCallButton;
private ImageView secureVideoButton;
private Listener listener;
private boolean secure;
private boolean blocked;
public ContactPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initialize();
}
public ContactPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initialize();
}
public ContactPreference(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
public ContactPreference(Context context) {
super(context);
initialize();
}
private void initialize() {
setWidgetLayoutResource(R.layout.recipient_preference_contact_widget);
}
@Override
public void onBindViewHolder(PreferenceViewHolder view) {
super.onBindViewHolder(view);
this.messageButton = (ImageView) view.findViewById(R.id.message);
this.callButton = (ImageView) view.findViewById(R.id.call);
this.secureCallButton = (ImageView) view.findViewById(R.id.secure_call);
this.secureVideoButton = (ImageView) view.findViewById(R.id.secure_video);
if (listener != null) setListener(listener);
setState(secure, blocked);
}
public void setState(boolean secure, boolean blocked) {
this.secure = secure;
if (secureCallButton != null) secureCallButton.setVisibility(secure && !blocked ? View.VISIBLE : View.GONE);
if (secureVideoButton != null) secureVideoButton.setVisibility(secure && !blocked ? View.VISIBLE : View.GONE);
if (callButton != null) callButton.setVisibility(secure || blocked ? View.GONE : View.VISIBLE);
if (messageButton != null) messageButton.setVisibility(blocked ? View.GONE : View.VISIBLE);
int color;
if (secure) {
color = getContext().getResources().getColor(R.color.core_ultramarine);
} else {
color = getContext().getResources().getColor(R.color.grey_600);
}
if (messageButton != null) messageButton.setColorFilter(color, PorterDuff.Mode.SRC_IN);
if (secureCallButton != null) secureCallButton.setColorFilter(color, PorterDuff.Mode.SRC_IN);
if (secureVideoButton != null) secureVideoButton.setColorFilter(color, PorterDuff.Mode.SRC_IN);
if (callButton != null) callButton.setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
public void setListener(Listener listener) {
this.listener = listener;
if (this.messageButton != null) this.messageButton.setOnClickListener(v -> listener.onMessageClicked());
if (this.secureCallButton != null) this.secureCallButton.setOnClickListener(v -> listener.onSecureCallClicked());
if (this.secureVideoButton != null) this.secureVideoButton.setOnClickListener(v -> listener.onSecureVideoClicked());
if (this.callButton != null) this.callButton.setOnClickListener(v -> listener.onInSecureCallClicked());
}
public interface Listener {
public void onMessageClicked();
public void onSecureCallClicked();
public void onSecureVideoClicked();
public void onInSecureCallClicked();
}
}
|
dcui/FreeBSD-9.3_kernel | sys/dev/nxge/include/xgehal-types.h | /*-
* Copyright (c) 2002-2007 Neterion, 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:
* 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 AUTHOR 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 AUTHOR 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.
*
* $FreeBSD: releng/9.3/sys/dev/nxge/include/xgehal-types.h 173139 2007-10-29 14:19:32Z rwatson $
*/
#ifndef XGE_HAL_TYPES_H
#define XGE_HAL_TYPES_H
#include <dev/nxge/include/xge-os-pal.h>
__EXTERN_BEGIN_DECLS
/*
* BIT(loc) - set bit at offset
*/
#define BIT(loc) (0x8000000000000000ULL >> (loc))
/*
* vBIT(val, loc, sz) - set bits at offset
*/
#define vBIT(val, loc, sz) (((u64)(val)) << (64-(loc)-(sz)))
#define vBIT32(val, loc, sz) (((u32)(val)) << (32-(loc)-(sz)))
/*
* bVALx(bits, loc) - Get the value of x bits at location
*/
#define bVAL1(bits, loc) ((((u64)bits) >> (64-(loc+1))) & 0x1)
#define bVAL2(bits, loc) ((((u64)bits) >> (64-(loc+2))) & 0x3)
#define bVAL3(bits, loc) ((((u64)bits) >> (64-(loc+3))) & 0x7)
#define bVAL4(bits, loc) ((((u64)bits) >> (64-(loc+4))) & 0xF)
#define bVAL5(bits, loc) ((((u64)bits) >> (64-(loc+5))) & 0x1F)
#define bVAL6(bits, loc) ((((u64)bits) >> (64-(loc+6))) & 0x3F)
#define bVAL7(bits, loc) ((((u64)bits) >> (64-(loc+7))) & 0x7F)
#define bVAL8(bits, loc) ((((u64)bits) >> (64-(loc+8))) & 0xFF)
#define bVAL12(bits, loc) ((((u64)bits) >> (64-(loc+12))) & 0xFFF)
#define bVAL14(bits, loc) ((((u64)bits) >> (64-(loc+14))) & 0x3FFF)
#define bVAL16(bits, loc) ((((u64)bits) >> (64-(loc+16))) & 0xFFFF)
#define bVAL20(bits, loc) ((((u64)bits) >> (64-(loc+20))) & 0xFFFFF)
#define bVAL22(bits, loc) ((((u64)bits) >> (64-(loc+22))) & 0x3FFFFF)
#define bVAL24(bits, loc) ((((u64)bits) >> (64-(loc+24))) & 0xFFFFFF)
#define bVAL28(bits, loc) ((((u64)bits) >> (64-(loc+28))) & 0xFFFFFFF)
#define bVAL32(bits, loc) ((((u64)bits) >> (64-(loc+32))) & 0xFFFFFFFF)
#define bVAL36(bits, loc) ((((u64)bits) >> (64-(loc+36))) & 0xFFFFFFFFF)
#define bVAL40(bits, loc) ((((u64)bits) >> (64-(loc+40))) & 0xFFFFFFFFFF)
#define bVAL44(bits, loc) ((((u64)bits) >> (64-(loc+44))) & 0xFFFFFFFFFFF)
#define bVAL48(bits, loc) ((((u64)bits) >> (64-(loc+48))) & 0xFFFFFFFFFFFF)
#define bVAL52(bits, loc) ((((u64)bits) >> (64-(loc+52))) & 0xFFFFFFFFFFFFF)
#define bVAL56(bits, loc) ((((u64)bits) >> (64-(loc+56))) & 0xFFFFFFFFFFFFFF)
#define bVAL60(bits, loc) ((((u64)bits) >> (64-(loc+60))) & 0xFFFFFFFFFFFFFFF)
#define XGE_HAL_BASE_INF 100
#define XGE_HAL_BASE_ERR 200
#define XGE_HAL_BASE_BADCFG 300
#define XGE_HAL_ALL_FOXES 0xFFFFFFFFFFFFFFFFULL
/**
* enum xge_hal_status_e - HAL return codes.
* @XGE_HAL_OK: Success.
* @XGE_HAL_FAIL: Failure.
* @XGE_HAL_COMPLETIONS_REMAIN: There are more completions on a channel.
* (specific to polling mode completion processing).
* @XGE_HAL_INF_NO_MORE_COMPLETED_DESCRIPTORS: No more completed
* descriptors. See xge_hal_fifo_dtr_next_completed().
* @XGE_HAL_INF_OUT_OF_DESCRIPTORS: Out of descriptors. Channel
* descriptors
* are reserved (via xge_hal_fifo_dtr_reserve(),
* xge_hal_fifo_dtr_reserve())
* and not yet freed (via xge_hal_fifo_dtr_free(),
* xge_hal_ring_dtr_free()).
* @XGE_HAL_INF_CHANNEL_IS_NOT_READY: Channel is not ready for
* operation.
* @XGE_HAL_INF_MEM_STROBE_CMD_EXECUTING: Indicates that host needs to
* poll until PIO is executed.
* @XGE_HAL_INF_STATS_IS_NOT_READY: Cannot retrieve statistics because
* HAL and/or device is not yet initialized.
* @XGE_HAL_INF_NO_MORE_FREED_DESCRIPTORS: No descriptors left to
* reserve. Internal use only.
* @XGE_HAL_INF_IRQ_POLLING_CONTINUE: Returned by the ULD channel
* callback when instructed to exit descriptor processing loop
* prematurely. Typical usage: polling mode of processing completed
* descriptors.
* Upon getting LRO_ISED, ll driver shall
* 1) initialise lro struct with mbuf if sg_num == 1.
* 2) else it will update m_data_ptr_of_mbuf to tcp pointer and
* append the new mbuf to the tail of mbuf chain in lro struct.
*
* @XGE_HAL_INF_LRO_BEGIN: Returned by ULD LRO module, when new LRO is
* being initiated.
* @XGE_HAL_INF_LRO_CONT: Returned by ULD LRO module, when new frame
* is appended at the end of existing LRO.
* @XGE_HAL_INF_LRO_UNCAPABLE: Returned by ULD LRO module, when new
* frame is not LRO capable.
* @XGE_HAL_INF_LRO_END_1: Returned by ULD LRO module, when new frame
* triggers LRO flush.
* @XGE_HAL_INF_LRO_END_2: Returned by ULD LRO module, when new
* frame triggers LRO flush. Lro frame should be flushed first then
* new frame should be flushed next.
* @XGE_HAL_INF_LRO_END_3: Returned by ULD LRO module, when new
* frame triggers close of current LRO session and opening of new LRO session
* with the frame.
* @XGE_HAL_INF_LRO_SESSIONS_XCDED: Returned by ULD LRO module, when no
* more LRO sessions can be added.
* @XGE_HAL_INF_NOT_ENOUGH_HW_CQES: TBD
* @XGE_HAL_ERR_DRIVER_NOT_INITIALIZED: HAL is not initialized.
* @XGE_HAL_ERR_OUT_OF_MEMORY: Out of memory (example, when and
* allocating descriptors).
* @XGE_HAL_ERR_CHANNEL_NOT_FOUND: xge_hal_channel_open will return this
* error if corresponding channel is not configured.
* @XGE_HAL_ERR_WRONG_IRQ: Returned by HAL's ISR when the latter is
* invoked not because of the Xframe-generated interrupt.
* @XGE_HAL_ERR_OUT_OF_MAC_ADDRESSES: Returned when user tries to
* configure more than XGE_HAL_MAX_MAC_ADDRESSES mac addresses.
* @XGE_HAL_ERR_BAD_DEVICE_ID: Unknown device PCI ID.
* @XGE_HAL_ERR_OUT_ALIGNED_FRAGS: Too many unaligned fragments
* in a scatter-gather list.
* @XGE_HAL_ERR_DEVICE_NOT_INITIALIZED: Device is not initialized.
* Typically means wrong sequence of API calls.
* @XGE_HAL_ERR_SWAPPER_CTRL: Error during device initialization: failed
* to set Xframe byte swapper in accordnace with the host
* endian-ness.
* @XGE_HAL_ERR_DEVICE_IS_NOT_QUIESCENT: Failed to restore the device to
* a "quiescent" state.
* @XGE_HAL_ERR_INVALID_MTU_SIZE: Returned when MTU size specified by
* caller is not in the (64, 9600) range.
* @XGE_HAL_ERR_OUT_OF_MAPPING: Failed to map DMA-able memory.
* @XGE_HAL_ERR_BAD_SUBSYSTEM_ID: Bad PCI subsystem ID. (Currently we
* check for zero/non-zero only.)
* @XGE_HAL_ERR_INVALID_BAR_ID: Invalid BAR ID. Xframe supports two Base
* Address Register Spaces: BAR0 (id=0) and BAR1 (id=1).
* @XGE_HAL_ERR_INVALID_OFFSET: Invalid offset. Example, attempt to read
* register value (with offset) outside of the BAR0 space.
* @XGE_HAL_ERR_INVALID_DEVICE: Invalid device. The HAL device handle
* (passed by ULD) is invalid.
* @XGE_HAL_ERR_OUT_OF_SPACE: Out-of-provided-buffer-space. Returned by
* management "get" routines when the retrieved information does
* not fit into the provided buffer.
* @XGE_HAL_ERR_INVALID_VALUE_BIT_SIZE: Invalid bit size.
* @XGE_HAL_ERR_VERSION_CONFLICT: Upper-layer driver and HAL (versions)
* are not compatible.
* @XGE_HAL_ERR_INVALID_MAC_ADDRESS: Invalid MAC address.
* @XGE_HAL_ERR_SPDM_NOT_ENABLED: SPDM support is not enabled.
* @XGE_HAL_ERR_SPDM_TABLE_FULL: SPDM table is full.
* @XGE_HAL_ERR_SPDM_INVALID_ENTRY: Invalid SPDM entry.
* @XGE_HAL_ERR_SPDM_ENTRY_NOT_FOUND: Unable to locate the entry in the
* SPDM table.
* @XGE_HAL_ERR_SPDM_TABLE_DATA_INCONSISTENT: Local SPDM table is not in
* synch ith the actual one.
* @XGE_HAL_ERR_INVALID_PCI_INFO: Invalid or unrecognized PCI frequency,
* and or width, and or mode (Xframe-II only, see UG on PCI_INFO register).
* @XGE_HAL_ERR_CRITICAL: Critical error. Returned by HAL APIs
* (including xge_hal_device_handle_tcode()) on: ECC, parity, SERR.
* Also returned when PIO read does not go through ("all-foxes")
* because of "slot-freeze".
* @XGE_HAL_ERR_RESET_FAILED: Failed to soft-reset the device.
* Returned by xge_hal_device_reset(). One circumstance when it could
* happen: slot freeze by the system (see @XGE_HAL_ERR_CRITICAL).
* @XGE_HAL_ERR_TOO_MANY: This error is returned if there were laready
* maximum number of sessions or queues allocated
* @XGE_HAL_ERR_PKT_DROP: TBD
* @XGE_HAL_BADCFG_TX_URANGE_A: Invalid Tx link utilization range A. See
* the structure xge_hal_tti_config_t{} for valid values.
* @XGE_HAL_BADCFG_TX_UFC_A: Invalid frame count for Tx link utilization
* range A. See the structure xge_hal_tti_config_t{} for valid values.
* @XGE_HAL_BADCFG_TX_URANGE_B: Invalid Tx link utilization range B. See
* the structure xge_hal_tti_config_t{} for valid values.
* @XGE_HAL_BADCFG_TX_UFC_B: Invalid frame count for Tx link utilization
* range B. See the strucuture xge_hal_tti_config_t{} for valid values.
* @XGE_HAL_BADCFG_TX_URANGE_C: Invalid Tx link utilization range C. See
* the structure xge_hal_tti_config_t{} for valid values.
* @XGE_HAL_BADCFG_TX_UFC_C: Invalid frame count for Tx link utilization
* range C. See the structure xge_hal_tti_config_t{} for valid values.
* @XGE_HAL_BADCFG_TX_UFC_D: Invalid frame count for Tx link utilization
* range D. See the structure xge_hal_tti_config_t{} for valid values.
* @XGE_HAL_BADCFG_TX_TIMER_VAL: Invalid Tx timer value. See the
* structure xge_hal_tti_config_t{} for valid values.
* @XGE_HAL_BADCFG_TX_TIMER_CI_EN: Invalid Tx timer continuous interrupt
* enable. See the structure xge_hal_tti_config_t{} for valid values.
* @XGE_HAL_BADCFG_RX_URANGE_A: Invalid Rx link utilization range A. See
* the structure xge_hal_rti_config_t{} for valid values.
* @XGE_HAL_BADCFG_RX_UFC_A: Invalid frame count for Rx link utilization
* range A. See the structure xge_hal_rti_config_t{} for valid values.
* @XGE_HAL_BADCFG_RX_URANGE_B: Invalid Rx link utilization range B. See
* the structure xge_hal_rti_config_t{} for valid values.
* @XGE_HAL_BADCFG_RX_UFC_B: Invalid frame count for Rx link utilization
* range B. See the structure xge_hal_rti_config_t{} for valid values.
* @XGE_HAL_BADCFG_RX_URANGE_C: Invalid Rx link utilization range C. See
* the structure xge_hal_rti_config_t{} for valid values.
* @XGE_HAL_BADCFG_RX_UFC_C: Invalid frame count for Rx link utilization
* range C. See the structure xge_hal_rti_config_t{} for valid values.
* @XGE_HAL_BADCFG_RX_UFC_D: Invalid frame count for Rx link utilization
* range D. See the structure xge_hal_rti_config_t{} for valid values.
* @XGE_HAL_BADCFG_RX_TIMER_VAL: Invalid Rx timer value. See the
* structure xge_hal_rti_config_t{} for valid values.
* @XGE_HAL_BADCFG_FIFO_QUEUE_INITIAL_LENGTH: Invalid initial fifo queue
* length. See the structure xge_hal_fifo_queue_t for valid values.
* @XGE_HAL_BADCFG_FIFO_QUEUE_MAX_LENGTH: Invalid fifo queue max length.
* See the structure xge_hal_fifo_queue_t for valid values.
* @XGE_HAL_BADCFG_FIFO_QUEUE_INTR: Invalid fifo queue interrupt mode.
* See the structure xge_hal_fifo_queue_t for valid values.
* @XGE_HAL_BADCFG_RING_QUEUE_INITIAL_BLOCKS: Invalid Initial number of
* RxD blocks for the ring. See the structure xge_hal_ring_queue_t for
* valid values.
* @XGE_HAL_BADCFG_RING_QUEUE_MAX_BLOCKS: Invalid maximum number of RxD
* blocks for the ring. See the structure xge_hal_ring_queue_t for
* valid values.
* @XGE_HAL_BADCFG_RING_QUEUE_BUFFER_MODE: Invalid ring buffer mode. See
* the structure xge_hal_ring_queue_t for valid values.
* @XGE_HAL_BADCFG_RING_QUEUE_SIZE: Invalid ring queue size. See the
* structure xge_hal_ring_queue_t for valid values.
* @XGE_HAL_BADCFG_BACKOFF_INTERVAL_US: Invalid backoff timer interval
* for the ring. See the structure xge_hal_ring_queue_t for valid values.
* @XGE_HAL_BADCFG_MAX_FRM_LEN: Invalid ring max frame length. See the
* structure xge_hal_ring_queue_t for valid values.
* @XGE_HAL_BADCFG_RING_PRIORITY: Invalid ring priority. See the
* structure xge_hal_ring_queue_t for valid values.
* @XGE_HAL_BADCFG_TMAC_UTIL_PERIOD: Invalid tmac util period. See the
* structure xge_hal_mac_config_t{} for valid values.
* @XGE_HAL_BADCFG_RMAC_UTIL_PERIOD: Invalid rmac util period. See the
* structure xge_hal_mac_config_t{} for valid values.
* @XGE_HAL_BADCFG_RMAC_BCAST_EN: Invalid rmac brodcast enable. See the
* structure xge_hal_mac_config_t{} for valid values.
* @XGE_HAL_BADCFG_RMAC_HIGH_PTIME: Invalid rmac pause time. See the
* structure xge_hal_mac_config_t{} for valid values.
* @XGE_HAL_BADCFG_MC_PAUSE_THRESHOLD_Q0Q3: Invalid threshold for pause
* frame generation for queues 0 through 3. See the structure
* xge_hal_mac_config_t{} for valid values.
* @XGE_HAL_BADCFG_MC_PAUSE_THRESHOLD_Q4Q7:Invalid threshold for pause
* frame generation for queues 4 through 7. See the structure
* xge_hal_mac_config_t{} for valid values.
* @XGE_HAL_BADCFG_FIFO_FRAGS: Invalid fifo max fragments length. See
* the structure xge_hal_fifo_config_t{} for valid values.
* @XGE_HAL_BADCFG_FIFO_RESERVE_THRESHOLD: Invalid fifo reserve
* threshold. See the structure xge_hal_fifo_config_t{} for valid values.
* @XGE_HAL_BADCFG_FIFO_MEMBLOCK_SIZE: Invalid fifo descriptors memblock
* size. See the structure xge_hal_fifo_config_t{} for valid values.
* @XGE_HAL_BADCFG_RING_MEMBLOCK_SIZE: Invalid ring descriptors memblock
* size. See the structure xge_hal_ring_config_t{} for valid values.
* @XGE_HAL_BADCFG_MAX_MTU: Invalid max mtu for the device. See the
* structure xge_hal_device_config_t{} for valid values.
* @XGE_HAL_BADCFG_ISR_POLLING_CNT: Invalid isr polling count. See the
* structure xge_hal_device_config_t{} for valid values.
* @XGE_HAL_BADCFG_LATENCY_TIMER: Invalid Latency timer. See the
* structure xge_hal_device_config_t{} for valid values.
* @XGE_HAL_BADCFG_MAX_SPLITS_TRANS: Invalid maximum number of pci-x
* split transactions. See the structure xge_hal_device_config_t{} for valid
* values.
* @XGE_HAL_BADCFG_MMRB_COUNT: Invalid mmrb count. See the structure
* xge_hal_device_config_t{} for valid values.
* @XGE_HAL_BADCFG_SHARED_SPLITS: Invalid number of outstanding split
* transactions that is shared by Tx and Rx requests. See the structure
* xge_hal_device_config_t{} for valid values.
* @XGE_HAL_BADCFG_STATS_REFRESH_TIME: Invalid time interval for
* automatic statistics transfer to the host. See the structure
* xge_hal_device_config_t{} for valid values.
* @XGE_HAL_BADCFG_PCI_FREQ_MHERZ: Invalid pci clock frequency. See the
* structure xge_hal_device_config_t{} for valid values.
* @XGE_HAL_BADCFG_PCI_MODE: Invalid pci mode. See the structure
* xge_hal_device_config_t{} for valid values.
* @XGE_HAL_BADCFG_INTR_MODE: Invalid interrupt mode. See the structure
* xge_hal_device_config_t{} for valid values.
* @XGE_HAL_BADCFG_SCHED_TIMER_US: Invalid scheduled timer interval to
* generate interrupt. See the structure xge_hal_device_config_t{}
* for valid values.
* @XGE_HAL_BADCFG_SCHED_TIMER_ON_SHOT: Invalid scheduled timer one
* shot. See the structure xge_hal_device_config_t{} for valid values.
* @XGE_HAL_BADCFG_QUEUE_SIZE_INITIAL: Invalid driver queue initial
* size. See the structure xge_hal_driver_config_t{} for valid values.
* @XGE_HAL_BADCFG_QUEUE_SIZE_MAX: Invalid driver queue max size. See
* the structure xge_hal_driver_config_t{} for valid values.
* @XGE_HAL_BADCFG_RING_RTH_EN: Invalid value of RTH-enable. See
* the structure xge_hal_ring_queue_t for valid values.
* @XGE_HAL_BADCFG_RING_INDICATE_MAX_PKTS: Invalid value configured for
* indicate_max_pkts variable.
* @XGE_HAL_BADCFG_TX_TIMER_AC_EN: Invalid value for Tx timer
* auto-cancel. See xge_hal_tti_config_t{}.
* @XGE_HAL_BADCFG_RX_TIMER_AC_EN: Invalid value for Rx timer
* auto-cancel. See xge_hal_rti_config_t{}.
* @XGE_HAL_BADCFG_RXUFCA_INTR_THRES: TODO
* @XGE_HAL_BADCFG_RXUFCA_LO_LIM: TODO
* @XGE_HAL_BADCFG_RXUFCA_HI_LIM: TODO
* @XGE_HAL_BADCFG_RXUFCA_LBOLT_PERIOD: TODO
* @XGE_HAL_BADCFG_TRACEBUF_SIZE: Bad configuration: the size of the circular
* (in memory) trace buffer either too large or too small. See the
* the corresponding header file or README for the acceptable range.
* @XGE_HAL_BADCFG_LINK_VALID_CNT: Bad configuration: the link-valid
* counter cannot have the specified value. Note that the link-valid
* counting is done only at device-open time, to determine with the
* specified certainty that the link is up. See the
* the corresponding header file or README for the acceptable range.
* See also @XGE_HAL_BADCFG_LINK_RETRY_CNT.
* @XGE_HAL_BADCFG_LINK_RETRY_CNT: Bad configuration: the specified
* link-up retry count is out of the valid range. Note that the link-up
* retry counting is done only at device-open time.
* See also xge_hal_device_config_t{}.
* @XGE_HAL_BADCFG_LINK_STABILITY_PERIOD: Invalid link stability period.
* @XGE_HAL_BADCFG_DEVICE_POLL_MILLIS: Invalid device poll interval.
* @XGE_HAL_BADCFG_RMAC_PAUSE_GEN_EN: TBD
* @XGE_HAL_BADCFG_RMAC_PAUSE_RCV_EN: TBD
* @XGE_HAL_BADCFG_MEDIA: TBD
* @XGE_HAL_BADCFG_NO_ISR_EVENTS: TBD
* See the structure xge_hal_device_config_t{} for valid values.
* @XGE_HAL_EOF_TRACE_BUF: End of the circular (in memory) trace buffer.
* Returned by xge_hal_mgmt_trace_read(), when user tries to read the trace
* past the buffer limits. Used to enable user to load the trace in two
* or more reads.
* @XGE_HAL_BADCFG_RING_RTS_MAC_EN: Invalid value of RTS_MAC_EN enable. See
* the structure xge_hal_ring_queue_t for valid values.
* @XGE_HAL_BADCFG_LRO_SG_SIZE : Invalid value of LRO scatter gatter size.
* See the structure xge_hal_device_config_t for valid values.
* @XGE_HAL_BADCFG_LRO_FRM_LEN : Invalid value of LRO frame length.
* See the structure xge_hal_device_config_t for valid values.
* @XGE_HAL_BADCFG_WQE_NUM_ODS: TBD
* @XGE_HAL_BADCFG_BIMODAL_INTR: Invalid value to configure bimodal interrupts
* Enumerates status and error codes returned by HAL public
* API functions.
* @XGE_HAL_BADCFG_BIMODAL_TIMER_LO_US: TBD
* @XGE_HAL_BADCFG_BIMODAL_TIMER_HI_US: TBD
* @XGE_HAL_BADCFG_BIMODAL_XENA_NOT_ALLOWED: TBD
* @XGE_HAL_BADCFG_RTS_QOS_EN: TBD
* @XGE_HAL_BADCFG_FIFO_QUEUE_INTR_VECTOR: TBD
* @XGE_HAL_BADCFG_RING_QUEUE_INTR_VECTOR: TBD
* @XGE_HAL_BADCFG_RTS_PORT_EN: TBD
* @XGE_HAL_BADCFG_RING_RTS_PORT_EN: TBD
*
*/
typedef enum xge_hal_status_e {
XGE_HAL_OK = 0,
XGE_HAL_FAIL = 1,
XGE_HAL_COMPLETIONS_REMAIN = 2,
XGE_HAL_INF_NO_MORE_COMPLETED_DESCRIPTORS = XGE_HAL_BASE_INF + 1,
XGE_HAL_INF_OUT_OF_DESCRIPTORS = XGE_HAL_BASE_INF + 2,
XGE_HAL_INF_CHANNEL_IS_NOT_READY = XGE_HAL_BASE_INF + 3,
XGE_HAL_INF_MEM_STROBE_CMD_EXECUTING = XGE_HAL_BASE_INF + 4,
XGE_HAL_INF_STATS_IS_NOT_READY = XGE_HAL_BASE_INF + 5,
XGE_HAL_INF_NO_MORE_FREED_DESCRIPTORS = XGE_HAL_BASE_INF + 6,
XGE_HAL_INF_IRQ_POLLING_CONTINUE = XGE_HAL_BASE_INF + 7,
XGE_HAL_INF_LRO_BEGIN = XGE_HAL_BASE_INF + 8,
XGE_HAL_INF_LRO_CONT = XGE_HAL_BASE_INF + 9,
XGE_HAL_INF_LRO_UNCAPABLE = XGE_HAL_BASE_INF + 10,
XGE_HAL_INF_LRO_END_1 = XGE_HAL_BASE_INF + 11,
XGE_HAL_INF_LRO_END_2 = XGE_HAL_BASE_INF + 12,
XGE_HAL_INF_LRO_END_3 = XGE_HAL_BASE_INF + 13,
XGE_HAL_INF_LRO_SESSIONS_XCDED = XGE_HAL_BASE_INF + 14,
XGE_HAL_INF_NOT_ENOUGH_HW_CQES = XGE_HAL_BASE_INF + 15,
XGE_HAL_ERR_DRIVER_NOT_INITIALIZED = XGE_HAL_BASE_ERR + 1,
XGE_HAL_ERR_OUT_OF_MEMORY = XGE_HAL_BASE_ERR + 4,
XGE_HAL_ERR_CHANNEL_NOT_FOUND = XGE_HAL_BASE_ERR + 5,
XGE_HAL_ERR_WRONG_IRQ = XGE_HAL_BASE_ERR + 6,
XGE_HAL_ERR_OUT_OF_MAC_ADDRESSES = XGE_HAL_BASE_ERR + 7,
XGE_HAL_ERR_SWAPPER_CTRL = XGE_HAL_BASE_ERR + 8,
XGE_HAL_ERR_DEVICE_IS_NOT_QUIESCENT = XGE_HAL_BASE_ERR + 9,
XGE_HAL_ERR_INVALID_MTU_SIZE = XGE_HAL_BASE_ERR + 10,
XGE_HAL_ERR_OUT_OF_MAPPING = XGE_HAL_BASE_ERR + 11,
XGE_HAL_ERR_BAD_SUBSYSTEM_ID = XGE_HAL_BASE_ERR + 12,
XGE_HAL_ERR_INVALID_BAR_ID = XGE_HAL_BASE_ERR + 13,
XGE_HAL_ERR_INVALID_OFFSET = XGE_HAL_BASE_ERR + 14,
XGE_HAL_ERR_INVALID_DEVICE = XGE_HAL_BASE_ERR + 15,
XGE_HAL_ERR_OUT_OF_SPACE = XGE_HAL_BASE_ERR + 16,
XGE_HAL_ERR_INVALID_VALUE_BIT_SIZE = XGE_HAL_BASE_ERR + 17,
XGE_HAL_ERR_VERSION_CONFLICT = XGE_HAL_BASE_ERR + 18,
XGE_HAL_ERR_INVALID_MAC_ADDRESS = XGE_HAL_BASE_ERR + 19,
XGE_HAL_ERR_BAD_DEVICE_ID = XGE_HAL_BASE_ERR + 20,
XGE_HAL_ERR_OUT_ALIGNED_FRAGS = XGE_HAL_BASE_ERR + 21,
XGE_HAL_ERR_DEVICE_NOT_INITIALIZED = XGE_HAL_BASE_ERR + 22,
XGE_HAL_ERR_SPDM_NOT_ENABLED = XGE_HAL_BASE_ERR + 23,
XGE_HAL_ERR_SPDM_TABLE_FULL = XGE_HAL_BASE_ERR + 24,
XGE_HAL_ERR_SPDM_INVALID_ENTRY = XGE_HAL_BASE_ERR + 25,
XGE_HAL_ERR_SPDM_ENTRY_NOT_FOUND = XGE_HAL_BASE_ERR + 26,
XGE_HAL_ERR_SPDM_TABLE_DATA_INCONSISTENT= XGE_HAL_BASE_ERR + 27,
XGE_HAL_ERR_INVALID_PCI_INFO = XGE_HAL_BASE_ERR + 28,
XGE_HAL_ERR_CRITICAL = XGE_HAL_BASE_ERR + 29,
XGE_HAL_ERR_RESET_FAILED = XGE_HAL_BASE_ERR + 30,
XGE_HAL_ERR_TOO_MANY = XGE_HAL_BASE_ERR + 32,
XGE_HAL_ERR_PKT_DROP = XGE_HAL_BASE_ERR + 33,
XGE_HAL_BADCFG_TX_URANGE_A = XGE_HAL_BASE_BADCFG + 1,
XGE_HAL_BADCFG_TX_UFC_A = XGE_HAL_BASE_BADCFG + 2,
XGE_HAL_BADCFG_TX_URANGE_B = XGE_HAL_BASE_BADCFG + 3,
XGE_HAL_BADCFG_TX_UFC_B = XGE_HAL_BASE_BADCFG + 4,
XGE_HAL_BADCFG_TX_URANGE_C = XGE_HAL_BASE_BADCFG + 5,
XGE_HAL_BADCFG_TX_UFC_C = XGE_HAL_BASE_BADCFG + 6,
XGE_HAL_BADCFG_TX_UFC_D = XGE_HAL_BASE_BADCFG + 8,
XGE_HAL_BADCFG_TX_TIMER_VAL = XGE_HAL_BASE_BADCFG + 9,
XGE_HAL_BADCFG_TX_TIMER_CI_EN = XGE_HAL_BASE_BADCFG + 10,
XGE_HAL_BADCFG_RX_URANGE_A = XGE_HAL_BASE_BADCFG + 11,
XGE_HAL_BADCFG_RX_UFC_A = XGE_HAL_BASE_BADCFG + 12,
XGE_HAL_BADCFG_RX_URANGE_B = XGE_HAL_BASE_BADCFG + 13,
XGE_HAL_BADCFG_RX_UFC_B = XGE_HAL_BASE_BADCFG + 14,
XGE_HAL_BADCFG_RX_URANGE_C = XGE_HAL_BASE_BADCFG + 15,
XGE_HAL_BADCFG_RX_UFC_C = XGE_HAL_BASE_BADCFG + 16,
XGE_HAL_BADCFG_RX_UFC_D = XGE_HAL_BASE_BADCFG + 17,
XGE_HAL_BADCFG_RX_TIMER_VAL = XGE_HAL_BASE_BADCFG + 18,
XGE_HAL_BADCFG_FIFO_QUEUE_INITIAL_LENGTH= XGE_HAL_BASE_BADCFG + 19,
XGE_HAL_BADCFG_FIFO_QUEUE_MAX_LENGTH = XGE_HAL_BASE_BADCFG + 20,
XGE_HAL_BADCFG_FIFO_QUEUE_INTR = XGE_HAL_BASE_BADCFG + 21,
XGE_HAL_BADCFG_RING_QUEUE_INITIAL_BLOCKS=XGE_HAL_BASE_BADCFG + 22,
XGE_HAL_BADCFG_RING_QUEUE_MAX_BLOCKS = XGE_HAL_BASE_BADCFG + 23,
XGE_HAL_BADCFG_RING_QUEUE_BUFFER_MODE = XGE_HAL_BASE_BADCFG + 24,
XGE_HAL_BADCFG_RING_QUEUE_SIZE = XGE_HAL_BASE_BADCFG + 25,
XGE_HAL_BADCFG_BACKOFF_INTERVAL_US = XGE_HAL_BASE_BADCFG + 26,
XGE_HAL_BADCFG_MAX_FRM_LEN = XGE_HAL_BASE_BADCFG + 27,
XGE_HAL_BADCFG_RING_PRIORITY = XGE_HAL_BASE_BADCFG + 28,
XGE_HAL_BADCFG_TMAC_UTIL_PERIOD = XGE_HAL_BASE_BADCFG + 29,
XGE_HAL_BADCFG_RMAC_UTIL_PERIOD = XGE_HAL_BASE_BADCFG + 30,
XGE_HAL_BADCFG_RMAC_BCAST_EN = XGE_HAL_BASE_BADCFG + 31,
XGE_HAL_BADCFG_RMAC_HIGH_PTIME = XGE_HAL_BASE_BADCFG + 32,
XGE_HAL_BADCFG_MC_PAUSE_THRESHOLD_Q0Q3 = XGE_HAL_BASE_BADCFG +33,
XGE_HAL_BADCFG_MC_PAUSE_THRESHOLD_Q4Q7 = XGE_HAL_BASE_BADCFG + 34,
XGE_HAL_BADCFG_FIFO_FRAGS = XGE_HAL_BASE_BADCFG + 35,
XGE_HAL_BADCFG_FIFO_RESERVE_THRESHOLD = XGE_HAL_BASE_BADCFG + 37,
XGE_HAL_BADCFG_FIFO_MEMBLOCK_SIZE = XGE_HAL_BASE_BADCFG + 38,
XGE_HAL_BADCFG_RING_MEMBLOCK_SIZE = XGE_HAL_BASE_BADCFG + 39,
XGE_HAL_BADCFG_MAX_MTU = XGE_HAL_BASE_BADCFG + 40,
XGE_HAL_BADCFG_ISR_POLLING_CNT = XGE_HAL_BASE_BADCFG + 41,
XGE_HAL_BADCFG_LATENCY_TIMER = XGE_HAL_BASE_BADCFG + 42,
XGE_HAL_BADCFG_MAX_SPLITS_TRANS = XGE_HAL_BASE_BADCFG + 43,
XGE_HAL_BADCFG_MMRB_COUNT = XGE_HAL_BASE_BADCFG + 44,
XGE_HAL_BADCFG_SHARED_SPLITS = XGE_HAL_BASE_BADCFG + 45,
XGE_HAL_BADCFG_STATS_REFRESH_TIME = XGE_HAL_BASE_BADCFG + 46,
XGE_HAL_BADCFG_PCI_FREQ_MHERZ = XGE_HAL_BASE_BADCFG + 47,
XGE_HAL_BADCFG_PCI_MODE = XGE_HAL_BASE_BADCFG + 48,
XGE_HAL_BADCFG_INTR_MODE = XGE_HAL_BASE_BADCFG + 49,
XGE_HAL_BADCFG_SCHED_TIMER_US = XGE_HAL_BASE_BADCFG + 50,
XGE_HAL_BADCFG_SCHED_TIMER_ON_SHOT = XGE_HAL_BASE_BADCFG + 51,
XGE_HAL_BADCFG_QUEUE_SIZE_INITIAL = XGE_HAL_BASE_BADCFG + 52,
XGE_HAL_BADCFG_QUEUE_SIZE_MAX = XGE_HAL_BASE_BADCFG + 53,
XGE_HAL_BADCFG_RING_RTH_EN = XGE_HAL_BASE_BADCFG + 54,
XGE_HAL_BADCFG_RING_INDICATE_MAX_PKTS = XGE_HAL_BASE_BADCFG + 55,
XGE_HAL_BADCFG_TX_TIMER_AC_EN = XGE_HAL_BASE_BADCFG + 56,
XGE_HAL_BADCFG_RX_TIMER_AC_EN = XGE_HAL_BASE_BADCFG + 57,
XGE_HAL_BADCFG_RXUFCA_INTR_THRES = XGE_HAL_BASE_BADCFG + 58,
XGE_HAL_BADCFG_RXUFCA_LO_LIM = XGE_HAL_BASE_BADCFG + 59,
XGE_HAL_BADCFG_RXUFCA_HI_LIM = XGE_HAL_BASE_BADCFG + 60,
XGE_HAL_BADCFG_RXUFCA_LBOLT_PERIOD = XGE_HAL_BASE_BADCFG + 61,
XGE_HAL_BADCFG_TRACEBUF_SIZE = XGE_HAL_BASE_BADCFG + 62,
XGE_HAL_BADCFG_LINK_VALID_CNT = XGE_HAL_BASE_BADCFG + 63,
XGE_HAL_BADCFG_LINK_RETRY_CNT = XGE_HAL_BASE_BADCFG + 64,
XGE_HAL_BADCFG_LINK_STABILITY_PERIOD = XGE_HAL_BASE_BADCFG + 65,
XGE_HAL_BADCFG_DEVICE_POLL_MILLIS = XGE_HAL_BASE_BADCFG + 66,
XGE_HAL_BADCFG_RMAC_PAUSE_GEN_EN = XGE_HAL_BASE_BADCFG + 67,
XGE_HAL_BADCFG_RMAC_PAUSE_RCV_EN = XGE_HAL_BASE_BADCFG + 68,
XGE_HAL_BADCFG_MEDIA = XGE_HAL_BASE_BADCFG + 69,
XGE_HAL_BADCFG_NO_ISR_EVENTS = XGE_HAL_BASE_BADCFG + 70,
XGE_HAL_BADCFG_RING_RTS_MAC_EN = XGE_HAL_BASE_BADCFG + 71,
XGE_HAL_BADCFG_LRO_SG_SIZE = XGE_HAL_BASE_BADCFG + 72,
XGE_HAL_BADCFG_LRO_FRM_LEN = XGE_HAL_BASE_BADCFG + 73,
XGE_HAL_BADCFG_WQE_NUM_ODS = XGE_HAL_BASE_BADCFG + 74,
XGE_HAL_BADCFG_BIMODAL_INTR = XGE_HAL_BASE_BADCFG + 75,
XGE_HAL_BADCFG_BIMODAL_TIMER_LO_US = XGE_HAL_BASE_BADCFG + 76,
XGE_HAL_BADCFG_BIMODAL_TIMER_HI_US = XGE_HAL_BASE_BADCFG + 77,
XGE_HAL_BADCFG_BIMODAL_XENA_NOT_ALLOWED = XGE_HAL_BASE_BADCFG + 78,
XGE_HAL_BADCFG_RTS_QOS_EN = XGE_HAL_BASE_BADCFG + 79,
XGE_HAL_BADCFG_FIFO_QUEUE_INTR_VECTOR = XGE_HAL_BASE_BADCFG + 80,
XGE_HAL_BADCFG_RING_QUEUE_INTR_VECTOR = XGE_HAL_BASE_BADCFG + 81,
XGE_HAL_BADCFG_RTS_PORT_EN = XGE_HAL_BASE_BADCFG + 82,
XGE_HAL_BADCFG_RING_RTS_PORT_EN = XGE_HAL_BASE_BADCFG + 83,
XGE_HAL_BADCFG_TRACEBUF_TIMESTAMP = XGE_HAL_BASE_BADCFG + 84,
XGE_HAL_EOF_TRACE_BUF = -1
} xge_hal_status_e;
#define XGE_HAL_ETH_ALEN 6
typedef u8 macaddr_t[XGE_HAL_ETH_ALEN];
#define XGE_HAL_PCI_XFRAME_CONFIG_SPACE_SIZE 0x100
/* frames sizes */
#define XGE_HAL_HEADER_ETHERNET_II_802_3_SIZE 14
#define XGE_HAL_HEADER_802_2_SIZE 3
#define XGE_HAL_HEADER_SNAP_SIZE 5
#define XGE_HAL_HEADER_VLAN_SIZE 4
#define XGE_HAL_MAC_HEADER_MAX_SIZE \
(XGE_HAL_HEADER_ETHERNET_II_802_3_SIZE + \
XGE_HAL_HEADER_802_2_SIZE + \
XGE_HAL_HEADER_SNAP_SIZE)
#define XGE_HAL_TCPIP_HEADER_MAX_SIZE (64 + 64)
/* 32bit alignments */
#define XGE_HAL_HEADER_ETHERNET_II_802_3_ALIGN 2
#define XGE_HAL_HEADER_802_2_SNAP_ALIGN 2
#define XGE_HAL_HEADER_802_2_ALIGN 3
#define XGE_HAL_HEADER_SNAP_ALIGN 1
#define XGE_HAL_L3_CKSUM_OK 0xFFFF
#define XGE_HAL_L4_CKSUM_OK 0xFFFF
#define XGE_HAL_MIN_MTU 46
#define XGE_HAL_MAX_MTU 9600
#define XGE_HAL_DEFAULT_MTU 1500
#define XGE_HAL_SEGEMENT_OFFLOAD_MAX_SIZE 81920
#define XGE_HAL_PCISIZE_XENA 26 /* multiples of dword */
#define XGE_HAL_PCISIZE_HERC 64 /* multiples of dword */
#define XGE_HAL_MAX_MSIX_MESSAGES 64
#define XGE_HAL_MAX_MSIX_MESSAGES_WITH_ADDR XGE_HAL_MAX_MSIX_MESSAGES * 2
/* Highest level interrupt blocks */
#define XGE_HAL_TX_PIC_INTR (0x0001<<0)
#define XGE_HAL_TX_DMA_INTR (0x0001<<1)
#define XGE_HAL_TX_MAC_INTR (0x0001<<2)
#define XGE_HAL_TX_XGXS_INTR (0x0001<<3)
#define XGE_HAL_TX_TRAFFIC_INTR (0x0001<<4)
#define XGE_HAL_RX_PIC_INTR (0x0001<<5)
#define XGE_HAL_RX_DMA_INTR (0x0001<<6)
#define XGE_HAL_RX_MAC_INTR (0x0001<<7)
#define XGE_HAL_RX_XGXS_INTR (0x0001<<8)
#define XGE_HAL_RX_TRAFFIC_INTR (0x0001<<9)
#define XGE_HAL_MC_INTR (0x0001<<10)
#define XGE_HAL_SCHED_INTR (0x0001<<11)
#define XGE_HAL_ALL_INTRS (XGE_HAL_TX_PIC_INTR | \
XGE_HAL_TX_DMA_INTR | \
XGE_HAL_TX_MAC_INTR | \
XGE_HAL_TX_XGXS_INTR | \
XGE_HAL_TX_TRAFFIC_INTR | \
XGE_HAL_RX_PIC_INTR | \
XGE_HAL_RX_DMA_INTR | \
XGE_HAL_RX_MAC_INTR | \
XGE_HAL_RX_XGXS_INTR | \
XGE_HAL_RX_TRAFFIC_INTR | \
XGE_HAL_MC_INTR | \
XGE_HAL_SCHED_INTR)
#define XGE_HAL_GEN_MASK_INTR (0x0001<<12)
/* Interrupt masks for the general interrupt mask register */
#define XGE_HAL_ALL_INTRS_DIS 0xFFFFFFFFFFFFFFFFULL
#define XGE_HAL_TXPIC_INT_M BIT(0)
#define XGE_HAL_TXDMA_INT_M BIT(1)
#define XGE_HAL_TXMAC_INT_M BIT(2)
#define XGE_HAL_TXXGXS_INT_M BIT(3)
#define XGE_HAL_TXTRAFFIC_INT_M BIT(8)
#define XGE_HAL_PIC_RX_INT_M BIT(32)
#define XGE_HAL_RXDMA_INT_M BIT(33)
#define XGE_HAL_RXMAC_INT_M BIT(34)
#define XGE_HAL_MC_INT_M BIT(35)
#define XGE_HAL_RXXGXS_INT_M BIT(36)
#define XGE_HAL_RXTRAFFIC_INT_M BIT(40)
/* MSI level Interrupts */
#define XGE_HAL_MAX_MSIX_VECTORS (16)
typedef struct xge_hal_ipv4 {
u32 addr;
}xge_hal_ipv4;
typedef struct xge_hal_ipv6 {
u64 addr[2];
}xge_hal_ipv6;
typedef union xge_hal_ipaddr_t {
xge_hal_ipv4 ipv4;
xge_hal_ipv6 ipv6;
}xge_hal_ipaddr_t;
/* DMA level Interrupts */
#define XGE_HAL_TXDMA_PFC_INT_M BIT(0)
/* PFC block interrupts */
#define XGE_HAL_PFC_MISC_ERR_1 BIT(0) /* Interrupt to indicate FIFO
full */
/* basic handles */
typedef void* xge_hal_device_h;
typedef void* xge_hal_dtr_h;
typedef void* xge_hal_channel_h;
/*
* I2C device id. Used in I2C control register for accessing EEPROM device
* memory.
*/
#define XGE_DEV_ID 5
typedef enum xge_hal_xpak_alarm_type_e {
XGE_HAL_XPAK_ALARM_EXCESS_TEMP = 1,
XGE_HAL_XPAK_ALARM_EXCESS_BIAS_CURRENT = 2,
XGE_HAL_XPAK_ALARM_EXCESS_LASER_OUTPUT = 3,
} xge_hal_xpak_alarm_type_e;
__EXTERN_END_DECLS
#endif /* XGE_HAL_TYPES_H */
|
feliposz/project-euler-solutions | python/euler51.py | <reponame>feliposz/project-euler-solutions
"""Problem 51
29 August 2003
http://projecteuler.net/problem=51
By replacing the 1st digit of *3, it turns out that six of the nine
possible values: 13, 23, 43, 53, 73, and 83, are all prime.
By replacing the 3rd and 4th digits of 56**3 with the same digit, this
5-digit number is the first example having seven primes among the ten
generated numbers, yielding the family: 56003, 56113, 56333, 56443,
56663, 56773, and 56993. Consequently 56003, being the first member of
this family, is the smallest prime with this property.
Find the smallest prime which, by replacing part of the number (not
necessarily adjacent digits) with the same digit, is part of an eight
prime value family.
"""
from eulerlib import generatePrimesSieve, timedRun
# Limit to the prime number generator (1 million is enough for this
# particular case).
LIMIT = 1000000
# Expected size of family of prime numbers with replaceable digits
FAMILY_SIZE = 8
primes, isPrime = generatePrimesSieve(LIMIT)
def euler51():
"""Solve problem 51 from Project Euler."""
# Check all prime numbers
for p in primes:
# Check if number can generate other primes by replacing a
# single digit
count = countSingleDigitReplacements(p)
if count == FAMILY_SIZE:
print(p)
break
# Check if number can generate other primes by replacing
# multiple repeated (possibly non-adjacent) digits
count = countRepeatedDigitReplacements(p)
if count == FAMILY_SIZE:
print(p)
break
def countSingleDigitReplacements(p):
"""Count how many primes can be generated at most by replacing a
single digit of the given number."""
s = str(p)
max_count = 0
# Don't replace the last digit. This makes sense, since replacing
# it would make the number non-prime in most of the cases anyway.
for i in range(len(s) - 1):
count = 0
for digit in range(10):
# Replace a single digit at position
new_s = s[:i] + str(digit) + s[i+1:]
# Don't count number if first digit was replaced by 0
if new_s[0] != '0' and isPrime[int(new_s)]:
count += 1
max_count = max(max_count, count)
return max_count
def countRepeatedDigitReplacements(p):
"""Count how many primes can be generated at most by replacing
multiple repeated (possibly non-adjacent) digits on the given
number."""
s = str(p)
# check for replaceable repeated digits
digit_count = {}
for c in s:
digit_count[c] = digit_count.get(c, 0) + 1
max_count = 0
for c in digit_count:
if digit_count[c] > 1: # found repeated digits
count = 0
for digit in range(10):
# Replace all repeated occurrences
new_s = s.replace(c, str(digit))
# Don't count number if first digit was replaced by 0
if new_s[0] != '0' and isPrime[int(new_s)]:
count += 1
max_count = max(max_count, count)
return max_count
if __name__ == "__main__":
timedRun(euler51)
|
amir9979/DesigniteJava | src/Designite/organic/collector/SmellName.java | <filename>src/Designite/organic/collector/SmellName.java
package Designite.organic.collector;
public enum SmellName {
ClassDataShouldBePrivate("Class Data Should Be Private"),
ComplexClass("Complex Class"),
FeatureEnvy("Feature Envy"),
GodClass("God Class"),
LazyClass("Lazy Class"),
LongMethod("Long Method"),
LongParameterList("Long Parameter List"),
MessageChain("Message Chain"),
RefusedBequest("Refused Bequest"),
SpeculativeGenerality("Speculative Generality"),
SpaghettiCode("Spaghetti Code"),
DispersedCoupling("Dispersed Coupling"),
IntensiveCoupling("Intensive Coupling"),
BrainClass("Brain Class"),
ShotgunSurgery("Shotgun Surgery"),
BrainMethod("Brain Method"),
DataClass("Data Class"),
LargeClass("Large Class"),
SwissArmyKnife("Swiss Army Knife"),
AntiSingleton("Anti Singleton");
private String name;
SmellName(String name) {
this.name = name;
}
@Override
public String toString() {
return this.name;
}
}
|
agoalofalife/slack-bot-loftschool-nodejs | src/Messages/Command.js | /**
*
* @type {module.Command}
*/
module.exports = class Command {
/**
*
* @param response
* @param baseBot class BaseBot
*/
constructor(response, baseBot){
this.response = response;
this.base = baseBot;
}
/**
* @link https://api.slack.com/events/message.im
* @return {string}
*/
get typeEvent() {
return 'command';
}
/**
* Description event
* @return {string}
*/
get descriptionEvent() {
return 'The event occurs when was sent a message with the type "command"';
}
get compareResponse(){
return this.response.command;
}
/**
* @link https://api.slack.com/slash-commands
* @return {boolean}
*/
verify(){
return this.base.team.id === this.response.team_id && process.env.SLACK_VERIFICATION_TOKEN === this.response.token;
}
}; |
reallinfo/lifelog | django/user/views.py | from django.views.generic import CreateView
from django.urls import reverse
from .forms import RegisterForm
class RegisterView(CreateView):
template_name = 'user/register.html'
form_class = RegisterForm
def get_success_url(self):
return reverse('user:login')
|
RyanTorant/simple-physx | PhysX_3.4/Include/PxActor.h | <reponame>RyanTorant/simple-physx
// This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PHYSICS_NX_ACTOR
#define PX_PHYSICS_NX_ACTOR
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "foundation/PxBounds3.h"
#include "PxClient.h"
#include "common/PxBase.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxRigidActor;
class PxRigidBody;
class PxRigidStatic;
class PxRigidDynamic;
class PxParticleBase;
class PxParticleSystem;
class PxParticleFluid;
class PxArticulation;
class PxArticulationLink;
/** Group index which allows to specify 1- or 2-way interaction */
typedef PxU8 PxDominanceGroup; // Must be < 32, PxU8.
/**
\brief Flags which control the behavior of an actor.
@see PxActorFlags PxActor PxActor.setActorFlag() PxActor.getActorFlags()
*/
struct PxActorFlag
{
enum Enum
{
/**
\brief Enable debug renderer for this actor
@see PxScene.getRenderBuffer() PxRenderBuffer PxVisualizationParameter
*/
eVISUALIZATION = (1<<0),
/**
\brief Disables scene gravity for this actor
*/
eDISABLE_GRAVITY = (1<<1),
/**
\brief Enables the sending of PxSimulationEventCallback::onWake() and PxSimulationEventCallback::onSleep() notify events
@see PxSimulationEventCallback::onWake() PxSimulationEventCallback::onSleep()
*/
eSEND_SLEEP_NOTIFIES = (1<<2),
/**
\brief Disables simulation for the actor.
\note This is only supported by PxRigidStatic and PxRigidDynamic actors and can be used to reduce the memory footprint when rigid actors are
used for scene queries only.
\note Setting this flag will remove all constraints attached to the actor from the scene.
\note If this flag is set, the following calls are forbidden:
\li PxRigidBody: setLinearVelocity(), setAngularVelocity(), addForce(), addTorque(), clearForce(), clearTorque()
\li PxRigidDynamic: setKinematicTarget(), setWakeCounter(), wakeUp(), putToSleep()
\par <b>Sleeping:</b>
Raising this flag will set all velocities and the wake counter to 0, clear all forces, clear the kinematic target, put the actor
to sleep and wake up all touching actors from the previous frame.
*/
eDISABLE_SIMULATION = (1<<3)
};
};
/**
\brief collection of set bits defined in PxActorFlag.
@see PxActorFlag
*/
typedef PxFlags<PxActorFlag::Enum,PxU8> PxActorFlags;
PX_FLAGS_OPERATORS(PxActorFlag::Enum,PxU8)
/**
\brief Identifies each type of actor.
@see PxActor
*/
struct PxActorType
{
enum Enum
{
/**
\brief A static rigid body
@see PxRigidStatic
*/
eRIGID_STATIC,
/**
\brief A dynamic rigid body
@see PxRigidDynamic
*/
eRIGID_DYNAMIC,
#if PX_USE_PARTICLE_SYSTEM_API
/**
\brief A particle system (deprecated)
\deprecated The PhysX particle feature has been deprecated in PhysX version 3.4
@see PxParticleSystem
*/
ePARTICLE_SYSTEM PX_DEPRECATED,
/**
\brief A particle fluid (deprecated)
\deprecated The PhysX particle feature has been deprecated in PhysX version 3.4
@see PxParticleFluid
*/
ePARTICLE_FLUID PX_DEPRECATED,
#endif
/**
\brief An articulation link
@see PxArticulationLink
*/
eARTICULATION_LINK,
#if PX_USE_CLOTH_API
/**
\brief A cloth
\deprecated The PhysX cloth feature has been deprecated in PhysX version 3.4.1
@see PxCloth
*/
eCLOTH PX_DEPRECATED,
#endif
//brief internal use only!
eACTOR_COUNT,
eACTOR_FORCE_DWORD = 0x7fffffff
};
};
/**
\brief PxActor is the base class for the main simulation objects in the physics SDK.
The actor is owned by and contained in a PxScene.
*/
class PxActor : public PxBase
{
public:
/**
\brief Deletes the actor.
Do not keep a reference to the deleted instance.
If the actor belongs to a #PxAggregate object, it is automatically removed from the aggregate.
@see PxBase.release(), PxAggregate
*/
virtual void release() = 0;
/**
\brief Retrieves the type of actor.
\return The actor type of the actor.
@see PxActorType
*/
virtual PxActorType::Enum getType() const = 0;
/**
\brief Retrieves the scene which this actor belongs to.
\return Owner Scene. NULL if not part of a scene.
@see PxScene
*/
virtual PxScene* getScene() const = 0;
// Runtime modifications
/**
\brief Sets a name string for the object that can be retrieved with getName().
This is for debugging and is not used by the SDK. The string is not copied by the SDK,
only the pointer is stored.
\param[in] name String to set the objects name to.
<b>Default:</b> NULL
@see getName()
*/
virtual void setName(const char* name) = 0;
/**
\brief Retrieves the name string set with setName().
\return Name string associated with object.
@see setName()
*/
virtual const char* getName() const = 0;
/**
\brief Retrieves the axis aligned bounding box enclosing the actor.
\param[in] inflation Scale factor for computed world bounds. Box extents are multiplied by this value.
\return The actor's bounding box.
@see PxBounds3
*/
virtual PxBounds3 getWorldBounds(float inflation=1.01f) const = 0;
/**
\brief Raises or clears a particular actor flag.
See the list of flags #PxActorFlag
<b>Sleeping:</b> Does <b>NOT</b> wake the actor up automatically.
\param[in] flag The PxActor flag to raise(set) or clear. See #PxActorFlag.
\param[in] value The boolean value to assign to the flag.
<b>Default:</b> PxActorFlag::eVISUALIZATION
@see PxActorFlag getActorFlags()
*/
virtual void setActorFlag(PxActorFlag::Enum flag, bool value) = 0;
/**
\brief sets the actor flags
See the list of flags #PxActorFlag
@see PxActorFlag setActorFlag()
*/
virtual void setActorFlags( PxActorFlags inFlags ) = 0;
/**
\brief Reads the PxActor flags.
See the list of flags #PxActorFlag
\return The values of the PxActor flags.
@see PxActorFlag setActorFlag()
*/
virtual PxActorFlags getActorFlags() const = 0;
/**
\brief Assigns dynamic actors a dominance group identifier.
PxDominanceGroup is a 5 bit group identifier (legal range from 0 to 31).
The PxScene::setDominanceGroupPair() lets you set certain behaviors for pairs of dominance groups.
By default every dynamic actor is created in group 0.
<b>Default:</b> 0
<b>Sleeping:</b> Changing the dominance group does <b>NOT</b> wake the actor up automatically.
\param[in] dominanceGroup The dominance group identifier. <b>Range:</b> [0..31]
@see getDominanceGroup() PxDominanceGroup PxScene::setDominanceGroupPair()
*/
virtual void setDominanceGroup(PxDominanceGroup dominanceGroup) = 0;
/**
\brief Retrieves the value set with setDominanceGroup().
\return The dominance group of this actor.
@see setDominanceGroup() PxDominanceGroup PxScene::setDominanceGroupPair()
*/
virtual PxDominanceGroup getDominanceGroup() const = 0;
/**
\brief Sets the owner client of an actor.
This cannot be done once the actor has been placed into a scene.
<b>Default:</b> PX_DEFAULT_CLIENT
@see PxClientID PxScene::createClient()
*/
virtual void setOwnerClient( PxClientID inClient ) = 0;
/**
\brief Returns the owner client that was specified with at creation time.
This value cannot be changed once the object is placed into the scene.
@see PxClientID PxScene::createClient()
*/
virtual PxClientID getOwnerClient() const = 0;
/**
\brief Sets the behavior bits of the actor.
The behavior bits determine which types of events the actor will broadcast to foreign clients.
The actor will always send notice for all possible events to its own owner client. By default
it will not send any events to any other clients. If the user however raises a bit flag for
any event type using this function, that event will then be sent also to any other clients which
are programmed to listed to foreign actor events of that type.
\deprecated PxActorClientBehaviorFlag feature has been deprecated in PhysX version 3.4
<b>Default:</b> 0
@see PxClientID PxActorClientBehaviorFlag PxScene::setClientBehaviorFlags()
*/
PX_DEPRECATED virtual void setClientBehaviorFlags(PxActorClientBehaviorFlags) = 0;
/**
\brief Retrieves the behavior bits of the actor.
The behavior bits determine which types of events the actor will broadcast to foreign clients.
\deprecated PxActorClientBehaviorFlag feature has been deprecated in PhysX version 3.4
@see PxActorClientBehaviorFlag setClientBehaviorFlags()
*/
PX_DEPRECATED virtual PxActorClientBehaviorFlags getClientBehaviorFlags() const = 0;
/**
\brief Retrieves the aggregate the actor might be a part of.
\return The aggregate the actor is a part of, or NULL if the actor does not belong to an aggregate.
@see PxAggregate
*/
virtual PxAggregate* getAggregate() const = 0;
//public variables:
void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object.
protected:
PX_INLINE PxActor(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags), userData(NULL) {}
PX_INLINE PxActor(PxBaseFlags baseFlags) : PxBase(baseFlags) {}
virtual ~PxActor() {}
virtual bool isKindOf(const char* name) const { return !::strcmp("PxActor", name) || PxBase::isKindOf(name); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
|
0range228/MySootScript | src/main/java/pta/Contex.java | //package pta;
//
//import soot.Local;
//import soot.Value;
//
//import java.util.Collections;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
///**
// *
// * @author xinjiang
// * 模拟一个函数上下文
// * 对于一个函数内部,有其相应的Local(变量),不同的函数内部,Local可以具有相同的名字
// * 对于该类需要解决:
// * 1. 在某个函数体A内,调用了函数B,如何将A中变量与B中变量相联系?
// * - 由于每个local都对应了一个Variable,那么我们可以看做添加对应的
// * - 赋值操作,A.r1 = B.p1,由于在指针分析中,赋值操作,是在r1的sourceId中
// * - 添加相应的p1的sourceId,因此,我们可以在r1对应的variables中,添加一个p1对应的variable
// * - !!!!因此,我们需要保留调用该函数的所在的函数域“! ! ! !,便于将该函数的参数与调用域中的参数对应
// * 2. 为了便于调试,明朗化,需要知道当前调用的深度
// * 3. 返回值,怎么处理?(暂时未处理!)
// * 4. 如何判断是否进入了递归函数?是否要处理递归函数?如果按照我们的添加variable的想法,
// * 处理递归函数会导致内存爆炸。因此,暂时不处理递归函数,如果要处理,需要修改一些机制。
// * 5. 还要处理分支函数,即If !!!!,第一次忽略了这个,一直跑不了
// * 6. 对于函数调用,需要将调用函数体内的变量与当前函数的参数进行联系。注意,函数调用后,只会影响对象的内部对象的指针指向!!
// *
// *
// *
// * 注意点:
// * 注意点,创建分支区域与创建函数子区域是不同的。
// * 创建一个分支域,需要复制半格,并且是deep复制,因为在分支内,对象及其内部成员都会受到影响。
// * 而创建函数子区域,则无需复制操作。
// * 在进行函数调用后,需要将参数与上层函数域内变量对应,简单的想,只要将上层对应变量的Variable与该层的Local对应就行了,
// * 这样在该域内,对该域的Local操作,然后相应进行半格操作。
// * 但是由于函数调用,不会改变对象本身的指针,只能改变对象成员的指针,
// * 因此,我们此时与该域对应的参数的Local对应的应该是上层相应变量的Variable的浅复制,这样该域内可以改变对象的成员指针,但是不能改变对象本身指针,举例说明:
// *
// *
// */
//public class Contex {
// private Analyzer analyzer;
// private int depth;
// private Contex invokeContex; // 调用该函数域的上级函数
// private String methodSignature; // 该函数的签名,用于判断是否是递归函数
// private List<Value> args; // 函数参数
// private Contex preContex; // 分支时刻的域
// private String branchSignature; // 分支签名
// private Variable thisVar; // this
// private Map<Local, Variable> localMap; // 在当前域内部,local和variable的对应表
//
// private Contex(Analyzer analyzer,
// int depth,
// Contex invokeContex,
// String methodSignature,
// List<Value> args,
// Contex preContex,
// String branchSignature,
// Variable thisVar) {
// this.analyzer = analyzer;
// this.depth = depth;
// this.invokeContex = invokeContex;
// this.methodSignature = methodSignature;
// this.args = args;
// this.preContex = preContex;
// this.branchSignature = branchSignature;
// this.thisVar = thisVar;
// localMap = new HashMap<>();
//
// }
//
// public static Contex getInstance(Analyzer analyzer) {
// return new Contex(analyzer, 0, null, null, Collections.emptyList(), null, null, null);
// }
//
// /**
// * 创建一个函数调用的新域
// */
// public Contex createInvokeContex(String methodSignature, List<Value> args, Variable thisVar) {
// // dep+1,
// return new Contex(analyzer, depth + 1, this, methodSignature, args, null, null, thisVar);
// }
//
// /**
// * 创建一个分支域,注意分支域与之前一个域,参数相同,因此需要复制下Variable
// * 需要复制variable,deep,
// * @param branchSignature
// * @return
// */
// public Contex createBranchScope(String branchSignature) {
// Contex contex = new Contex(analyzer, depth, invokeContex, methodSignature, args, this, branchSignature, thisVar);
// for (Map.Entry<Local, Variable> entry : this.localMap.entrySet()) {
// Variable copy = entry.getValue().copyDeep(true);
// contex.bindLocalAndVariable(copy.getLocal(), copy);
// }
// return contex;
// }
//
// public Analyzer getAnalyzer() {
// return analyzer;
// }
//
// /**
// * 将local与var对应
// * @param local
// * @param var
// */
// private void bindLocalAndVariable(Local local, Variable var) {
// localMap.put(local, var);
// analyzer.addLocal(local, var);
// }
//
// public Variable getVariable(Local local) {
// return localMap.get(local);
// }
//
// // 将local和参数索引匹配
// // 将上层函数域中的对应local的var浅复制一下,与当前域的local进行对应
// public void bindArg(Local local, int paramIndex) {
// // args.size()初始是0,如果第二个是false,说明是main方法
// if (paramIndex >= 0 && paramIndex < args.size()) {
// Value argValue = args.get(paramIndex);
// if (argValue instanceof Local) {
// Variable argVar = invokeContex.getVariable((Local)argValue);
// Variable var;
// if (argVar != null) {
// var = argVar.copyDeep(false);
// } else {
// var = Variable.getInstance(argValue);
// }
// bindLocalAndVariable(local, var);
// }
// }
// }
//
// public Variable getOrAdd(Local local) {
// // 获取local对应的var,这里的local是rop
// Variable var = getVariable(local);
// if (var == null) {
// var = Variable.getInstance(local);
// // 将local与var绑定
// bindLocalAndVariable(local, var);
// }
// return var;
// }
//
// public void bindThis(Local local) {
// bindLocalAndVariable(local, thisVar.copyDeep(false));
// }
//
// public Variable createVariable(Value val) {
// return Variable.getInstance(val);
// }
//
// // 判断是否递归
// public boolean isInRecursion(String invokeSignature) {
// if (invokeSignature.equals(methodSignature)) {
// return true;
// }
// if (invokeContex != null) {
// return invokeContex.isInRecursion(invokeSignature);
// }
// return false;
// }
//
// // 判断是否分支
// public boolean isInBranchChain(String branchSignature) {
// if (branchSignature.equals(this.branchSignature)) {
// return true;
// }
// if (preContex != null) {
// return preContex.isInBranchChain(branchSignature);
// }
// return false;
// }
//
// public int getDepth() {
// return depth;
// }
//
// @Override
// public String toString() {
// return "Contex{ "
// + this.localMap
// + "}";
// }
//}
|
ScalablyTyped/SlinkyTyped | c/cypress/src/main/scala/typingsSlinky/cypress/fpMod/LodashZipWith.scala | package typingsSlinky.cypress.fpMod
import typingsSlinky.cypress.lodashMod.List
import typingsSlinky.cypress.lodashMod.__
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation._
@js.native
trait LodashZipWith extends js.Object {
def apply[T1](iteratee: __, arrays1: List[T1]): LodashZipWith1x2[T1] = js.native
def apply[T2](iteratee: __, arrays1: __, arrays2: List[T2]): LodashZipWith1x4[T2] = js.native
def apply[T1, T2](iteratee: __, arrays1: List[T1], arrays2: List[T2]): LodashZipWith1x6[T1, T2] = js.native
def apply[T1, T2, TResult](iteratee: js.Function2[/* value1 */ T1, /* value2 */ T2, TResult]): LodashZipWith1x1[T1, T2, TResult] = js.native
def apply[T1, T2, TResult](iteratee: js.Function2[/* value1 */ T1, /* value2 */ T2, TResult], arrays1: List[T1]): LodashZipWith1x3[T2, TResult] = js.native
def apply[T1, T2, TResult](
iteratee: js.Function2[/* value1 */ T1, /* value2 */ T2, TResult],
arrays1: List[T1],
arrays2: List[T2]
): js.Array[TResult] = js.native
def apply[T1, T2, TResult](iteratee: js.Function2[/* value1 */ T1, /* value2 */ T2, TResult], arrays1: __, arrays2: List[T2]): LodashZipWith1x5[T1, TResult] = js.native
}
|
ahmedlawi92/izpack | izpack-compiler/src/main/java/com/izforge/izpack/compiler/compressor/DefaultPackCompressor.java | /*
* $Id$
* IzPack - Copyright 2001-2008 <NAME>, All Rights Reserved.
*
* http://izpack.org/
* http://izpack.codehaus.org/
*
* Copyright 2005 <NAME>
*
* 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.izforge.izpack.compiler.compressor;
import java.io.OutputStream;
/**
* IzPack will be able to support different compression methods for the
* packs included in the installation jar file.
* This class implements the PackCompressor for the compression format "default"
* which is current the LZ77 implementation of zlib (also known as
* zip or deflate).
*
* @author <NAME>
*/
public class DefaultPackCompressor extends PackCompressorBase
{
private static final String[] THIS_FORMAT_NAMES =
{"default", "deflate", "zip", "lz77"};
private static final String THIS_DECODER_MAPPER = null;
private static final String THIS_ENCODER_CLASS_NAME = null;
/**
*
*/
public DefaultPackCompressor()
{
formatNames = THIS_FORMAT_NAMES;
decoderMapper = THIS_DECODER_MAPPER;
encoderClassName = THIS_ENCODER_CLASS_NAME;
}
/* (non-Javadoc)
* @see com.izforge.izpack.compressor.PackCompressor#getOutputStream(java.io.OutputStream)
*/
public OutputStream getOutputStream(OutputStream os)
{
// This will crash the packager if implementation is wrong :-)
return (null);
}
/* (non-Javadoc)
* @see com.izforge.izpack.compressor.PackCompressor#useStandardCompression()
*/
public boolean useStandardCompression()
{
return (true);
}
/* (non-Javadoc)
* @see com.izforge.izpack.compressor.PackCompressor#needsBufferedOutputStream()
*/
public boolean needsBufferedOutputStream()
{
return (false);
}
}
|
lauramazzuca21/DTNME | servlib/bundling/BundleEventHandler.h | /*
* Copyright 2005-2006 Intel Corporation
*
* 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.
*/
/*
* Modifications made to this file by the patch file dtnme_mfs-33289-1.patch
* are Copyright 2015 United States Government as represented by NASA
* Marshall Space Flight Center. All Rights Reserved.
*
* Released under the NASA Open Source Software Agreement version 1.3;
* You may obtain a copy of the Agreement at:
*
* http://ti.arc.nasa.gov/opensource/nosa/
*
* The subject software is provided "AS IS" WITHOUT ANY WARRANTY of any kind,
* either expressed, implied or statutory and this agreement does not,
* in any manner, constitute an endorsement by government agency of any
* results, designs or products resulting from use of the subject software.
* See the Agreement for the specific language governing permissions and
* limitations.
*/
#ifndef _BUNDLE_EVENT_HANDLER_H_
#define _BUNDLE_EVENT_HANDLER_H_
#include <oasys/debug/Log.h>
#include "BundleEvent.h"
namespace dtn {
/**
* Both the BundleDaemon and all the BundleRouter classes need to
* process the various types of BundleEvent that are generated by the
* rest of the system. This class provides that abstraction plus a
* useful dispatching function for event-specific handlers.
*/
class BundleEventHandler : public oasys::Logger {
public:
/**
* Pure virtual event handler function.
*/
virtual void handle_event(BundleEvent* event) = 0;
protected:
/**
* Constructor -- protected since this class shouldn't ever be
* instantiated directly.
*/
BundleEventHandler(const char* classname,
const char* logpath)
: oasys::Logger(classname, "%s", logpath) {}
/**
* Destructor -- Needs to be defined virtual to be sure that
* derived classes get a chance to clean up their stuff on removal.
*/
virtual ~BundleEventHandler() {}
/**
* Dispatch the event by type code to one of the event-specific
* handler functions below.
*/
void dispatch_event(BundleEvent* event);
/**
* Default event handler for new bundle arrivals.
*/
virtual void handle_bundle_received(BundleReceivedEvent* event);
/**
* Default event handler when bundles are transmitted.
*/
virtual void handle_bundle_transmitted(BundleTransmittedEvent* event);
/**
* Default event handler when bundles are locally delivered.
*/
virtual void handle_bundle_delivered(BundleDeliveredEvent* event);
/**
* Default event handler when bundles are acked by app.
*/
virtual void handle_bundle_acknowledged_by_app(BundleAckEvent* event);
/**
* Default event handler when bundles expire.
*/
virtual void handle_bundle_expired(BundleExpiredEvent* event);
/**
* Default event handler when bundles are free (i.e. no more
* references).
*/
virtual void handle_bundle_free(BundleFreeEvent* event);
/**
* Default event handler for bundle send requests
*/
virtual void handle_bundle_send(BundleSendRequest* event);
/**
* Default event handler for send bundle request cancellations
*/
virtual void handle_bundle_cancel(BundleCancelRequest* event);
/**
* Default event handler for bundle cancellations.
*/
virtual void handle_bundle_cancelled(BundleSendCancelledEvent*);
/**
* Default event handler for bundle inject requests
*/
virtual void handle_deliver_bundle_to_reg(DeliverBundleToRegEvent* event);
/**
* Default event handler for bundle inject requests
*/
virtual void handle_bundle_inject(BundleInjectRequest* event);
/**
* Default event handler for bundle injected events.
*/
virtual void handle_bundle_injected(BundleInjectedEvent* event);
/**
* Default event handler for bundle delete requests.
*/
virtual void handle_bundle_delete(BundleDeleteRequest* request);
/**
* Default event handler for requests to take custody of a bundle (ExternalRouter).
*/
virtual void handle_bundle_take_custody(BundleTakeCustodyRequest* request);
/**
* Default event handler for custody accepted event (ExternalRouter).
*/
virtual void handle_bundle_custody_accepted(BundleCustodyAcceptedEvent* event);
/**
* Default event handler for a bundle accept request probe.
*/
virtual void handle_bundle_accept(BundleAcceptRequest* event);
/**
* Default event handler for bundle query requests.
*/
virtual void handle_bundle_query(BundleQueryRequest* request);
/**
* Default event handler for bundle reports.
*/
virtual void handle_bundle_report(BundleReportEvent* request);
/**
* Default event handler for bundle attribute query requests.
*/
virtual void handle_bundle_attributes_query(BundleAttributesQueryRequest*);
/**
* Default event handler for bundle attribute reports.
*/
virtual void handle_bundle_attributes_report(BundleAttributesReportEvent*);
/**
* Default event handler for a private event
*/
virtual void handle_private(PrivateEvent*);
/**
* Default event handler when a new application registration
* arrives.
*/
virtual void handle_registration_added(RegistrationAddedEvent* event);
/**
* Default event handler when a registration is removed.
*/
virtual void handle_registration_removed(RegistrationRemovedEvent* event);
/**
* Default event handler when a registration expires.
*/
virtual void handle_registration_expired(RegistrationExpiredEvent* event);
/**
* Default event handler when a registration is to be deleted.
*/
virtual void handle_registration_delete(RegistrationDeleteRequest* event);
/**
* Default event handler for store bundle update events.
*/
virtual void handle_store_bundle_update(StoreBundleUpdateEvent*);
/**
* Default event handler for store bundle delete events.
*/
virtual void handle_store_bundle_delete(StoreBundleDeleteEvent*);
#ifdef ACS_ENABLED
/**
* Default event handler for store pendingacs update events.
*/
virtual void handle_store_pendingacs_update(StorePendingAcsUpdateEvent*);
/**
* Default event handler for store pendingacs delete events.
*/
virtual void handle_store_pendingacs_delete(StorePendingAcsDeleteEvent*);
#endif // ACS_ENABLED
/**
* Default event handler for an External Router ACS -- purposely not in the ACS_ENABLED block
*/
virtual void handle_external_router_acs(ExternalRouterAcsEvent*);
/**
* Default event handler for store registration update events.
*/
virtual void handle_store_registration_update(StoreRegistrationUpdateEvent*);
/**
* Default event handler for store registration delete events.
*/
virtual void handle_store_registration_delete(StoreRegistrationDeleteEvent*);
/**
* Default event handler for store link update events.
*/
virtual void handle_store_link_update(StoreLinkUpdateEvent*);
/**
* Default event handler for store link delete events.
*/
virtual void handle_store_link_delete(StoreLinkDeleteEvent*);
/**
* Default event handler when a new contact is up.
*/
virtual void handle_contact_up(ContactUpEvent* event);
/**
* Default event handler when a contact is down.
*/
virtual void handle_contact_down(ContactDownEvent* event);
/**
* Default event handler for contact query requests.
*/
virtual void handle_contact_query(ContactQueryRequest* request);
/**
* Default event handler for contact reports.
*/
virtual void handle_contact_report(ContactReportEvent* request);
/**
* Default event handler for contact attribute changes.
*/
virtual void handle_contact_attribute_changed(ContactAttributeChangedEvent*);
/**
* Default event handler when a new link is created.
*/
virtual void handle_link_created(LinkCreatedEvent* event);
/**
* Default event handler when a link is deleted.
*/
virtual void handle_link_deleted(LinkDeletedEvent* event);
/**
* Default event handler when link becomes available
*/
virtual void handle_link_available(LinkAvailableEvent* event);
/**
* Default event handler when a link is unavailable
*/
virtual void handle_link_unavailable(LinkUnavailableEvent* event);
/**
* Default event handler when a link is unavailable
*/
virtual void handle_link_check_deferred(LinkCheckDeferredEvent* event);
/**
* Default event handler for link state change requests.
*/
virtual void handle_link_state_change_request(LinkStateChangeRequest* req);
/**
* Default event handler for link cancel all bundles request
*/
virtual void handle_link_cancel_all_bundles_request(LinkCancelAllBundlesRequest* req);
/**
* Default event handler for link create requests.
*/
virtual void handle_link_create(LinkCreateRequest* request);
/**
* Default event handler for link delete requests.
*/
virtual void handle_link_delete(LinkDeleteRequest* request);
/**
* Default event handler for link reconfigure requests.
*/
virtual void handle_link_reconfigure(LinkReconfigureRequest* request);
/**
* Default event handler for link query requests.
*/
virtual void handle_link_query(LinkQueryRequest* request);
/**
* Default event handler for link reports.
*/
virtual void handle_link_report(LinkReportEvent* request);
/**
* Default event handler for link attribute changes.
*/
virtual void handle_link_attribute_changed(LinkAttributeChangedEvent*);
/**
* Default event handler when reassembly is completed.
*/
virtual void handle_reassembly_completed(ReassemblyCompletedEvent* event);
/**
* Default event handler when a new route is added by the command
* or management interface.
*/
virtual void handle_route_add(RouteAddEvent* event);
/**
* Default event handler to check bundle routing after new routes have been added
*/
virtual void handle_route_recompute(RouteRecomputeEvent* event);
/**
* Default event handler when a route is deleted by the command
* or management interface.
*/
virtual void handle_route_del(RouteDelEvent* event);
/**
* Default event handler for static route query requests.
*/
virtual void handle_route_query(RouteQueryRequest* request);
/**
* Default event handler for static route reports.
*/
virtual void handle_route_report(RouteReportEvent* request);
/**
* Default event handler when custody signals are received.
*/
virtual void handle_custody_signal(CustodySignalEvent* event);
/**
* Default event handler when custody transfer timers expire
*/
virtual void handle_custody_timeout(CustodyTimeoutEvent* event);
/**
* Default event handler for shutdown requests.
*/
virtual void handle_shutdown_request(ShutdownRequest* event);
/**
* Default event handler for status requests.
*/
virtual void handle_status_request(StatusRequest* event);
/**
* Default event handler for CLA parameter set requests.
*/
virtual void handle_cla_set_params(CLASetParamsRequest*);
/**
* Default event handler for CLA parameters set events.
*/
virtual void handle_cla_params_set(CLAParamsSetEvent*);
/**
* Default event handler for set link defaults requests.
*/
virtual void handle_set_link_defaults(SetLinkDefaultsRequest*);
/**
* Default event handler for new EIDs discovered by CLA.
*/
virtual void handle_new_eid_reachable(NewEIDReachableEvent*);
/**
* Default event handlers for queries to and reports from the CLA.
*/
virtual void handle_bundle_queued_query(BundleQueuedQueryRequest*);
virtual void handle_bundle_queued_report(BundleQueuedReportEvent*);
virtual void handle_eid_reachable_query(EIDReachableQueryRequest*);
virtual void handle_eid_reachable_report(EIDReachableReportEvent*);
virtual void handle_link_attributes_query(LinkAttributesQueryRequest*);
virtual void handle_link_attributes_report(LinkAttributesReportEvent*);
virtual void handle_iface_attributes_query(IfaceAttributesQueryRequest*);
virtual void handle_iface_attributes_report(IfaceAttributesReportEvent*);
virtual void handle_cla_parameters_query(CLAParametersQueryRequest*);
virtual void handle_cla_parameters_report(CLAParametersReportEvent*);
#ifdef ACS_ENABLED
/**
* Default event handler when custody signals are received.
*/
virtual void handle_aggregate_custody_signal(AggregateCustodySignalEvent* event);
/**
* Default event handler for issuing an aggreage custody signal
*/
virtual void handle_add_bundle_to_acs(AddBundleToAcsEvent* event);
/**
* Default event handler for an aggreage custody signal expiration
*/
virtual void handle_acs_expired(AcsExpiredEvent* event);
#endif // ACS_ENABLED
#ifdef DTPC_ENABLED
/**
* Default event handler when DTPC topic is registered
*/
virtual void handle_dtpc_topic_registration(DtpcTopicRegistrationEvent* event);
/**
* Default event handler when DTPC topic is unregistered
*/
virtual void handle_dtpc_topic_unregistration(DtpcTopicUnregistrationEvent* event);
/**
* Default event handler when DTPC data item is sent
*/
virtual void handle_dtpc_send_data_item(DtpcSendDataItemEvent* event);
/**
* Default event handler when DTPC Payload Aggregation Timer expires
*/
virtual void handle_dtpc_payload_aggregation_timer_expired(DtpcPayloadAggregationTimerExpiredEvent* event);
/**
* Default event handler when DTPC transmits a PDU
*/
virtual void handle_dtpc_transmitted_event(DtpcPduTransmittedEvent* event);
/**
* Default event handler when DTPC requests deletion of a PDU
*/
virtual void handle_dtpc_delete_request(DtpcPduDeleteRequest* event);
/**
* Default event handler when DTPC Payload Aggregation Timer expires
*/
virtual void handle_dtpc_retransmit_timer_expired(DtpcRetransmitTimerExpiredEvent* event);
/**
* Default event handler when DTPC ACK PDUs are received
*/
virtual void handle_dtpc_ack_received_event(DtpcAckReceivedEvent* event);
/**
* Default event handler when DTPC Data PDUs are received
*/
virtual void handle_dtpc_data_received_event(DtpcDataReceivedEvent* event);
/**
* Default event handler when a DTPC Deliver PDU Timer expires
*/
virtual void handle_dtpc_deliver_pdu_event(DtpcDeliverPduTimerExpiredEvent* event);
/**
* Default event handler when a DTPC Topic Expiration Timer expires
*/
virtual void handle_dtpc_topic_expiration_check(DtpcTopicExpirationCheckEvent* event);
/**
* Default event handler when a DTPC elision function response is received
*/
virtual void handle_dtpc_elision_func_response(DtpcElisionFuncResponse* event);
#endif // DTPC_ENABLED
};
} // namespace dtn
#endif /* _BUNDLE_EVENT_HANDLER_H_ */
|
Akhilesh271988/numpy | numpy/core/src/common/npy_partition.h | #ifndef NUMPY_CORE_SRC_COMMON_PARTITION_H_
#define NUMPY_CORE_SRC_COMMON_PARTITION_H_
#include "npy_sort.h"
/* Python include is for future object sorts */
#include <Python.h>
#include <numpy/ndarraytypes.h>
#include <numpy/npy_common.h>
#define NPY_MAX_PIVOT_STACK 50
#ifdef __cplusplus
extern "C" {
#endif
NPY_NO_EXPORT PyArray_PartitionFunc *
get_partition_func(int type, NPY_SELECTKIND which);
NPY_NO_EXPORT PyArray_ArgPartitionFunc *
get_argpartition_func(int type, NPY_SELECTKIND which);
#ifdef __cplusplus
}
#endif
#endif
|
MhdT/dhis2-core | dhis-2/dhis-api/src/main/java/org/hisp/dhis/calendar/impl/PersianCalendar.java | <reponame>MhdT/dhis2-core<gh_stars>1-10
package org.hisp.dhis.calendar.impl;
/*
* Copyright (c) 2004-2020, University of Oslo
* 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 HISP project 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 OWNER 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 org.hisp.dhis.calendar.AbstractCalendar;
import org.hisp.dhis.calendar.Calendar;
import org.hisp.dhis.calendar.DateInterval;
import org.hisp.dhis.calendar.DateIntervalType;
import org.hisp.dhis.calendar.DateTimeUnit;
import org.hisp.dhis.calendar.exception.InvalidCalendarParametersException;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Days;
import org.joda.time.chrono.ISOChronology;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @author <NAME> <<EMAIL>>
*/
@Component
public class PersianCalendar extends AbstractCalendar
{
private static final DateTimeUnit START_PERSIAN = new DateTimeUnit( 1353, 1, 1, java.util.Calendar.THURSDAY );
private static final DateTimeUnit START_ISO = new DateTimeUnit( 1974, 3, 21, java.util.Calendar.THURSDAY, true );
private static final DateTimeUnit STOP_PERSIAN = new DateTimeUnit( 1418, 12, 29, java.util.Calendar.MONDAY );
private static final DateTimeUnit STOP_ISO = new DateTimeUnit( 2040, 3, 19, java.util.Calendar.MONDAY, true );
private static final Calendar SELF = new PersianCalendar();
public static Calendar getInstance()
{
return SELF;
}
@Override
public String name()
{
return "persian";
}
@Override
public DateTimeUnit toIso( DateTimeUnit dateTimeUnit )
{
if ( dateTimeUnit.getYear() >= START_ISO.getYear() && dateTimeUnit.getYear() <= STOP_ISO.getYear() )
{
return new DateTimeUnit( dateTimeUnit.getYear(), dateTimeUnit.getMonth(), dateTimeUnit.getDay(),
dateTimeUnit.getDayOfWeek(), true );
}
if ( dateTimeUnit.getYear() > STOP_PERSIAN.getYear() ||
dateTimeUnit.getYear() < START_PERSIAN.getYear() )
{
throw new InvalidCalendarParametersException(
"Illegal PERSIAN year, must be between " + START_PERSIAN.getYear() + " and " +
STOP_PERSIAN.getYear() + ", was given " + dateTimeUnit.getYear() );
}
DateTime dateTime = START_ISO.toJodaDateTime();
int totalDays = 0;
for ( int year = START_PERSIAN.getYear(); year < dateTimeUnit.getYear(); year++ )
{
totalDays += getYearTotal( year );
}
for ( int month = START_PERSIAN.getMonth(); month < dateTimeUnit.getMonth(); month++ )
{
totalDays += getDaysFromMap( dateTimeUnit.getYear(), month );
}
totalDays += dateTimeUnit.getDay() - START_PERSIAN.getDay();
dateTime = dateTime.plusDays( totalDays );
return new DateTimeUnit( DateTimeUnit.fromJodaDateTime( dateTime ), true );
}
@Override
public DateTimeUnit fromIso( Date date )
{
return fromIso( DateTimeUnit.fromJdkDate( date ) );
}
@Override
public DateTimeUnit fromIso( DateTimeUnit dateTimeUnit )
{
if ( dateTimeUnit.getYear() >= START_PERSIAN.getYear() &&
dateTimeUnit.getYear() <= STOP_PERSIAN.getYear() )
{
return new DateTimeUnit( dateTimeUnit.getYear(), dateTimeUnit.getMonth(), dateTimeUnit.getDay(),
dateTimeUnit.getDayOfWeek(), false );
}
if ( dateTimeUnit.getYear() < START_ISO.getYear() || dateTimeUnit.getYear() > STOP_ISO.getYear() )
{
throw new InvalidCalendarParametersException(
"Illegal ISO year, must be between " + START_ISO.getYear() + " and " + STOP_ISO.getYear() +
", was given " + dateTimeUnit.getYear() );
}
DateTime start = START_ISO.toJodaDateTime();
DateTime end = dateTimeUnit.toJodaDateTime();
return plusDays( START_PERSIAN, Days.daysBetween( start, end ).getDays() );
}
@Override
public DateInterval toInterval( DateTimeUnit dateTimeUnit, DateIntervalType type, int offset, int length )
{
switch ( type )
{
case ISO8601_YEAR:
return toYearIsoInterval( dateTimeUnit, offset, length );
case ISO8601_MONTH:
return toMonthIsoInterval( dateTimeUnit, offset, length );
case ISO8601_WEEK:
return toWeekIsoInterval( dateTimeUnit, offset, length );
case ISO8601_DAY:
return toDayIsoInterval( dateTimeUnit, offset, length );
default:
return null;
}
}
@Override
public int daysInYear( int year )
{
return getYearTotal( year );
}
@Override
public int daysInMonth( int year, int month )
{
int newYear = year;
if ( year > START_ISO.getYear() )
{
if ( month < 4 )
{
newYear = year - 622;
}
else
{
newYear = year - 621;
}
}
return getDaysFromMap( newYear, month );
}
@Override
public int weeksInYear( int year )
{
DateTime dateTime = new DateTime( year, 1, 1, 0, 0,
ISOChronology.getInstance( DateTimeZone.getDefault() ) );
return dateTime.weekOfWeekyear().getMaximumValue();
}
@Override
public int isoWeek( DateTimeUnit dateTimeUnit )
{
DateTime dateTime = toIso( dateTimeUnit )
.toJodaDateTime( ISOChronology.getInstance( DateTimeZone.getDefault() ) );
return dateTime.getWeekOfWeekyear();
}
@Override
public int week( DateTimeUnit dateTimeUnit )
{
return isoWeek( dateTimeUnit );
}
@Override
public int isoWeekday( DateTimeUnit dateTimeUnit )
{
DateTime dateTime = toIso( dateTimeUnit )
.toJodaDateTime( ISOChronology.getInstance( DateTimeZone.getDefault() ) );
return dateTime.getDayOfWeek();
}
@Override
public int weekday( DateTimeUnit dateTimeUnit )
{
int dayOfWeek = (isoWeekday( dateTimeUnit ) + 1);
if ( dayOfWeek > 7 )
{
return 1;
}
return dayOfWeek;
}
@Override
public String nameOfMonth( int month )
{
if ( month > DEFAULT_I18N_MONTH_NAMES.length || month <= 0 )
{
return null;
}
return "persian." + DEFAULT_I18N_MONTH_NAMES[month - 1];
}
@Override
public String shortNameOfMonth( int month )
{
if ( month > DEFAULT_I18N_MONTH_SHORT_NAMES.length || month <= 0 )
{
return null;
}
return "persian." + DEFAULT_I18N_MONTH_SHORT_NAMES[month - 1];
}
@Override
public String nameOfDay( int day )
{
if ( day > DEFAULT_I18N_DAY_NAMES.length || day <= 0 )
{
return null;
}
return "persian." + DEFAULT_I18N_DAY_NAMES[day - 1];
}
@Override
public String shortNameOfDay( int day )
{
if ( day > DEFAULT_I18N_DAY_SHORT_NAMES.length || day <= 0 )
{
return null;
}
return "persian." + DEFAULT_I18N_DAY_SHORT_NAMES[day - 1];
}
@Override
public DateTimeUnit minusYears( DateTimeUnit dateTimeUnit, int years )
{
DateTimeUnit result = new DateTimeUnit( dateTimeUnit.getYear() - years, dateTimeUnit.getMonth(),
dateTimeUnit.getDay(), dateTimeUnit.getDayOfWeek() );
updateDateUnit( result );
return result;
}
@Override
public DateTimeUnit minusMonths( DateTimeUnit dateTimeUnit, int months )
{
DateTimeUnit result = new DateTimeUnit( dateTimeUnit );
int newMonths = months;
while ( newMonths != 0 )
{
result.setMonth( result.getMonth() - 1 );
if ( result.getMonth() < 1 )
{
result.setMonth( monthsInYear() );
result.setYear( result.getYear() - 1 );
}
newMonths--;
}
updateDateUnit( result );
return result;
}
@Override
public DateTimeUnit minusWeeks( DateTimeUnit dateTimeUnit, int weeks )
{
return minusDays( dateTimeUnit, weeks * daysInWeek() );
}
@Override
public DateTimeUnit minusDays( DateTimeUnit dateTimeUnit, int days )
{
int curYear = dateTimeUnit.getYear();
int curMonth = dateTimeUnit.getMonth();
int curDay = dateTimeUnit.getDay();
int dayOfWeek = dateTimeUnit.getDayOfWeek();
int newDays = days;
while ( newDays != 0 )
{
curDay--;
if ( curDay == 0 )
{
curMonth--;
if ( curMonth == 0 )
{
curYear--;
curMonth = 12;
}
curDay = getDaysFromMap( curYear, curMonth );
}
dayOfWeek--;
if ( dayOfWeek == 0 )
{
dayOfWeek = 7;
}
newDays--;
}
return new DateTimeUnit( curYear, curMonth, curDay, dayOfWeek );
}
@Override
public DateTimeUnit plusYears( DateTimeUnit dateTimeUnit, int years )
{
DateTimeUnit result = new DateTimeUnit( dateTimeUnit.getYear() + years, dateTimeUnit.getMonth(),
dateTimeUnit.getDay(), dateTimeUnit.getDayOfWeek() );
updateDateUnit( result );
return result;
}
@Override
public DateTimeUnit plusMonths( DateTimeUnit dateTimeUnit, int months )
{
if ( months < 0 )
{
return minusMonths( dateTimeUnit, Math.abs( months ) );
}
DateTimeUnit result = new DateTimeUnit( dateTimeUnit );
int newMonths = months;
while ( newMonths != 0 )
{
result.setMonth( result.getMonth() + 1 );
if ( result.getMonth() > monthsInYear() )
{
result.setMonth( 1 );
result.setYear( result.getYear() + 1 );
}
newMonths--;
}
updateDateUnit( result );
return result;
}
@Override
public DateTimeUnit plusWeeks( DateTimeUnit dateTimeUnit, int weeks )
{
return plusDays( dateTimeUnit, weeks * daysInWeek() );
}
@Override
public DateTimeUnit plusDays( DateTimeUnit dateTimeUnit, int days )
{
if ( days < 0 )
{
return minusDays( dateTimeUnit, Math.abs( days ) );
}
int curYear = dateTimeUnit.getYear();
int curMonth = dateTimeUnit.getMonth();
int curDay = dateTimeUnit.getDay();
int dayOfWeek = dateTimeUnit.getDayOfWeek();
int newDays = days;
while ( newDays != 0 )
{
if ( curDay < getDaysFromMap( curYear, curMonth ) )
{
curDay++;
}
else
{
curMonth++;
curDay = 1;
if ( curMonth == 13 )
{
curMonth = 1;
curYear++;
}
}
newDays--;
dayOfWeek++;
if ( dayOfWeek == 8 )
{
dayOfWeek = 1;
}
}
return new DateTimeUnit( curYear, curMonth, curDay, dayOfWeek, false );
}
@Override
public DateTimeUnit isoStartOfYear( int year )
{
int day = 21;
int[] twenties = new int[]{ 1375, 1379, 1383, 1387, 1391, 1395, 1399, 1403, 1407, 1408, 1411, 1412,
1415, 1416, 1419 };
if ( contains( twenties, year ) )
{
day = 20;
}
return new DateTimeUnit( year + 621, 3, day, java.util.Calendar.FRIDAY, true );
}
//---------------------------------------------------------------------------------------------
// Helpers
//---------------------------------------------------------------------------------------------
private int getYearTotal( int year )
{
if ( CONVERSION_MAP.get( year ) == null )
{
throw new InvalidCalendarParametersException(
"Illegal PERSIAN year, must be between " + START_PERSIAN.getYear() + " and " +
STOP_PERSIAN.getYear() + " was given " + year );
}
if ( CONVERSION_MAP.get( year )[0] == 0 )
{
for ( int j = 1; j <= 12; j++ )
{
CONVERSION_MAP.get( year )[0] += CONVERSION_MAP.get( year )[j];
}
}
return CONVERSION_MAP.get( year )[0];
}
private int getDaysFromMap( int year, int month )
{
if ( CONVERSION_MAP.get( year ) == null )
{
throw new InvalidCalendarParametersException(
"Illegal PERSIAN year, must be between " + START_PERSIAN.getYear() + " and " +
STOP_PERSIAN.getYear() + ", was given " + year );
}
return CONVERSION_MAP.get( year )[month];
}
private DateInterval toYearIsoInterval( DateTimeUnit dateTimeUnit, int offset, int length )
{
DateTimeUnit from = new DateTimeUnit( dateTimeUnit );
if ( offset > 0 )
{
from = plusYears( from, offset );
}
else if ( offset < 0 )
{
from = minusYears( from, -offset );
}
DateTimeUnit to = new DateTimeUnit( from );
to = plusYears( to, length );
to = minusDays( to, length );
from = toIso( from );
to = toIso( to );
return new DateInterval( from, to, DateIntervalType.ISO8601_YEAR );
}
private DateInterval toMonthIsoInterval( DateTimeUnit dateTimeUnit, int offset, int length )
{
DateTimeUnit from = new DateTimeUnit( dateTimeUnit );
if ( offset > 0 )
{
from = plusMonths( from, offset );
}
else if ( offset < 0 )
{
from = minusMonths( from, -offset );
}
DateTimeUnit to = new DateTimeUnit( from );
to = plusMonths( to, length );
to = minusDays( to, 1 );
from = toIso( from );
to = toIso( to );
return new DateInterval( from, to, DateIntervalType.ISO8601_MONTH );
}
private DateInterval toWeekIsoInterval( DateTimeUnit dateTimeUnit, int offset, int length )
{
DateTimeUnit from = new DateTimeUnit( dateTimeUnit );
if ( offset > 0 )
{
from = plusWeeks( from, offset );
}
else if ( offset < 0 )
{
from = minusWeeks( from, -offset );
}
DateTimeUnit to = new DateTimeUnit( from );
to = plusWeeks( to, length );
to = minusDays( to, 1 );
from = toIso( from );
to = toIso( to );
return new DateInterval( from, to, DateIntervalType.ISO8601_WEEK );
}
private DateInterval toDayIsoInterval( DateTimeUnit dateTimeUnit, int offset, int length )
{
DateTimeUnit from = new DateTimeUnit( dateTimeUnit );
if ( offset >= 0 )
{
from = plusDays( from, offset );
}
else if ( offset < 0 )
{
from = minusDays( from, -offset );
}
DateTimeUnit to = new DateTimeUnit( from );
to = plusDays( to, length );
from = toIso( from );
to = toIso( to );
return new DateInterval( from, to, DateIntervalType.ISO8601_DAY );
}
private boolean contains( final int[] arr, final int key )
{
return Arrays.stream( arr ).anyMatch( i -> i == key );
}
// check if day is more than current maximum for month, don't overflow, just set to maximum
// set day of week
private void updateDateUnit( DateTimeUnit result )
{
int dm = getDaysFromMap( result.getYear(), result.getMonth() );
if ( result.getDay() > dm )
{
result.setDay( dm );
}
result.setDayOfWeek( weekday( result ) );
}
//------------------------------------------------------------------------------------------------------------
// Conversion map for Persian calendar
//
//------------------------------------------------------------------------------------------------------------
/**
* Map that gives an array of month lengths based on Persian year lookup.
* Index 1 - 12 is used for months, index 0 is used to give year total (lazy calculated).
*/
private static final Map<Integer, int[]> CONVERSION_MAP = new HashMap<>();
static
{
CONVERSION_MAP.put( 1353, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1354, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30 } );
CONVERSION_MAP.put( 1355, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1356, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1357, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1358, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30 } );
CONVERSION_MAP.put( 1359, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1360, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1361, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1362, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30 } );
CONVERSION_MAP.put( 1363, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1364, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1365, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1366, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30 } );
CONVERSION_MAP.put( 1367, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1368, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1369, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1370, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30 } );
CONVERSION_MAP.put( 1371, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1372, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1373, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1374, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1375, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30 } );
CONVERSION_MAP.put( 1376, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1377, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1378, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1379, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30 } );
CONVERSION_MAP.put( 1380, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1381, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1382, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1383, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30 } );
CONVERSION_MAP.put( 1384, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1385, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1386, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1387, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30 } );
CONVERSION_MAP.put( 1388, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1389, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1390, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1391, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30 } );
CONVERSION_MAP.put( 1392, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1393, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1394, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1395, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30 } );
CONVERSION_MAP.put( 1396, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1397, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1398, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1399, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30 } );
CONVERSION_MAP.put( 1400, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1401, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1402, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1403, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30 } );
CONVERSION_MAP.put( 1404, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1405, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1406, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1407, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1408, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30 } );
CONVERSION_MAP.put( 1409, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1410, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1411, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1412, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30 } );
CONVERSION_MAP.put( 1413, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1414, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1415, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1416, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30 } );
CONVERSION_MAP.put( 1417, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1418, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
CONVERSION_MAP.put( 1419, new int[]{ 0, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 } );
}
} |
venkatramanm/swf-all | swf-plugin-bugs/src/main/java/com/venky/swf/plugins/bugs/controller/NotesController.java | <gh_stars>1-10
package com.venky.swf.plugins.bugs.controller;
import java.util.List;
import com.venky.swf.controller.ModelController;
import com.venky.swf.path.Path;
import com.venky.swf.plugins.bugs.db.model.Note;
import com.venky.swf.views.HtmlView;
import com.venky.swf.views.model.ModelListView;
public class NotesController extends ModelController<Note> {
public NotesController(Path path) {
super(path);
}
protected HtmlView constructModelListView(List<Note> records,boolean isCompleteList){
return new ModelListView<Note>(getPath(), new String[]{"UPDATED_AT","NOTES","ATTACHMENT","CREATOR_USER_ID"},records,isCompleteList);
}
}
|
manbanpan/TrickEditPic | TrickEditPic/TrickEditPic/Puzzle-trick/puzzle/TcePuzzlePuzzleEditScrollView.h | //
// TcePuzzlePuzzleEditScrollView.h
// ConstellationCamera
//
// Created by zzb on 2019/1/9.
// Copyright © 2019年 ConstellationCamera. All rights reserved.
//
#import <UIKit/UIKit.h>
@class TcePuzzlePuzzleEditScrollView;
@protocol TcePuzzlePuzzleEditScrollViewDelegate <NSObject>
- (void)TcePuzzleTapWithEditView:(TcePuzzlePuzzleEditScrollView *)editView;
@end
@interface TcePuzzlePuzzleEditScrollView : UIScrollView
@property (nonatomic, assign) id<TcePuzzlePuzzleEditScrollViewDelegate> editDelegate;
@property (nonatomic, retain) UIBezierPath *TcePuzzleRealCellPath;
@property (nonatomic, retain) UIImageView *TcePuzzleImageView;
@property (nonatomic, assign) CGRect TcePuzzleOldRect;
- (void)setNotReloadFrame:(CGRect)frame;
- (void)setImageViewData:(UIImage *)image;
- (void)setImageViewData:(UIImage *)image rect:(CGRect)rect;
@end
/******************************************************************/
@class TSMneuLabel;
typedef void(^TSMneuLabelHandler)(TSMneuLabel * menuLabel);
typedef NS_ENUM(NSInteger, TSMneuLabelMenuType) {
TSMneuLabelTypeDefault,//啥也没有
TSMneuLabelTypeCopy = 1,//只有复制
TSMneuLabelTypeDemo,//栗子
};
typedef NS_ENUM(NSInteger, TSMneuLabelGestureType) {
TSMneuLabelGestureTypeNone,//强制不作处理
TSMneuLabelGestureTypeDefault = 0,//没赋值会走tap
TSMneuLabelGestureTypeTap,//默认单击
TSMneuLabelGestureTypeLongTap,//长按
};
@interface TSMneuLabel : UILabel
@property (assign, nonatomic)TSMneuLabelMenuType menuType;//弹窗类型
@property (assign, nonatomic)TSMneuLabelGestureType gestureType;//手势类型
@property (strong, nonatomic)TSMneuLabelHandler actionHandler;//暂时用不到 , 用于点击事件的往外传
/**
初始化方法
@param menuType 弹窗类型
@param gestureType 手势类型
@return 返回label
*/
+ (instancetype)mneuLabelWithMenuType:(TSMneuLabelMenuType)menuType
andGestureType:(TSMneuLabelGestureType)gestureType;
/**
初始化方法
@param menuType 弹窗类型
@param gestureType 手势类型
@return 返回label
*/
- (instancetype)initWithMenuType:(TSMneuLabelMenuType)menuType
andGestureType:(TSMneuLabelGestureType)gestureType;
/**
万能初始化方法
@param frame frame
@param menuType 弹窗类型
@param gestureType 手势类型
@return 返回label
*/
- (instancetype)initWithFrame:(CGRect)frame
andMenuType:(TSMneuLabelMenuType)menuType
andGestureType:(TSMneuLabelGestureType)gestureType;
@end
|
flogic/flogiston-cms | spec/models/layout_spec.rb | <gh_stars>1-10
require File.expand_path(File.join(File.dirname(__FILE__), *%w[.. spec_helper]))
describe Layout do
before :each do
@layout = Layout.spawn
end
describe 'attributes' do
it 'should have a handle' do
@layout.should respond_to(:handle)
end
it 'should allow setting and retrieving the handle' do
@layout.handle = 'test_handle'
@layout.save!
@layout.reload.handle.should == 'test_handle'
end
it 'should have contents' do
@layout.should respond_to(:contents)
end
it 'should allow setting and retrieving the contents' do
@layout.contents = 'Test Contents'
@layout.save!
@layout.reload.contents.should == 'Test Contents'
end
it 'should have format' do
@layout.should respond_to(:format)
end
it 'should allow setting and retrieving the format' do
@layout.format = 'haml'
@layout.save!
@layout.reload.format.should == 'haml'
end
it 'should have a default flag' do
@layout.should respond_to(:default)
end
it 'should allow setting and retrieving the default flag' do
@layout.default = true
@layout.save!
@layout.reload.default.should == true
end
end
describe 'validations' do
it 'should require handles to be unique' do
Layout.generate!(:handle => 'duplicate handle')
dup = Layout.generate(:handle => 'duplicate handle')
dup.errors.should be_invalid(:handle)
end
it 'should require handle' do
layout = Layout.generate(:handle => nil)
layout.errors.should be_invalid(:handle)
end
it 'should not check if the handle is valid according to the class' do
handle = '/some_crazy_handle'
Layout.expects(:valid_handle?).never
Layout.generate(:handle => handle)
end
end
it 'should have full contents' do
@layout.should respond_to(:full_contents)
end
describe 'full contents' do
it 'should accept a hash of replacements' do
lambda { @layout.full_contents({}) }.should_not raise_error(ArgumentError)
end
it 'should not require a hash of replacements' do
lambda { @layout.full_contents }.should_not raise_error(ArgumentError)
end
describe 'when no replacements are specified' do
it 'should be the layout contents in simple cases' do
contents = 'abba dabba'
@layout.contents = contents
@layout.full_contents.should == contents
end
it 'should include the contents of any referenced snippet' do
snippet_handle = 'testsnip'
snippet_contents = 'blah blah blah'
Snippet.generate!(:handle => snippet_handle, :contents => snippet_contents)
@layout = Layout.generate!(:contents => "big bag boom {{ #{snippet_handle} }} badaboom")
@layout.full_contents.should == "big bag boom #{snippet_contents} badaboom"
end
it 'should handle multiple snippet references' do
snippets = []
snippets.push Snippet.generate!(:handle => 'testsnip1', :contents => 'blah blah blah')
snippets.push Snippet.generate!(:handle => 'testsnip2', :contents => 'bing bang bong')
@layout = Layout.generate!(:contents => "big bag {{#{snippets[0].handle}}} boom {{ #{snippets[1].handle} }} badaboom")
@layout.full_contents.should == "big bag #{snippets[0].contents} boom #{snippets[1].contents} badaboom"
end
it 'should replace an unknown snippet reference with the empty string' do
@layout = Layout.generate!(:contents => "big bag boom {{ who_knows }} badaboom")
@layout.full_contents.should == "big bag boom badaboom"
end
it 'should format included snippet contents' do
snippet = Snippet.generate!(:handle => 'testsnip', :contents => 'blah *blah* blah', :format => 'markdown')
@layout = Layout.generate!(:contents => contents = "big bag boom {{ #{snippet.handle} }} badaboom")
@layout.full_contents.should == "big bag boom #{snippet.full_contents} badaboom"
end
it 'should correctly indent raw snippets used in HAML layouts' do
contents = {}
contents[:layout] = "
this
is
a
{{ thing }}
test
"
contents[:snippet] = "
really
crazy
blah
boing
boom
"
contents[:expected] = "
this
is
a
really
crazy
blah
boing
boom
test
"
contents.each { |k, v| v.strip! }
@layout = Layout.generate!(:format => 'haml', :contents => contents[:layout])
@snippet = Snippet.generate!(:format => 'raw', :contents => contents[:snippet], :handle => 'thing')
@layout.full_contents.should == contents[:expected]
end
it 'should also indent snippets used in non-HAML layouts' do
contents = {}
contents[:layout] = "
this
is
a
{{ thing }}
test
"
contents[:snippet] = "
really
crazy
blah
boing
boom
"
contents[:expected] = "
this
is
a
really
crazy
blah
boing
boom
test
"
contents.each { |k, v| v.strip! }
@layout = Layout.generate!(:format => 'erb', :contents => contents[:layout])
@snippet = Snippet.generate!(:format => 'raw', :contents => contents[:snippet], :handle => 'thing')
@layout.full_contents.should == contents[:expected]
end
it 'should keep spacing for replacements' do
contents = {}
contents[:layout] = "
this
is
a {{ thing }}
test
"
contents[:expected] = "
this
is
a blah
test
"
contents.each { |k, v| v.strip! }
@layout = Layout.generate!(:format => 'erb', :contents => contents[:layout])
@layout.full_contents(:thing => 'blah').should == contents[:expected]
end
it 'should keep spacing for line-starting replacements' do
contents = {}
contents[:layout] = "
this
is
a
{{ thing }}
test
"
contents[:expected] = "
this
is
a
blah
test
"
contents.each { |k, v| v.strip! }
@layout = Layout.generate!(:format => 'erb', :contents => contents[:layout])
@layout.full_contents(:thing => 'blah').should == contents[:expected]
end
end
describe 'when replacements are specified' do
before :each do
@replacements = { 'replacement' => 'This is the replacement'}
end
it 'should be the layout contents in simple cases and there are no replacement matches' do
contents = 'abba dabba'
@layout.contents = contents
@layout.full_contents(@replacements).should == contents
end
it 'should include the contents of any referenced snippet if it does not match a replacement' do
snippet_handle = 'testsnip'
snippet_contents = 'blah blah blah'
Snippet.generate!(:handle => snippet_handle, :contents => snippet_contents)
@layout = Layout.generate!(:contents => "big bag boom {{ #{snippet_handle} }} badaboom")
@layout.full_contents(@replacements).should == "big bag boom #{snippet_contents} badaboom"
end
it 'should handle multiple snippet references that do not match replacements' do
snippets = []
snippets.push Snippet.generate!(:handle => 'testsnip1', :contents => 'blah blah blah')
snippets.push Snippet.generate!(:handle => 'testsnip2', :contents => 'bing bang bong')
@layout = Layout.generate!(:contents => "big bag {{#{snippets[0].handle}}} boom {{ #{snippets[1].handle} }} badaboom")
@layout.full_contents(@replacements).should == "big bag #{snippets[0].contents} boom #{snippets[1].contents} badaboom"
end
it 'should replace a matched replacement with its replacement string' do
contents = 'abba dabba {{ replacement }} yabba dabba'
@layout.contents = contents
@layout.full_contents(@replacements).should == "abba dabba This is the replacement yabba dabba"
end
it 'should match replacements with symbol keys' do
replacements = { :replacement => 'This is the replacement' }
contents = 'abba dabba {{ replacement }} yabba dabba'
@layout.contents = contents
@layout.full_contents(replacements).should == "abba dabba This is the replacement yabba dabba"
end
it 'should prefer to use a snippet instead of a replacement when there is a conflict' do
snippet_handle = 'replacement'
snippet_contents = 'blah blah blah'
Snippet.generate!(:handle => snippet_handle, :contents => snippet_contents)
@layout = Layout.generate!(:contents => "big bag boom {{ #{snippet_handle} }} badaboom")
@layout.full_contents(@replacements).should == "big bag boom #{snippet_contents} badaboom"
end
it 'should replace an unknown snippet reference with the empty string' do
@layout = Layout.generate!(:contents => "big bag boom {{ who_knows }} badaboom")
@layout.full_contents(@replacements).should == "big bag boom badaboom"
end
end
end
describe 'to support pretending to be an ActionView Template' do
it 'should have a path without format and extension' do
@layout.should respond_to(:path_without_format_and_extension)
end
describe 'path_without_format_and_extension' do
before :each do
@layout.handle = 'some_template'
end
it 'should indicate this is a Layout object' do
@layout.path_without_format_and_extension.should include('Layout')
end
it 'should include the handle' do
@layout.path_without_format_and_extension.should include(@layout.handle)
end
end
it 'should render_template' do
@layout.should respond_to(:render_template)
end
describe 'render_template' do
before :each do
@layout.contents = 'contents go here, yes?'
@layout_full_contents = 'full contents'
@layout.stubs(:full_contents).returns(@layout_full_contents)
@layout_obj = ActionView::Template.new('')
@layout_obj.stubs(:render_template)
ActionView::Template.stubs(:new).returns(@layout_obj)
@view = 'some view'
@locals = { :this => :that, :other => :thing }
end
it 'should accept a view and local assigns' do
lambda { @layout.render_template(@view, @locals) }.should_not raise_error(ArgumentError)
end
it 'should accept just a view' do
lambda { @layout.render_template(@view) }.should_not raise_error(ArgumentError)
end
it 'should require a view' do
lambda { @layout.render_template }.should raise_error(ArgumentError)
end
it 'should initialize an ActionView::Template object with an empty argument' do
ActionView::Template.expects(:new).with('').returns(@layout_obj)
@layout.render_template(@view, @locals)
end
it "should get the layout full contents" do
@layout.expects(:full_contents).returns(@layout_full_contents)
@layout.render_template(@view, @locals)
end
it "should set the ActionView::Template object's source to the layout's full contents" do
@layout.render_template(@view, @locals)
@layout_obj.source.should == @layout_full_contents
end
it "should set the ActionView::Template object to recompile" do
@layout.render_template(@view, @locals)
@layout_obj.recompile?.should be_true
end
it "should set the ActionView::Template object's extension to the layout's format" do
format = 'haml'
@layout.format = format
@layout.render_template(@view, @locals)
@layout_obj.extension.should == format
end
it "should set the ActionView::Template object's extension to nil if the layout has no set format" do
format = nil
@layout.format = format
@layout.render_template(@view, @locals)
@layout_obj.extension.should == format
end
it 'should make the ActionView::Template object render the template with the given view and local assigns' do
@layout_obj.expects(:render_template).with(@view, @locals)
@layout.render_template(@view, @locals)
end
it 'should return the result of the rendering' do
@results = 'render results'
@layout_obj.stubs(:render_template).returns(@results)
@layout.render_template(@view, @locals).should == @results
end
it 'should default the local assigns to the empty hash' do
@layout_obj.expects(:render_template).with(@view, {})
@layout.render_template(@view)
end
end
it 'should refresh itself' do
@layout.should respond_to(:refresh)
end
describe 'refreshing' do
describe 'if the layout is not a new record' do
before :each do
@layout = Layout.generate!
end
it 'should simply reload' do
@layout.expects(:reload)
@layout.refresh
end
it 'should return itself' do
@layout.refresh.should == @layout
end
end
describe 'if the layout is a new record' do
before :each do
@layout = Layout.spawn
end
it 'should simply reload' do
@layout.expects(:reload).never
@layout.refresh
end
it 'should return itself' do
@layout.refresh.should == @layout
end
end
it 'should eventually be more efficient and check if a reload is necessary'
end
end
describe 'to support pretending to be an ActionView Template (view)' do
it "should indicate whether it's exempt from layout" do
@layout.should respond_to(:exempt_from_layout?)
end
describe "indicating whether it's exempt from layout" do
it 'should return false' do
@layout.exempt_from_layout?.should == false
end
end
end
it 'should be able to retrieve the default' do
Layout.should respond_to(:default)
end
describe 'retrieving the default' do
before do
Layout.delete_all
@layouts = Array.new(5) { Layout.generate!(:default => false) }
@default = @layouts[3]
@default.update_attributes!(:default => true)
end
it 'should return the Layout object marked as default' do
Layout.default.should == @default
end
it 'should return one of the Layout objects marked as default if there are multiple matches' do
defaults = @layouts.values_at(0,2,3)
defaults.each { |l| l.update_attributes!(:default => true) }
result = Layout.default
defaults.should include(result)
end
it 'should return nil if no Layout objects are marked as default' do
Layout.update_all(:default => false)
Layout.default.should be_nil
end
it 'should return nil if there are no Layout objects' do
Layout.delete_all
Layout.default.should be_nil
end
end
it 'should be able to set itself as the default' do
@layout.should respond_to(:make_default!)
end
describe 'setting itself as the default' do
before do
@layout = Layout.generate!(:default => false)
end
it 'should set and persist its default flag to true' do
@layout.make_default!
@layout.reload
@layout.default.should == true
end
it 'should set the default flag for all other layouts to false' do
5.times { Layout.generate!(:default => true) }
@layout.make_default!
Layout.count(:conditions => { :default => true }).should == 1
end
it 'should keep itself as default if already set to default' do
@layout.update_attributes!(:default => true)
@layout.make_default!
@layout.reload
@layout.default.should == true
end
end
end
|
alteryx/alteryx-ui | packages/icons/src/icons/procedure.js | import React from 'react';
import PropTypes from 'prop-types';
// Mui Example:
// https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/Avatar/Avatar.js#L38
// eslint-disable-next-line prefer-arrow-callback
const Procedure = React.forwardRef(function Procedure(props, ref) {
const { color, size, ...otherProps } = props;
const variantSizes = {
xsmall: 12,
small: 14,
medium: 16,
large: 20,
xlarge: 28,
xxlarge: 36,
};
const newSize = !isNaN(parseInt(size, 10))
? size
: variantSizes[size] !== undefined
? variantSizes[size]
: variantSizes['medium'];
return (
<svg
width={newSize}
height={newSize}
viewBox="0 0 24 24"
{...otherProps}
fill={color}
ref={ref}
>
<path d="M17.926 2A4.074 4.074 0 0122 6.074v11.852A4.074 4.074 0 0117.926 22H6.074A4.074 4.074 0 012 17.926V6.074A4.074 4.074 0 016.074 2h11.852zM7.925 4.222h-1.85c-1.024 0-1.853.83-1.853 1.852v11.852c0 1.023.83 1.852 1.852 1.852l1.851-.001V4.222zm9.972 7.1a1.177 1.177 0 01.15.267c.104.266.102.564-.007.828l-.018.042a1.078 1.078 0 01-.205.302l-3.97 3.97a1.111 1.111 0 11-1.57-1.571l2.052-2.055-4.181.001v6.671h7.778c1.023 0 1.852-.828 1.852-1.851V6.074c0-1.023-.83-1.852-1.852-1.852h-7.778v6.661h4.181L12.276 8.83a1.111 1.111 0 111.571-1.571l3.97 3.969.019.022-.038-.04.064.069.035.044z" />
</svg>
);
});
Procedure.propTypes = {
color: PropTypes.string,
size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
};
Procedure.defaultProps = {
color: 'currentColor',
size: '16',
};
// Hard coding component names and render names
Procedure.name = Procedure.render.name || 'Procedure';
export default Procedure;
|
carlos-sancho-ramirez/android-java-langbook | dbManager/src/test/java/sword/langbook3/android/db/RuleIdManager.java | package sword.langbook3.android.db;
import sword.database.DbValue;
final class RuleIdManager implements ConceptualizableSetter<ConceptIdHolder, RuleIdHolder> {
@Override
public RuleIdHolder getKeyFromInt(int key) {
return (key == 0)? null : new RuleIdHolder(key);
}
@Override
public RuleIdHolder getKeyFromDbValue(DbValue value) {
return getKeyFromInt(value.toInt());
}
@Override
public RuleIdHolder getKeyFromConceptId(ConceptIdHolder concept) {
return new RuleIdHolder(concept.key);
}
}
|
nataliesun/estatecloud-app | src/components/UserStats/UserStats.test.js | <filename>src/components/UserStats/UserStats.test.js
import React from 'react';
import { shallow } from 'enzyme';
import UserStats from './UserStats';
import { library } from '@fortawesome/fontawesome-svg-core';
import 'jest-canvas-mock';
import {
faDoorOpen, faPlusCircle, faPlus, faTimes
} from '@fortawesome/free-solid-svg-icons'
library.add(
faDoorOpen, // logo
faPlusCircle,
faPlus,
faTimes
)
describe(`UserStats Component`, () => {
it('should render correctly with no props', () => {
const component = shallow(<UserStats />);
expect(component).toMatchSnapshot();
});
//write test that only calls createAvailabilityChart function using jest
}) |
divad-nhok/obsidian_fork | src/world/testworld.hpp | //!
//! Contains tests for the world model.
//!
//! \file world/testworld.cpp
//! \author <NAME>
//! \date 2014
//! \license Affero General Public License version 3 or later
//! \copyright (c) 2014, NICTA
//!
#include <cmath>
#include "world/grid.hpp"
#include "world/kernel.hpp"
#include "world/interpolate.hpp"
#include "world/voxelise.hpp"
#include "world/transitions.hpp"
using namespace obsidian;
using namespace world;
|
Tarsnap/tarsnap-gui | src/widgets/tarsnapaccountdialog.cpp | #include "tarsnapaccountdialog.h"
WARNINGS_DISABLE
#include <QAbstractItemView>
#include <QDate>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
#include <QPushButton>
#include <QRegExp>
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QVariant>
#include <Qt>
#include "ui_logindialog.h"
WARNINGS_ENABLE
#include "TSettings.h"
#include "compat.h"
#include "debug.h"
#include "tarsnapaccount.h"
/* Forward declaration(s). */
class QWidget;
TarsnapAccountDialog::TarsnapAccountDialog(QWidget *parent)
: QDialog(parent), _ui(new Ui::LoginDialog), _popup(new QMessageBox())
{
// Basic UI.
_ui->setupUi(this);
setWindowFlags((windowFlags() | Qt::CustomizeWindowHint)
& ~Qt::WindowMaximizeButtonHint);
_popup->setParent(this->parentWidget());
_popup->setWindowModality(Qt::NonModal);
// Connection for basic UI.
connect(_ui->passwordLineEdit, &QLineEdit::textEdited, [this]() {
const bool empty_password = _ui->passwordLineEdit->text().isEmpty();
_ui->loginButton->setEnabled(!empty_password);
});
// Create the TarsnapAccount backend.
_ta = new TarsnapAccount();
// Act on password.
connect(this, &TarsnapAccountDialog::finished, this,
&TarsnapAccountDialog::processPasswordBox);
// Act on query response.
connect(_ta, &TarsnapAccount::gotTable, this,
&TarsnapAccountDialog::displayCSVTable);
connect(_ta, &TarsnapAccount::possibleWarning, this,
&TarsnapAccountDialog::showWarningIfApplicable);
// Pass signals onwards.
connect(_ta, &TarsnapAccount::accountCredit, this,
&TarsnapAccountDialog::accountCredit);
connect(_ta, &TarsnapAccount::lastMachineActivity, this,
&TarsnapAccountDialog::lastMachineActivity);
connect(_ta, &TarsnapAccount::getKeyId, this,
&TarsnapAccountDialog::getKeyId);
}
TarsnapAccountDialog::~TarsnapAccountDialog()
{
delete _popup;
delete _ta;
delete _ui;
}
void TarsnapAccountDialog::getAccountInfo(bool displayActivity,
bool displayMachineActivity)
{
// What type of info do we want?
_displayActivity = displayActivity;
_displayMachineActivity = displayMachineActivity;
// Get the username, or warn if there isn't one.
TSettings settings;
_user = settings.value("tarsnap/user", "").toString();
if(_user.isEmpty())
{
_popup->setWindowTitle(tr("Warning"));
_popup->setIcon(QMessageBox::Warning);
_popup->setText(tr("Tarsnap username must be set."));
_popup->open();
return;
}
// Send a message to get the key id and save it in "tarsnap/key_id".
emit getKeyId(settings.value("tarsnap/key", "").toString());
// ... while that's happening, ask the user for the password.
_ui->textLabel->setText(tr("Type password for account %1:").arg(_user));
_ui->loginButton->setEnabled(false);
open();
}
void TarsnapAccountDialog::processPasswordBox(int res)
{
// Bail (if applicable).
if(res == QDialog::Rejected)
return;
// Use password to get account info. This will only work if the key id
// has already been saved to "tarsnap/key_id" in TSettings.
_ta->getAccountInfo(_displayActivity, _displayMachineActivity,
_ui->passwordLineEdit->text());
// Attempt to remove password from memory. This is not as powerful as
// libcperciva's insecure_memzero(), but looking through the API docs and
// even the source code for QLineEdit hasn't suggested a better option.
_ui->passwordLineEdit->clear();
}
void TarsnapAccountDialog::displayCSVTable(const QString &csv,
const QString &title)
{
DEBUG << csv;
// Bail (if applicable).
if(csv.isEmpty() || csv.startsWith("<!DOCTYPE html>"))
return;
// Split output into lines.
QStringList lines = csv.split(QRegExp("[\r\n]"), SKIP_EMPTY_PARTS);
if(lines.count() <= 1)
return;
// Extract column headers.
QStringList columnHeaders = lines.first().split(',', SKIP_EMPTY_PARTS);
lines.removeFirst();
// Create new widget in which to display the table.
QDialog *csvDialog = new QDialog(this);
csvDialog->setWindowTitle(title);
csvDialog->setAttribute(Qt::WA_DeleteOnClose, true);
QTableWidget *table =
new QTableWidget(lines.count(), columnHeaders.count(), csvDialog);
table->setHorizontalHeaderLabels(columnHeaders);
table->horizontalHeader()->setStretchLastSection(true);
table->setAlternatingRowColors(true);
table->setEditTriggers(QAbstractItemView::NoEditTriggers);
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(table);
layout->setMargin(0);
csvDialog->setLayout(layout);
// Add the data to the table inside the new widget.
int row = 0;
int column = 0;
for(const QString &line : lines)
{
for(const QString &entry : line.split(',', KEEP_EMPTY_PARTS))
{
table->setItem(row, column, new QTableWidgetItem(entry));
column++;
}
row++;
column = 0;
}
// Show the widget to the user.
csvDialog->show();
}
void TarsnapAccountDialog::showWarningIfApplicable(const QByteArray &data)
{
// Check for an incorrect password.
if(data.contains("Password is incorrect; please try again."))
{
_popup->setWindowTitle(tr("Invalid password"));
_popup->setIcon(QMessageBox::Warning);
_popup->setText(
tr("Password for account %1 is incorrect; please try again.")
.arg(_user));
_popup->open();
return;
}
// Check for an invalid username.
if(data.contains("No user exists with the provided email "
"address; please try again."))
{
_popup->setWindowTitle(tr("Invalid username"));
_popup->setIcon(QMessageBox::Warning);
_popup->setText(
tr("Account %1 is invalid; please try again.").arg(_user));
_popup->open();
return;
}
}
|
zhouyihangcn/my-blog | blog-halo/src/main/java/cc/ryanc/halo/service/UserService.java | package cc.ryanc.halo.service;
import cc.ryanc.halo.model.domain.User;
import java.util.Date;
/**
* <pre>
* 用户业务逻辑接口
* </pre>
*
* @author : RYAN0UP
* @date : 2017/11/14
*/
public interface UserService {
/**
* 保存个人资料
*
* @param user user
*/
void save(User user);
/**
* 根据用户名和密码查询,用于登录
*
* @param userName userName
* @param userPass userPass
* @return User
*/
User userLoginByName(String userName, String userPass);
/**
* 根据邮箱和密码查询,用户登录
*
* @param userEmail userEmail
* @param userPass userPass
* @return User
*/
User userLoginByEmail(String userEmail, String userPass);
/**
* 查询所有用户
*
* @return User
*/
User findUser();
/**
* 根据用户编号和密码查询
*
* @param userId userid
* @param userPass user<PASSWORD>
* @return User
*/
User findByUserIdAndUserPass(Long userId, String userPass);
/**
* 修改禁用状态
*
* @param enable enable
*/
void updateUserLoginEnable(String enable);
/**
* 修改最后登录时间
*
* @param lastDate 最后登录时间
* @return User
*/
User updateUserLoginLast(Date lastDate);
/**
* 增加登录错误次数
*
* @return 登录错误次数
*/
Integer updateUserLoginError();
/**
* 修改用户的状态为正常
*
* @return User
*/
User updateUserNormal();
}
|
loremipsumjp/custom-base | proxy/lib/auth.js | 'use strict'
module.exports = factory
function factory() {
return function (req, res, next) {
const authorization = req.headers['authorization']
const buffer = new Buffer(authorization.split(' ')[1], 'base64')
const userId = buffer.toString().split(':')[0]
req.locals.user = { _id: userId }
return next()
}
}
|
matthiasblaesing/COMTypelibraries | office2/src/main/java/eu/doppel_helix/jna/tlb/office2/MsoGradientStyle.java | <gh_stars>10-100
package eu.doppel_helix.jna.tlb.office2;
import com.sun.jna.platform.win32.COM.util.IComEnum;
public enum MsoGradientStyle implements IComEnum {
/**
* (-2)
*/
msoGradientMixed(-2),
/**
* (1)
*/
msoGradientHorizontal(1),
/**
* (2)
*/
msoGradientVertical(2),
/**
* (3)
*/
msoGradientDiagonalUp(3),
/**
* (4)
*/
msoGradientDiagonalDown(4),
/**
* (5)
*/
msoGradientFromCorner(5),
/**
* (6)
*/
msoGradientFromTitle(6),
/**
* (7)
*/
msoGradientFromCenter(7),
;
private MsoGradientStyle(long value) {
this.value = value;
}
private long value;
public long getValue() {
return this.value;
}
} |
gsteri1/OG-Platform | projects/OG-Core/src/com/opengamma/core/position/impl/PortfolioNodeTraverser.java | <reponame>gsteri1/OG-Platform
/**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.core.position.impl;
import com.opengamma.core.position.PortfolioNode;
import com.opengamma.core.position.Position;
import com.opengamma.util.ArgumentChecker;
// REVIEW kirk 2010-01-02 -- One reason this class exists is so that you can parallel-apply
// many of the operations if they happen to be expensive. This isn't done yet, but the
// more code that depends on this class the easier it is to port to that system.
/**
* A manager for traversing the tree of nodes.
*/
public class PortfolioNodeTraverser {
/**
* Enumeration of traversal styles.
*/
public enum TraversalStyle {
/** Traverse the nodes depth-first. */
DEPTH_FIRST,
/** Traverse the nodes breadth-first. */
BREADTH_FIRST,
};
/**
* The traversal style.
*/
private final TraversalStyle _traversalStyle;
/**
* The callback.
*/
private final PortfolioNodeTraversalCallback _callback;
/**
* Creates a traverser using depth-first searching.
* If you don't know whether to use depth-first or breadth-first, then use depth-first.
*
* @param callback the callback to invoke, not null
* @return the traverser, not null
*/
public static PortfolioNodeTraverser depthFirst(PortfolioNodeTraversalCallback callback) {
return new PortfolioNodeTraverser(TraversalStyle.DEPTH_FIRST, callback);
}
/**
* Creates a traverser using breadth-first searching.
* If you don't know whether to use depth-first or breadth-first, then use depth-first.
*
* @param callback the callback to invoke, not null
* @return the traverser, not null
*/
public static PortfolioNodeTraverser breadthFirst(PortfolioNodeTraversalCallback callback) {
return new PortfolioNodeTraverser(TraversalStyle.BREADTH_FIRST, callback);
}
/**
* Creates a traverser.
*
* @param traversalStyle the style of traversal, not null
* @param callback the callback to invoke, not null
*/
public PortfolioNodeTraverser(TraversalStyle traversalStyle, PortfolioNodeTraversalCallback callback) {
ArgumentChecker.notNull(traversalStyle, "traversalStyle");
ArgumentChecker.notNull(callback, "callback");
// [PLAT-1431]
if (traversalStyle == TraversalStyle.BREADTH_FIRST) {
throw new UnsupportedOperationException("[PLAT-1431] - breadth first is not correctly implemented");
}
_traversalStyle = traversalStyle;
_callback = callback;
}
//-------------------------------------------------------------------------
/**
* Gets the traversal style to be used.
*
* @return the traversal style, not null
*/
public TraversalStyle getTraversalStyle() {
return _traversalStyle;
}
/**
* Gets the callback to be used.
*
* @return the callback, not null
*/
public PortfolioNodeTraversalCallback getCallback() {
return _callback;
}
//-------------------------------------------------------------------------
/**
* Traverse the nodes notifying using the callback.
*
* @param portfolioNode the node to start from, null does nothing
*/
public void traverse(PortfolioNode portfolioNode) {
if (portfolioNode == null) {
return;
}
traverse(portfolioNode, true);
}
/**
* Traverse the nodes.
*
* @param portfolioNode the node to start from, not null
* @param firstPass true if first pass
*/
protected void traverse(PortfolioNode portfolioNode, boolean firstPass) {
if (firstPass) {
getCallback().preOrderOperation(portfolioNode);
for (Position position : portfolioNode.getPositions()) {
getCallback().preOrderOperation(position);
}
}
switch (getTraversalStyle()) {
case DEPTH_FIRST:
assert firstPass == true;
for (PortfolioNode subNode : portfolioNode.getChildNodes()) {
traverse(subNode, true);
}
break;
case BREADTH_FIRST:
if (!firstPass) {
for (PortfolioNode subNode : portfolioNode.getChildNodes()) {
traverse(subNode, true);
}
for (PortfolioNode subNode : portfolioNode.getChildNodes()) {
traverse(subNode, false);
}
}
break;
default:
throw new IllegalStateException("Only DEPTH_FIRST and BREADTH_FIRST currently supported");
}
if (firstPass) {
for (Position position : portfolioNode.getPositions()) {
getCallback().postOrderOperation(position);
}
getCallback().postOrderOperation(portfolioNode);
}
}
}
|
tuix/tutorials | House_Price_Prediction/hpp_databroker/house_price_prediction_client.py | import grpc
from timeit import default_timer as timer
import logging
# import the generated classes
import model_pb2
import model_pb2_grpc
port = 8061
def run():
print("Calling HPP_Stub..")
with grpc.insecure_channel('localhost:{}'.format(port)) as channel:
stub = model_pb2_grpc.DatabrokerStub(channel)
ui_request = model_pb2.Empty()
response = stub.hppdatabroker(ui_request)
print("Greeter client received: ")
print(response)
if __name__ == '__main__':
logging.basicConfig()
run()
|
Hupengyu/Paddle_learning | img_opt/compress_img.py | <reponame>Hupengyu/Paddle_learning<filename>img_opt/compress_img.py
from PIL import Image
import cv2
import os
def compress_img(image, img_path, cover_ori_img=True, img_size_thresh_KB=1000):
os_size = os.path.getsize(img_path) # 返回字节数
img_size = os_size / 1024
if img_size < img_size_thresh_KB:
return image
else:
if cover_ori_img:
image = image.copy() # 将原图复制,使用copy的图片,并最后重新命名
img = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
img_width, img_height = img.size
while img_size > img_size_thresh_KB:
img.thumbnail((int(img_width / 2), int(img_height / 2)), Image.ANTIALIAS)
ori_img_name, img_suffix = os.path.splitext(img_path) # ('imgs/01_oppo', '.jpg')
copy_img_path = ori_img_name + '_copy' + img_suffix
img.save(copy_img_path)
img = Image.open(copy_img_path)
img_width, img_height = img.size
img_size = os.path.getsize(copy_img_path) / 1024 # 返回字节数
img_compressed = cv2.imread(copy_img_path)
return img_compressed
else:
img = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
img_width, img_height = img.size
while img_size > img_size_thresh_KB:
img.thumbnail((int(img_width/2), int(img_height/2)), Image.ANTIALIAS)
img.save(img_path)
img = Image.open(img_path)
img_width, img_height = img.size
img_size = os.path.getsize(img_path) / 1024 # 返回字节数
img_compressed = cv2.imread(img_path)
return img_compressed
if __name__ == '__main__':
img_path = 'imgs/01_oppo.jpg'
img = cv2.imread(img_path)
img_compressed = compress_img(img, img_path) # 默认覆盖,默认大小为1000KB
cv2.imshow('aa', img_compressed)
cv2.waitKey() |
Marthox1999/UV-Energy | front/uv-energy-front/src/views/Administrador-Configurar/SetInvoices.js | import React from "react";
import axios from 'axios';
// reactstrap components
import {
Button,
Card,
CardHeader,
CardBody,
Form,
Input,
Container,
Row,
Col,
Table,
Alert,
} from "reactstrap";
// core components
import 'leaflet/dist/leaflet.css';
import Cookies from 'universal-cookie';
import { withTranslation } from 'react-i18next';
import i18n from '../../i18n.js';
// core components
import UVHeader from "components/Headers/UVHeader.js";
const c = require('../constants')
const cookie = new Cookies();
class SetInvoices extends React.Component {
constructor(props){
super(props);
this.state = {
residencial: ["416.58715",
"446.64775",
"548.2377",
"592.6894",
"711.2273"],
industrial: ["711.2273",
"711.2273",
"711.2273",
"711.2273",
"711.2273"],
mora:"1",
alertSuccess:false,
credentials: cookie.get('notCredentials'),
isInvalidNumber: false
}
this.onChangeStratum = this.onChangeStratum.bind(this);
this.onChangeMora = this.onChangeMora.bind(this);
this.getInitState = this.getInitState.bind(this);
this.checkNumbers = this.checkNumbers.bind(this);
}
onChangeStratum(e){
const target = e.target;
const value = target.value;
const estrato = target.name[target.name.length-1];
const tipo = target.name.substring(0, target.name.length-1);
const temp = this.state[tipo];
temp[parseInt(estrato,10)]=value;
this.setState({
[tipo]: temp,
isInvalidNumber: false
});
}
onChangeMora(e){
this.setState({
mora:e.target.value
})
}
getInitState(){
let obj = new Object();
obj.residencial=["416.58715",
"446.64775",
"548.2377",
"592.6894",
"711.2273"];
obj.industrial=["711.2273",
"711.2273",
"711.2273",
"711.2273",
"711.2273"];
obj.mora="1";
obj.isInvalidNumber=false;
return obj;
}
checkNumbers(){
let isNumber = (number) => /^(\d+(\.\d+)?|\.\d+)$/.test(number);
let numeroResidencial = this.state.residencial.every(isNumber)
let numeroIndustrial = this.state.industrial.every(isNumber);
//Si alguno no es número
if(!(isNumber(this.state.mora) && numeroResidencial && numeroIndustrial)){
this.setState({
isInvalidNumber:true
})
return false;
}
this.setState({
isInvalidNumber:false
})
return true;
}
SubmitEvent(buttonVal){
//Si buttonVal es 1
if(buttonVal===1){
this.setState(this.getInitState());
return;
}
//Si buttonVal es 2
//Verificar que sean números, si alguno no lo es entonces no post
if(!this.checkNumbers()){
return;
}
axios.post(c.api + 'sales/generateInvoices/',
{
residencial: this.state.residencial,
industrial: this.state.industrial,
mora:this.state.mora,
},
{headers: { 'Authorization' : `Token ${this.state.credentials.token}`}})
.then( response => {
this.setState(this.getInitState());
this.setState({
alertSuccess: true
})
}).catch(
error => {
alert(i18n.t("Settings.Error.1"));
console.log(error.response.request.responseText);
}
)
}
render() {
const { t } = this.props
return(
<>
<UVHeader />
{/* Page content */}
<Container className="mt--7" fluid>
<Card className="bg-secondary shadow">
<CardHeader className="bg-white border-0">
<Row className="align-items-center">
<Col xs="8">
<font size="5">{t("Settings.SetUpInvoices.1")}</font>
</Col>
</Row>
</CardHeader>
<CardBody>
<Form>
<h6 className="heading-small text-muted mb-4">
{t("Settings.StratumInformation.1")}
</h6>
<Alert color="warning" isOpen={this.state.isInvalidNumber}>
{t("Settings.Invalid.1")}
</Alert>
<Alert color="success" isOpen={this.state.alertSuccess}>
{t("Settings.Success.2")}
</Alert>
{/**
* Tabla de estratos
*/}
<Table className="align-items-center table-flush" responsive>
<thead className="thead-light">
<tr>
<th scope="col"><font size="2"></font>
</th>
<th scope="col"><font size="2">
<center>
{t("Settings.Residential.1")}
</center></font>
</th>
<th scope="col"><font size="2">
<center>
{t("Settings.Industrial.1")}
</center></font>
</th>
</tr>
</thead>
<tbody>
{[...Array(5).keys()].map((indexStratum)=>
<tr>
<td>
{t("Settings.Stratum.1")} {indexStratum+1}
</td>
<td>
<center>
<Input
required
className="form-control-alternative"
name={"residencial"+indexStratum}
placeholder={t("Settings.Residential.1")}
type="number"
value={this.state.residencial[indexStratum]}
onChange={this.onChangeStratum}
/>
</center>
</td>
<td>
<center>
<Input
required
className="form-control-alternative"
name={"industrial"+indexStratum}
placeholder={t("Settings.Industrial.1")}
type="number"
value={this.state.industrial[indexStratum]}
onChange={this.onChangeStratum}
/>
</center>
</td>
</tr>
)}
</tbody>
</Table>
<hr className="my-4"></hr>
{/**
* Porcentaje de mora
*/}
<h6 className="heading-small text-muted mb-4">
{t("Settings.DebtInformation.1")}
</h6>
<label
className="form-control-label"
htmlFor="input-first-name"
>
{t("Settings.DebtPercentage.1")} (%)
</label>
<Input
required
className="form-control-alternative"
name="mora"
placeholder={t("Settings.DebtPercentage.1")}
type="number"
value={this.state.mora}
onChange={this.onChangeMora}
/>
<div className="text-center">
<Button className="mt-4" color="primary" onClick={ () => this.SubmitEvent(1) }>
{t("Settings.Default.1")}
</Button>
<Button className="mt-4" color="primary" onClick={ () => this.SubmitEvent(2) }>
{t("Settings.GenerateInvoices.1")}
</Button>
</div>
</Form>
</CardBody>
</Card>
</Container>
</>
);
}
}
export default withTranslation()(SetInvoices); |
BlackCatInTheWhite/jiayouzhanjianguan | src/main/java/com/aaa/project/system/gas/mapper/GasMapper.java | <filename>src/main/java/com/aaa/project/system/gas/mapper/GasMapper.java
package com.aaa.project.system.gas.mapper;
import com.aaa.project.system.gas.domain.Gas;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 加油站 数据层
*
* @author aaa
* @date 2019-04-22
*/
public interface GasMapper
{
/**
* 查询加油站信息
*
* @param gasId 加油站ID
* @return 加油站信息
*/
public Gas selectGasById(Integer gasId);
/**
* 查询加油站列表对巡检
*
* @param gas 加油站信息
* @return 加油站集合
*/
public List<Gas> selectGasMission(Gas gas);
/**
* 查询加油站列表
*
* @param gas 加油站信息
* @return 加油站集合
*/
public List<Gas> selectGasList(Gas gas);
/**
* 新增加油站
*
* @param gas 加油站信息
* @return 结果
*/
public int insertGas(Gas gas);
/**
* 修改加油站
*
* @param gas 加油站信息
* @return 结果
*/
public int updateGas(Gas gas);
/**
* 删除加油站
*
* @param gasId 加油站ID
* @return 结果
*/
public int deleteGasById(Integer gasId);
/**
* 批量删除加油站
*
* @param gasIds 需要删除的数据ID
* @return 结果
*/
public int deleteGasByIds(String[] gasIds);
/**
* 巡查人员的历史加油站
*/
public List<Gas> selectArrayGas(@Param("policemanid") int aa);
} |
oxygenxml/oxygen-dita-references-view-addon | src/main/java/com/oxygenxml/ditareferences/workspace/KeysProvider.java | /**
*
*/
package com.oxygenxml.ditareferences.workspace;
import java.net.URL;
import java.util.LinkedHashMap;
import ro.sync.ecss.dita.reference.keyref.KeyInfo;
/**
* @author Alexandra_Dinisor
*
*/
public interface KeysProvider {
/**
* Get the LinkedHashMap with KeyInfo for key references from the current DITAMAP.
*/
LinkedHashMap<String, KeyInfo> getKeys(URL editorLocation);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.