repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
AriDine/MotoWallet
|
nuttx/drivers/power/battery_temp.c
|
<gh_stars>1-10
/*
* Copyright (C) 2016 Motorola Mobility, LLC.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <debug.h>
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <nuttx/device.h>
#include <nuttx/device_battery_temp.h>
#include <nuttx/power/battery_state.h>
#include "battery_temp.h"
/* Battery temperature zones */
enum battery_temp_zone_e {
BATTERY_COLD,
BATTERY_COOL,
BATTERY_NORMAL,
BATTERY_WARM,
BATTERY_HOT,
BATTERY_COOL_DOWN
};
struct battery_temp_info_s {
struct device *dev; /* device for temp measurements */
bool available; /* are temp measurements available ? */
enum battery_temp_zone_e zone; /* current zone */
};
static struct battery_temp_info_s *g_info; /* for battery_temp_stop() */
/* Helper function */
static void battery_temp_set_zone(struct battery_temp_info_s *info,
enum battery_temp_zone_e new_zone)
{
enum batt_temp_e state; /* new battery state temp */
int min, max; /* new temp limits */
info->zone = new_zone;
/* Determine new battery state temp and limits */
switch (new_zone) {
case BATTERY_COLD:
state = BATTERY_TEMP_NO_CHARGING;
min = INT_MIN;
max = CONFIG_BATTERY_TEMP_COLD + CONFIG_BATTERY_TEMP_HYST;
break;
case BATTERY_COOL:
state = BATTERY_TEMP_REDUCED_CHARGING;
min = CONFIG_BATTERY_TEMP_COLD;
max = CONFIG_BATTERY_TEMP_COOL + CONFIG_BATTERY_TEMP_HYST;
break;
case BATTERY_NORMAL:
state = BATTERY_TEMP_NORMAL;
min = CONFIG_BATTERY_TEMP_COOL;
max = CONFIG_BATTERY_TEMP_WARM;
break;
case BATTERY_WARM:
state = BATTERY_TEMP_REDUCED_CHARGING;
min = CONFIG_BATTERY_TEMP_WARM - CONFIG_BATTERY_TEMP_HYST;
max = CONFIG_BATTERY_TEMP_HOT;
break;
case BATTERY_HOT:
state = BATTERY_TEMP_NO_CHARGING;
min = CONFIG_BATTERY_TEMP_HOT - CONFIG_BATTERY_TEMP_HYST;
max = CONFIG_BATTERY_TEMP_COOL_DOWN;
break;
case BATTERY_COOL_DOWN:
state = BATTERY_TEMP_COOL_DOWN;
min = CONFIG_BATTERY_TEMP_COOL_DOWN - CONFIG_BATTERY_TEMP_HYST;
max = INT_MAX;
break;
default:
/* Should never be here! */
return;
}
battery_state_set_temp(state);
device_batt_temp_set_limits(info->dev, min, max);
}
/* Device driver callback */
static void battery_limits_cb(void *arg, bool min)
{
struct battery_temp_info_s *info = arg;
enum battery_temp_zone_e new_zone = BATTERY_NORMAL;
/* Transition to a new temp zone */
switch (info->zone) {
case BATTERY_COLD:
new_zone = BATTERY_COOL;
break;
case BATTERY_COOL:
new_zone = min ? BATTERY_COLD : BATTERY_NORMAL;
break;
case BATTERY_NORMAL:
new_zone = min ? BATTERY_COOL : BATTERY_WARM;
break;
case BATTERY_WARM:
new_zone = min ? BATTERY_NORMAL : BATTERY_HOT;
break;
case BATTERY_HOT:
new_zone = min ? BATTERY_WARM : BATTERY_COOL_DOWN;
break;
case BATTERY_COOL_DOWN:
new_zone = BATTERY_HOT;
break;
default:
/* Should never be here !*/
break;
}
battery_temp_set_zone(info, new_zone);
}
/* Device driver callback */
static void battery_available_cb(void *arg, bool available)
{
struct battery_temp_info_s *info = arg;
int temperature;
if (!info->available && available) {
/*
* Determine initial zone based on current temperature. Choose stricter
* zone if temp is equal to the threshold. Device driver temp callbacks
* will be used to transition between zones.
*/
info->available = true;
if (device_batt_temp_get_temperature(info->dev, &temperature))
battery_temp_set_zone(info, BATTERY_COOL_DOWN);
else if (temperature <= CONFIG_BATTERY_TEMP_COLD )
battery_temp_set_zone(info, BATTERY_COLD);
else if (temperature <= CONFIG_BATTERY_TEMP_COOL)
battery_temp_set_zone(info, BATTERY_COOL);
else if (temperature < CONFIG_BATTERY_TEMP_WARM)
battery_temp_set_zone(info, BATTERY_NORMAL);
else if (temperature < CONFIG_BATTERY_TEMP_HOT)
battery_temp_set_zone(info, BATTERY_WARM);
else if (temperature < CONFIG_BATTERY_TEMP_COOL_DOWN)
battery_temp_set_zone(info, BATTERY_HOT);
else
battery_temp_set_zone(info, BATTERY_COOL_DOWN);
} else if (info->available && !available) {
info->available = false;
battery_state_set_temp(BATTERY_TEMP_UNAVAILABLE);
}
}
int battery_temp_start(void)
{
struct battery_temp_info_s *info;
int ret;
battery_state_set_temp(BATTERY_TEMP_UNAVAILABLE);
info = zalloc(sizeof(*info));
if (!info) {
dbg("failed to allocate memory\n");
return -ENOMEM;
}
info->dev = device_open(DEVICE_TYPE_BATTERY_TEMP_HW, 0);
if (!info->dev) {
dbg("failed to open battery temp device\n");
ret = EIO;
goto error;
}
ret = device_batt_temp_register_limits_cb(info->dev, battery_limits_cb, info);
if (ret) {
dbg("failed to register battery limits callback\n");
goto error;
}
ret = device_batt_temp_register_available_cb(info->dev, battery_available_cb,
info);
if (ret) {
dbg("failed to register battery available callback\n");
goto error;
}
g_info = info;
return 0;
error:
if (info->dev)
device_close(info->dev);
free(info);
return ret;
}
void battery_temp_stop(void)
{
if (g_info && g_info->dev)
device_close(g_info->dev);
free(g_info);
}
|
dreamsxin/ultimatepp
|
bazaar/kissfir/kissfir.h
|
#ifndef _kissfir_kissfir_h
#define _kissfir_kissfir_h
#include <Core/Core.h>
using namespace Upp;
#include <plugin/kissfft/kissfft.h>
#endif
|
tychobrailleur/mvnizer
|
lib/mvnizer/task_helper.rb
|
require 'fileutils'
require 'nokogiri'
module Mvnizer
# The +TaskHelper+ provides different functions that can be used in tasks,
# such as function to create directories, generate files from templates, etc.
module TaskHelper
# path to the template location.
TEMPLATE_DIR = File.expand_path(File.join(File.dirname(__FILE__), 'templates'))
# creates recursively all directories passed as a param.
def create_dir(*dir)
dir.each { |d| FileUtils.mkdir_p d }
end
# generates the file +destination_file+ from template +template+
# and object +binding+. +binding+ must be an ERB binding.
# +destination_file+ must be the aboslute location to the generated
# file.
# If the output folder in which the file gets generated does not exist,
# it automatically gets created.
def generate_file(template, destination_file, binding)
dir = File.dirname(destination_file)
create_dir(dir) unless File.exists?(dir)
template = File.open(template, 'r').read
File.open(destination_file, "w") do |f|
f.write(ERB.new(template).result(binding.get_binding))
end
end
# adds a list of dependencies to the pom file whose location
# can be given as +pom_location+. By default, this function
# looks up the pom in the current directory.
def add_dependency(dependency, pom_location = File.join(Dir.pwd, "pom.xml"))
raise FileNotFoundError, "The pom.xml file cannot be found." unless File.exists?(pom_location)
coordinate_parser = CoordinateParser.new
pom = Nokogiri::XML(File.open(pom_location)) do |c|
c.noblanks
end
dependencies_node = pom.xpath("/pom:project/pom:dependencies", {"pom" => "http://maven.apache.org/POM/4.0.0"}).first
dependency.each do |d|
# First parse the dependency coordinates
dep_project = coordinate_parser.parse_scoped_coordinates(d)
Nokogiri::XML::Builder.with(dependencies_node) do |xml|
xml.dependency {
xml.groupId dep_project.group_id
xml.artifactId dep_project.artifact_id
xml.version dep_project.version
xml.scope dep_project.scope if dep_project.scope != nil && dep_project.scope != "compile"
xml.type dep_project.type if dep_project.type != "jar"
}
end
end
# Requires sparklemotion/nokogiri#772 to produce
# identical pom files in both MRI and JRuby.
pom.to_xml(indent: 2)
end
end
end
|
brianv0/rucio
|
lib/rucio/core/monitor.py
|
<filename>lib/rucio/core/monitor.py<gh_stars>0
# Copyright European Organization for Nuclear Research (CERN)
#
# 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
#
# Authors:
# - <NAME>, <<EMAIL>>, 2013
from pystatsd import Client
from rucio.common.config import config_get
import time
server = config_get('monitor', 'carbon_server')
port = config_get('monitor', 'carbon_port')
scope = config_get('monitor', 'user_scope')
pystatsd_client = Client(host=server, port=port, prefix=scope)
def record_counter(counters, delta=1):
"""
Log one or more counters by arbitrary amounts
:param counters: The counter or a list of counters to be updated.
:param delta: The increment for the counter, by default increment by 1.
"""
pystatsd_client.update_stats(counters, delta)
def record_gauge(stat, value):
"""
Log gauge information for a single stat
:param stat: The name of the stat to be updated.
:param value: The value to log.
"""
pystatsd_client.gauge(stat, value)
def record_timer(stat, time):
"""
Log timing information for a single stat (in miliseconds)
:param stat: The name of the stat to be updated.
:param value: The time to log.
"""
pystatsd_client.timing(stat, time)
class record_timer_block(object):
"""
A context manager for timing a block of code.
:param stats: The name of the stat or list of stats that should be updated.
Each stat can be a simple string or a tuple (string, divisor)
Usage:
with monitor.record_timer_block('test.context_timer'):
stuff1()
stuff2()
with monitor.record_timer_block(['test.context_timer', ('test.context_timer_normalised', 10)]):
stuff1()
stuff2()
"""
def __init__(self, stats):
if not isinstance(stats, list):
stats = [stats]
self.stats = stats
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, typ, value, tb):
dt = time.time() - self.start
ms = int(round(1000 * dt)) # Convert to ms.
for s in self.stats:
if isinstance(s, str):
record_timer(s, ms)
elif isinstance(s, tuple):
if s[1] != 0:
ms = ms / s[1]
record_timer(s[0], ms)
|
ExplorableGraph/hello
|
demos/hello/graphs/6.js
|
const letters = ["a", "b", "c", "d", "e", "f", "g", "i", "j"];
const routes = ["index.html", ...letters];
class HelloGraph {
async *[Symbol.asyncIterator]() {
yield* routes;
}
async get(key) {
if (key === "index.html") {
const links = letters
.map((letter) => `<li><a href="${letter}">${letter}</a></li>`)
.join("");
return `<ul>${links}</ul>`;
} else if (key === "secret") {
return "You have found the secret page!";
} else {
return `Hello, ${key}.`;
}
}
}
export default new HelloGraph();
|
Saisimon/AGTMS
|
agtms-parent/agtms-web/src/main/java/net/saisimon/agtms/web/controller/main/ManagementMainController.java
|
package net.saisimon.agtms.web.controller.main;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import net.saisimon.agtms.core.annotation.ControllerInfo;
import net.saisimon.agtms.core.annotation.Operate;
import net.saisimon.agtms.core.annotation.ResourceInfo;
import net.saisimon.agtms.core.dto.Result;
import net.saisimon.agtms.core.enums.Functions;
import net.saisimon.agtms.core.enums.OperateTypes;
import net.saisimon.agtms.web.constant.ErrorMessage;
import net.saisimon.agtms.web.dto.req.ExportParam;
import net.saisimon.agtms.web.service.main.ManagementMainService;
/**
* 自定义对象管理主控制器
*
* @author saisimon
*
*/
@RestController
@RequestMapping("/management/main/{key}")
@ControllerInfo(value="management", link="/management/main")
public class ManagementMainController {
@Autowired
private ManagementMainService managementMainService;
@ResourceInfo(func=Functions.VIEW)
@PostMapping("/grid")
public Result grid(@PathVariable("key") String key) {
return managementMainService.grid(key);
}
@ResourceInfo(func=Functions.VIEW)
@Operate(type=OperateTypes.QUERY, value="list")
@PostMapping("/list")
public Result list(@PathVariable("key") String key, @RequestBody Map<String, Object> body) {
return managementMainService.list(key, body);
}
@ResourceInfo(func=Functions.REMOVE)
@Operate(type=OperateTypes.REMOVE)
@PostMapping("/remove")
public Result remove(@PathVariable("key") String key, @RequestParam(name = "id") Long id) {
return managementMainService.remove(key, id);
}
@ResourceInfo(func={ Functions.BATCH_EDIT, Functions.BATCH_REMOVE, Functions.EXPORT, Functions.IMPORT })
@PostMapping("/batch/grid")
public Result batchGrid(@PathVariable("key") String key, @RequestParam("type") String type, @RequestParam("func") String func) {
return managementMainService.batchGrid(key, type, func);
}
@ResourceInfo(func=Functions.BATCH_EDIT)
@Operate(type=OperateTypes.BATCH_EDIT)
@PostMapping("/batch/save")
public Result batchSave(@PathVariable("key") String key, @RequestBody Map<String, Object> body) {
return managementMainService.batchSave(key, body);
}
@ResourceInfo(func=Functions.BATCH_REMOVE)
@Operate(type=OperateTypes.BATCH_REMOVE)
@PostMapping("/batch/remove")
public Result batchRemove(@PathVariable("key") String key, @RequestBody Map<String, Object> body) {
return managementMainService.batchRemove(key, body);
}
@ResourceInfo(func=Functions.EXPORT)
@Operate(type=OperateTypes.EXPORT)
@PostMapping("/batch/export")
public Result batchExport(@PathVariable("key") String key, @Validated @RequestBody ExportParam body, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return ErrorMessage.Common.MISSING_REQUIRED_FIELD;
}
return managementMainService.batchExport(key, body);
}
@ResourceInfo(func=Functions.IMPORT)
@Operate(type=OperateTypes.IMPORT)
@PostMapping("/batch/import")
public Result batchImport(@PathVariable("key") String key,
@RequestParam(name="importFileName", required=false) String importFileName,
@RequestParam("importFileType") String importFileType,
@RequestParam("importFields") List<String> importFields,
@RequestParam("importFiles") MultipartFile[] importFiles) {
return managementMainService.batchImport(key, importFileName, importFileType, importFields, importFiles);
}
}
|
dariadomagala/busola
|
core-ui/src/components/Lambdas/helpers/resources/memoryHelpers.js
|
<filename>core-ui/src/components/Lambdas/helpers/resources/memoryHelpers.js<gh_stars>10-100
import bytes from 'bytes-iec';
export function normalizeMemory(memory = '') {
if (!memory) {
return 0;
}
const memoryWithSuffix = memory.endsWith('B') ? memory : `${memory}B`;
return bytes(memoryWithSuffix) || 0;
}
export function compareMemory(limit = '', current = '') {
if (!limit || !current) {
return;
}
const normalizedLimit = normalizeMemory(limit);
const normalizedCurrent = normalizeMemory(current);
return normalizedLimit <= normalizedCurrent;
}
|
JamesLinus/OS-Zero
|
usr/lib/vec/op.c
|
<reponame>JamesLinus/OS-Zero
#if 0
#include <stdio.h>
#include <stdlib.h>
#include <vec/vec.h>
/* add two vectors */
struct vec *
vcaddv(struct vec *src, struct vec *dest)
{
struct vec *vec = NULL;
size_t n = dest->nval;
long t = dest->type;
vcint ival1;
vcint ival2;
vcfloat dval1;
vcfloat dval2;
long l;
if (n != src->nval) {
return NULL;
}
if (src->type != t) {
return NULL;
}
vec = malloc(sizeof(struct vec));
vec->type = t;
vec->nval = n;
vec->data = malloc(n * sizeof(struct vcval));
if (t == VC_INT) {
for (l = 0 ; l < n ; l++) {
ival1 = dest->data[l].data.i;
ival2 = src->data[l].data.i;
vec->data[l].data.i = ival1 + ival2;
}
} else if (t == VC_FLOAT) {
for (l = 0 ; l < n ; l++) {
dval1 = dest->data[l].data.f;
dval2 = src->data[l].data.f;
vec->data[l].data.f = dval1 + dval2;
}
} else {
fprintf(stderr, "invalid argument type for addition: %lx\n", t);
free(vec->data);
free(vec);
vec = NULL;
}
return vec;
}
/* subtract vector src from vector dest */
struct vec *
vcsubv(struct vec *src, struct vec *dest)
{
struct vec *vec = NULL;
size_t n = dest->nval;
long t = dest->type;
vcint ival1;
vcint ival2;
vcfloat dval1;
vcfloat dval2;
long l;
if (n != src->nval) {
return NULL;
}
if (src->type != t) {
return NULL;
}
vec = malloc(sizeof(struct vec));
vec->type = t;
vec->nval = n;
vec->data = malloc(n * sizeof(struct vcval));
if (t == VC_INT) {
for (l = 0 ; l < n ; l++) {
ival1 = dest->data[l].data.i;
ival2 = src->data[l].data.i;
vec->data[l].data.i = ival1 - ival2;
}
} else if (t == VC_FLOAT) {
for (l = 0 ; l < n ; l++) {
dval1 = dest->data[l].data.f;
dval2 = src->data[l].data.f;
vec->data[l].data.f = dval1 - dval2;
}
} else {
fprintf(stderr, "invalid argument type for subtraction: %lx\n", t);
free(vec->data);
free(vec);
vec = NULL;
}
return vec;
}
/* multiply vector src by vector dest */
struct vec *
vcmulv(struct vec *src, struct vec *dest)
{
struct vec *vec = NULL;
size_t n = dest->nval;
long t = dest->type;
vcint ival1;
vcint ival2;
vcfloat dval1;
vcfloat dval2;
long l;
if (n != src->nval) {
return NULL;
}
if (src->type != t) {
return NULL;
}
vec = malloc(sizeof(struct vec));
vec->type = t;
vec->nval = n;
vec->data = malloc(n * sizeof(struct vcval));
if (t == VC_INT) {
for (l = 0 ; l < n ; l++) {
ival1 = dest->data[l].data.i;
ival2 = src->data[l].data.i;
vec->data[l].data.i = ival1 * ival2;
}
} else if (t == VC_FLOAT) {
for (l = 0 ; l < n ; l++) {
dval1 = dest->data[l].data.f;
dval2 = src->data[l].data.f;
vec->data[l].data.f = dval1 * dval2;
}
} else {
fprintf(stderr, "invalid argument type for multiplication: %lx\n", t);
free(vec->data);
free(vec);
vec = NULL;
}
return vec;
}
/* divide vector src by vector dest */
struct vec *
vcdivv(struct vec *src, struct vec *dest)
{
struct vec *vec = NULL;
size_t n = dest->nval;
long t = dest->type;
vcint ival1;
vcint ival2;
vcfloat dval1;
vcfloat dval2;
long l;
if (n != src->nval) {
return NULL;
}
if (src->type != t) {
return NULL;
}
vec = malloc(sizeof(struct vec));
vec->type = t;
vec->nval = n;
vec->data = malloc(n * sizeof(struct vcval));
if (t == VC_INT) {
for (l = 0 ; l < n ; l++) {
ival1 = dest->data[l].data.i;
ival2 = src->data[l].data.i;
vec->data[l].data.i = ival1 / ival2;
}
} else if (t == VC_FLOAT) {
for (l = 0 ; l < n ; l++) {
dval1 = dest->data[l].data.f;
dval2 = src->data[l].data.f;
vec->data[l].data.f = dval1 / dval2;
}
} else {
fprintf(stderr, "invalid argument type for division: %lx\n", t);
free(vec->data);
free(vec);
vec = NULL;
}
return vec;
}
/* calculate modulus of vector dest with vector src */
struct vec *
vcmodv(struct vec *src, struct vec *dest)
{
struct vec *vec = NULL;
size_t n = dest->nval;
long t = dest->type;
vcint ival1;
vcint ival2;
long l;
if (n != src->nval) {
return NULL;
}
if (src->type != t) {
return NULL;
}
vec = malloc(sizeof(struct vec));
vec->type = t;
vec->nval = n;
vec->data = malloc(n * sizeof(struct vcval));
if (t == VC_INT) {
for (l = 0 ; l < n ; l++) {
ival1 = dest->data[l].data.i;
ival2 = src->data[l].data.i;
vec->data[l].data.i = ival1 % ival2;
}
} else {
fprintf(stderr, "invalid argument type for modulus: %lx\n", t);
free(vec->data);
free(vec);
vec = NULL;
}
return vec;
}
#endif
|
nkapinos/chorus
|
spec/javascripts/views/database_column_list_view_spec.js
|
<gh_stars>1-10
describe("chorus.views.DatabaseColumnList", function() {
describe("#render", function() {
beforeEach(function() {
this.dataset = backboneFixtures.workspaceDataset.datasetTable();
this.dataset.setDatasetNumber(1);
this.collection = backboneFixtures.databaseColumnSet([
{
name: "column_name_1",
typeCategory: "BOOLEAN",
dataType: "boolean",
description: "column comment"
},
{
name: "column_name_2",
typeCategory: "WHOLE_NUMBER",
dataType: "int4",
description: "column comment"
}
]);
this.column1 = this.collection.at(0);
this.column2 = this.collection.at(1);
this.dataset.columns().reset(this.collection.models);
this.view = new chorus.views.DatabaseColumnList({collection: this.collection});
this.view.render();
});
it("defaults to selectMulti false", function() {
expect(this.view.selectMulti).toBeFalsy();
});
it("renders an item for each column", function() {
expect(this.view.$("> li").length).toBe(this.collection.length);
});
it("shows the comment for each column", function() {
expect(this.view.$("li:eq(0) .summary")).toHaveText("column comment");
});
it("shows the type for each column", function() {
expect(this.view.$("li:eq(0) .type")).toHaveClass("boolean");
expect(this.view.$("li:eq(0) .type_name").text().trim()).toBe("boolean");
expect(this.view.$("li:eq(1) .type")).toHaveClass("numeric");
expect(this.view.$("li:eq(1) .type_name").text().trim()).toBe("int4");
});
it("sorts the columns by ordinalPosition", function() {
expect(this.view.$("li:eq(0) .name")).toHaveText("column_name_1");
expect(this.view.$("li:eq(1) .name")).toHaveText("column_name_2");
});
it("subscribes to column:select_all", function() {
expect(this.view).toHaveSubscription("column:select_all", this.view.selectAll);
});
it("subscribes to column:select_none", function() {
expect(this.view).toHaveSubscription("column:select_none", this.view.selectNone);
});
it("subscribes to column:removed", function() {
expect(this.view).toHaveSubscription("column:removed", this.view.deselectColumn);
});
describe("column:deselected", function() {
beforeEach(function() {
this.view.selectMulti = true;
chorus.PageEvents.trigger("column:deselected", this.collection.at(0));
});
it("deselects the column", function() {
expect(this.view.$("li.selected").length).toBe(0);
});
});
describe("clicking on a list item", function() {
beforeEach(function() {
spyOn(chorus.PageEvents, "trigger").andCallThrough();
});
context("with selectMulti false", function() {
it("has the first row selected by default", function() {
expect(this.view.$("li:eq(0)")).toHaveClass("selected");
});
context("selecting a column", function() {
beforeEach(function() {
this.view.$("li:eq(1)").click();
});
it("moves the selected class", function() {
expect(this.view.$("li:eq(0)")).not.toHaveClass("selected");
expect(this.view.$("li:eq(1)")).toHaveClass("selected");
});
it("triggers the column:selected page event with the corresponding model as an argument", function() {
expect(chorus.PageEvents.trigger).toHaveBeenCalledWith("column:selected", this.collection.at(1));
});
it("triggers the column:deselected page event with the corresponding model as an argument", function() {
expect(chorus.PageEvents.trigger).toHaveBeenCalledWith("column:deselected", this.collection.at(0));
});
describe("#selectNone", function() {
beforeEach(function() {
this.view.selectNone();
});
it("should remove class selected from all list items and select the first item", function() {
expect(this.view.$("li.selected").length).toBe(1);
expect(this.view.$("li:eq(0)")).toHaveClass("selected");
});
});
});
});
context("with selectMulti true", function() {
beforeEach(function() {
this.view.selectMulti = true;
this.view.render();
});
it("has nothing selected by default", function() {
expect(this.view.$("li.selected")).not.toExist();
});
context("with a column selected", function() {
beforeEach(function() {
this.column2.selected = true;
this.view.render();
});
it("renders a selected column as selected", function() {
expect(this.view.$('.selected').length).toBe(1);
});
});
context("selecting multiple", function() {
beforeEach(function() {
this.view.$("li:eq(0)").click();
this.view.$("li:eq(1)").click();
});
it("selects both", function() {
expect(this.view.$("li:eq(0)")).toHaveClass("selected");
expect(this.view.$("li:eq(1)")).toHaveClass("selected");
});
it("triggers the column:selected page event with the corresponding model as an argument", function() {
expect(chorus.PageEvents.trigger).toHaveBeenCalledWith("column:selected", this.collection.at(0));
expect(chorus.PageEvents.trigger).toHaveBeenCalledWith("column:selected", this.collection.at(1));
});
describe("deselecting", function() {
beforeEach(function() {
this.view.$("li:eq(1)").click();
});
it("can deselect everything", function() {
expect(this.view.$("li:eq(0)")).toHaveClass("selected");
expect(this.view.$("li:eq(1)")).not.toHaveClass("selected");
this.view.$("li:eq(0)").click();
expect(this.view.$("li:eq(0)")).not.toHaveClass("selected");
});
it("triggers the column:deselected event with the corresponding model as an argument", function() {
expect(chorus.PageEvents.trigger).toHaveBeenCalledWith("column:deselected", this.collection.at(1));
});
});
});
});
});
describe("showDatasetName", function() {
context("when enabled", function() {
beforeEach(function() {
this.view.showDatasetName = true;
this.view.render();
});
it("shows the dataset name", function() {
expect(this.view.$("li:eq(0) .aliased_name .letter")).toContainText(this.column1.dataset.aliasedName);
});
});
context("when disabled", function() {
beforeEach(function() {
this.view.showDatasetName = false;
this.view.render();
});
it("does not show the dataset name", function() {
expect(this.view.$("li:eq(0) .aliased_name")).not.toExist();
});
});
});
});
});
|
acktsap/it-book-searcher
|
it-book-indexer/src/main/java/acktsap/books/IndexerApplication.java
|
/*
* @copyright defined in LICENSE.txt
*/
package acktsap.books;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class IndexerApplication {
public static void main(String[] args) {
SpringApplication.run(IndexerApplication.class, args);
}
}
|
donhui/kubesphere
|
vendor/openpitrix.io/openpitrix/pkg/pb/app.pb.gw.go
|
<reponame>donhui/kubesphere<filename>vendor/openpitrix.io/openpitrix/pkg/pb/app.pb.gw.go
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: app.proto
/*
Package pb is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package pb
import (
"io"
"net/http"
"github.com/golang/protobuf/proto"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/grpc-ecosystem/grpc-gateway/utilities"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/status"
)
var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
func request_AppManager_CreateApp_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq CreateAppRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.CreateApp(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_AppManager_ValidatePackage_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ValidatePackageRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.ValidatePackage(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_AppManager_GetAppStatistics_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq GetAppStatisticsRequest
var metadata runtime.ServerMetadata
msg, err := client.GetAppStatistics(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
var (
filter_AppManager_DescribeApps_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)}
)
func request_AppManager_DescribeApps_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq DescribeAppsRequest
var metadata runtime.ServerMetadata
if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_AppManager_DescribeApps_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.DescribeApps(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
var (
filter_AppManager_DescribeActiveApps_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)}
)
func request_AppManager_DescribeActiveApps_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq DescribeAppsRequest
var metadata runtime.ServerMetadata
if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_AppManager_DescribeActiveApps_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.DescribeActiveApps(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_AppManager_ModifyApp_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ModifyAppRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.ModifyApp(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_AppManager_UploadAppAttachment_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq UploadAppAttachmentRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.UploadAppAttachment(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_AppManager_DeleteApps_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq DeleteAppsRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.DeleteApps(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_AppManager_CreateAppVersion_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq CreateAppVersionRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.CreateAppVersion(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
var (
filter_AppManager_DescribeAppVersions_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)}
)
func request_AppManager_DescribeAppVersions_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq DescribeAppVersionsRequest
var metadata runtime.ServerMetadata
if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_AppManager_DescribeAppVersions_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.DescribeAppVersions(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
var (
filter_AppManager_DescribeActiveAppVersions_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)}
)
func request_AppManager_DescribeActiveAppVersions_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq DescribeAppVersionsRequest
var metadata runtime.ServerMetadata
if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_AppManager_DescribeActiveAppVersions_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.DescribeActiveAppVersions(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
var (
filter_AppManager_DescribeAppVersionAudits_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)}
)
func request_AppManager_DescribeAppVersionAudits_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq DescribeAppVersionAuditsRequest
var metadata runtime.ServerMetadata
if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_AppManager_DescribeAppVersionAudits_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.DescribeAppVersionAudits(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
var (
filter_AppManager_DescribeAppVersionReviews_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)}
)
func request_AppManager_DescribeAppVersionReviews_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq DescribeAppVersionReviewsRequest
var metadata runtime.ServerMetadata
if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_AppManager_DescribeAppVersionReviews_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.DescribeAppVersionReviews(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_AppManager_ModifyAppVersion_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ModifyAppVersionRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.ModifyAppVersion(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
var (
filter_AppManager_GetAppVersionPackage_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)}
)
func request_AppManager_GetAppVersionPackage_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq GetAppVersionPackageRequest
var metadata runtime.ServerMetadata
if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_AppManager_GetAppVersionPackage_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.GetAppVersionPackage(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
var (
filter_AppManager_GetAppVersionPackageFiles_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)}
)
func request_AppManager_GetAppVersionPackageFiles_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq GetAppVersionPackageFilesRequest
var metadata runtime.ServerMetadata
if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_AppManager_GetAppVersionPackageFiles_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.GetAppVersionPackageFiles(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_AppManager_SubmitAppVersion_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq SubmitAppVersionRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.SubmitAppVersion(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_AppManager_CancelAppVersion_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq CancelAppVersionRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.CancelAppVersion(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_AppManager_ReleaseAppVersion_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ReleaseAppVersionRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.ReleaseAppVersion(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_AppManager_DeleteAppVersion_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq DeleteAppVersionRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.DeleteAppVersion(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_AppManager_IsvReviewAppVersion_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ReviewAppVersionRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.IsvReviewAppVersion(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_AppManager_IsvPassAppVersion_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq PassAppVersionRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.IsvPassAppVersion(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_AppManager_IsvRejectAppVersion_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq RejectAppVersionRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.IsvRejectAppVersion(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_AppManager_BusinessReviewAppVersion_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ReviewAppVersionRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.BusinessReviewAppVersion(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_AppManager_BusinessPassAppVersion_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq PassAppVersionRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.BusinessPassAppVersion(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_AppManager_BusinessRejectAppVersion_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq RejectAppVersionRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.BusinessRejectAppVersion(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_AppManager_TechnicalReviewAppVersion_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ReviewAppVersionRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.TechnicalReviewAppVersion(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_AppManager_TechnicalPassAppVersion_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq PassAppVersionRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.TechnicalPassAppVersion(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_AppManager_TechnicalRejectAppVersion_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq RejectAppVersionRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.TechnicalRejectAppVersion(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_AppManager_AdminPassAppVersion_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq PassAppVersionRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.AdminPassAppVersion(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_AppManager_AdminRejectAppVersion_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq RejectAppVersionRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.AdminRejectAppVersion(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_AppManager_SuspendAppVersion_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq SuspendAppVersionRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.SuspendAppVersion(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_AppManager_RecoverAppVersion_0(ctx context.Context, marshaler runtime.Marshaler, client AppManagerClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq RecoverAppVersionRequest
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.RecoverAppVersion(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
// RegisterAppManagerHandlerFromEndpoint is same as RegisterAppManagerHandler but
// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
func RegisterAppManagerHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {
conn, err := grpc.Dial(endpoint, opts...)
if err != nil {
return err
}
defer func() {
if err != nil {
if cerr := conn.Close(); cerr != nil {
grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
}
return
}
go func() {
<-ctx.Done()
if cerr := conn.Close(); cerr != nil {
grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
}
}()
}()
return RegisterAppManagerHandler(ctx, mux, conn)
}
// RegisterAppManagerHandler registers the http handlers for service AppManager to "mux".
// The handlers forward requests to the grpc endpoint over "conn".
func RegisterAppManagerHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
return RegisterAppManagerHandlerClient(ctx, mux, NewAppManagerClient(conn))
}
// RegisterAppManagerHandlerClient registers the http handlers for service AppManager
// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "AppManagerClient".
// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "AppManagerClient"
// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in
// "AppManagerClient" to call the correct interceptors.
func RegisterAppManagerHandlerClient(ctx context.Context, mux *runtime.ServeMux, client AppManagerClient) error {
mux.Handle("POST", pattern_AppManager_CreateApp_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_CreateApp_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_CreateApp_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_AppManager_ValidatePackage_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_ValidatePackage_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_ValidatePackage_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_AppManager_GetAppStatistics_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_GetAppStatistics_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_GetAppStatistics_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_AppManager_DescribeApps_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_DescribeApps_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_DescribeApps_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_AppManager_DescribeActiveApps_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_DescribeActiveApps_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_DescribeActiveApps_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("PATCH", pattern_AppManager_ModifyApp_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_ModifyApp_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_ModifyApp_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("PATCH", pattern_AppManager_UploadAppAttachment_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_UploadAppAttachment_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_UploadAppAttachment_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("DELETE", pattern_AppManager_DeleteApps_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_DeleteApps_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_DeleteApps_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_AppManager_CreateAppVersion_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_CreateAppVersion_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_CreateAppVersion_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_AppManager_DescribeAppVersions_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_DescribeAppVersions_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_DescribeAppVersions_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_AppManager_DescribeActiveAppVersions_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_DescribeActiveAppVersions_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_DescribeActiveAppVersions_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_AppManager_DescribeAppVersionAudits_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_DescribeAppVersionAudits_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_DescribeAppVersionAudits_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_AppManager_DescribeAppVersionReviews_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_DescribeAppVersionReviews_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_DescribeAppVersionReviews_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("PATCH", pattern_AppManager_ModifyAppVersion_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_ModifyAppVersion_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_ModifyAppVersion_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_AppManager_GetAppVersionPackage_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_GetAppVersionPackage_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_GetAppVersionPackage_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_AppManager_GetAppVersionPackageFiles_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_GetAppVersionPackageFiles_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_GetAppVersionPackageFiles_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_AppManager_SubmitAppVersion_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_SubmitAppVersion_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_SubmitAppVersion_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_AppManager_CancelAppVersion_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_CancelAppVersion_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_CancelAppVersion_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_AppManager_ReleaseAppVersion_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_ReleaseAppVersion_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_ReleaseAppVersion_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_AppManager_DeleteAppVersion_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_DeleteAppVersion_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_DeleteAppVersion_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_AppManager_IsvReviewAppVersion_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_IsvReviewAppVersion_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_IsvReviewAppVersion_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_AppManager_IsvPassAppVersion_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_IsvPassAppVersion_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_IsvPassAppVersion_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_AppManager_IsvRejectAppVersion_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_IsvRejectAppVersion_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_IsvRejectAppVersion_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_AppManager_BusinessReviewAppVersion_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_BusinessReviewAppVersion_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_BusinessReviewAppVersion_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_AppManager_BusinessPassAppVersion_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_BusinessPassAppVersion_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_BusinessPassAppVersion_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_AppManager_BusinessRejectAppVersion_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_BusinessRejectAppVersion_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_BusinessRejectAppVersion_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_AppManager_TechnicalReviewAppVersion_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_TechnicalReviewAppVersion_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_TechnicalReviewAppVersion_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_AppManager_TechnicalPassAppVersion_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_TechnicalPassAppVersion_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_TechnicalPassAppVersion_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_AppManager_TechnicalRejectAppVersion_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_TechnicalRejectAppVersion_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_TechnicalRejectAppVersion_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_AppManager_AdminPassAppVersion_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_AdminPassAppVersion_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_AdminPassAppVersion_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_AppManager_AdminRejectAppVersion_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_AdminRejectAppVersion_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_AdminRejectAppVersion_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_AppManager_SuspendAppVersion_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_SuspendAppVersion_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_SuspendAppVersion_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_AppManager_RecoverAppVersion_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_AppManager_RecoverAppVersion_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_AppManager_RecoverAppVersion_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
var (
pattern_AppManager_CreateApp_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "apps"}, ""))
pattern_AppManager_ValidatePackage_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "apps", "validate_package"}, ""))
pattern_AppManager_GetAppStatistics_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "apps", "statistics"}, ""))
pattern_AppManager_DescribeApps_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "apps"}, ""))
pattern_AppManager_DescribeActiveApps_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "active_apps"}, ""))
pattern_AppManager_ModifyApp_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "apps"}, ""))
pattern_AppManager_UploadAppAttachment_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "app", "attachment"}, ""))
pattern_AppManager_DeleteApps_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "apps"}, ""))
pattern_AppManager_CreateAppVersion_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "app_versions"}, ""))
pattern_AppManager_DescribeAppVersions_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "app_versions"}, ""))
pattern_AppManager_DescribeActiveAppVersions_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "active_app_versions"}, ""))
pattern_AppManager_DescribeAppVersionAudits_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "app_version_audits"}, ""))
pattern_AppManager_DescribeAppVersionReviews_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "app_version_reviews"}, ""))
pattern_AppManager_ModifyAppVersion_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "app_versions"}, ""))
pattern_AppManager_GetAppVersionPackage_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "app_version", "package"}, ""))
pattern_AppManager_GetAppVersionPackageFiles_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"v1", "app_version", "package", "files"}, ""))
pattern_AppManager_SubmitAppVersion_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"v1", "app_version", "action", "submit"}, ""))
pattern_AppManager_CancelAppVersion_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"v1", "app_version", "action", "cancel"}, ""))
pattern_AppManager_ReleaseAppVersion_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"v1", "app_version", "action", "release"}, ""))
pattern_AppManager_DeleteAppVersion_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"v1", "app_version", "action", "delete"}, ""))
pattern_AppManager_IsvReviewAppVersion_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "app_version", "action", "review", "isv"}, ""))
pattern_AppManager_IsvPassAppVersion_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "app_version", "action", "pass", "isv"}, ""))
pattern_AppManager_IsvRejectAppVersion_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "app_version", "action", "reject", "isv"}, ""))
pattern_AppManager_BusinessReviewAppVersion_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "app_version", "action", "review", "business"}, ""))
pattern_AppManager_BusinessPassAppVersion_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "app_version", "action", "pass", "business"}, ""))
pattern_AppManager_BusinessRejectAppVersion_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "app_version", "action", "reject", "business"}, ""))
pattern_AppManager_TechnicalReviewAppVersion_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "app_version", "action", "review", "technical"}, ""))
pattern_AppManager_TechnicalPassAppVersion_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "app_version", "action", "pass", "technical"}, ""))
pattern_AppManager_TechnicalRejectAppVersion_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "app_version", "action", "reject", "technical"}, ""))
pattern_AppManager_AdminPassAppVersion_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "app_version", "action", "pass", "admin"}, ""))
pattern_AppManager_AdminRejectAppVersion_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "app_version", "action", "reject", "admin"}, ""))
pattern_AppManager_SuspendAppVersion_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"v1", "app_version", "action", "suspend"}, ""))
pattern_AppManager_RecoverAppVersion_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"v1", "app_version", "action", "recover"}, ""))
)
var (
forward_AppManager_CreateApp_0 = runtime.ForwardResponseMessage
forward_AppManager_ValidatePackage_0 = runtime.ForwardResponseMessage
forward_AppManager_GetAppStatistics_0 = runtime.ForwardResponseMessage
forward_AppManager_DescribeApps_0 = runtime.ForwardResponseMessage
forward_AppManager_DescribeActiveApps_0 = runtime.ForwardResponseMessage
forward_AppManager_ModifyApp_0 = runtime.ForwardResponseMessage
forward_AppManager_UploadAppAttachment_0 = runtime.ForwardResponseMessage
forward_AppManager_DeleteApps_0 = runtime.ForwardResponseMessage
forward_AppManager_CreateAppVersion_0 = runtime.ForwardResponseMessage
forward_AppManager_DescribeAppVersions_0 = runtime.ForwardResponseMessage
forward_AppManager_DescribeActiveAppVersions_0 = runtime.ForwardResponseMessage
forward_AppManager_DescribeAppVersionAudits_0 = runtime.ForwardResponseMessage
forward_AppManager_DescribeAppVersionReviews_0 = runtime.ForwardResponseMessage
forward_AppManager_ModifyAppVersion_0 = runtime.ForwardResponseMessage
forward_AppManager_GetAppVersionPackage_0 = runtime.ForwardResponseMessage
forward_AppManager_GetAppVersionPackageFiles_0 = runtime.ForwardResponseMessage
forward_AppManager_SubmitAppVersion_0 = runtime.ForwardResponseMessage
forward_AppManager_CancelAppVersion_0 = runtime.ForwardResponseMessage
forward_AppManager_ReleaseAppVersion_0 = runtime.ForwardResponseMessage
forward_AppManager_DeleteAppVersion_0 = runtime.ForwardResponseMessage
forward_AppManager_IsvReviewAppVersion_0 = runtime.ForwardResponseMessage
forward_AppManager_IsvPassAppVersion_0 = runtime.ForwardResponseMessage
forward_AppManager_IsvRejectAppVersion_0 = runtime.ForwardResponseMessage
forward_AppManager_BusinessReviewAppVersion_0 = runtime.ForwardResponseMessage
forward_AppManager_BusinessPassAppVersion_0 = runtime.ForwardResponseMessage
forward_AppManager_BusinessRejectAppVersion_0 = runtime.ForwardResponseMessage
forward_AppManager_TechnicalReviewAppVersion_0 = runtime.ForwardResponseMessage
forward_AppManager_TechnicalPassAppVersion_0 = runtime.ForwardResponseMessage
forward_AppManager_TechnicalRejectAppVersion_0 = runtime.ForwardResponseMessage
forward_AppManager_AdminPassAppVersion_0 = runtime.ForwardResponseMessage
forward_AppManager_AdminRejectAppVersion_0 = runtime.ForwardResponseMessage
forward_AppManager_SuspendAppVersion_0 = runtime.ForwardResponseMessage
forward_AppManager_RecoverAppVersion_0 = runtime.ForwardResponseMessage
)
|
langkcc/AndroidFramwork
|
androidframework/src/main/java/com/juefeng/android/framework/common/util/Base64Util.java
|
package com.juefeng.android.framework.common.util;
import android.util.Base64;
/**
* Created with IntelliJ IDEA.
* User: LangK
* Date: 2017/9/30
* Time: 17:43
* Description:
*/
public class Base64Util {
Base64 decoder;
public static String encode(String str){
String strBase64 = new String(Base64.encode(str.getBytes(), Base64.NO_WRAP));
return strBase64;
}
public static String decode(String str){
return new String(Base64.decode(str.getBytes(), Base64.NO_WRAP));
}
}
|
rram12/huntKingdomPlatform
|
mobile/src/Entities/PiecesDefectueuses.java
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Entities;
/**
*
* @author asus_pc
*/
public class PiecesDefectueuses {
private int id;
private boolean etat;
private boolean reserved;
private String nom;
private String categorie;
private String description;
private String image;
private int userId;
public PiecesDefectueuses() {
}
public PiecesDefectueuses( String nom, String categorie, String description, String image, int userId) {
this.nom = nom;
this.categorie = categorie;
this.description = description;
this.image = image;
this.userId = userId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isEtat() {
return etat;
}
public void setEtat(boolean etat) {
this.etat = etat;
}
public boolean isReserved() {
return reserved;
}
public void setReserved(boolean reserved) {
this.reserved = reserved;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getCategorie() {
return categorie;
}
public void setCategorie(String categorie) {
this.categorie = categorie;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
@Override
public String toString() {
return "PiecesDefectueses{" + "id=" + id + ", etat=" + etat + ", reserved=" + reserved + ", nom=" + nom + ", categorie=" + categorie + ", description=" + description + ", image=" + image + ", userId=" + userId + '}';
}
}
|
newcommerdontblame/ionlib
|
src/sdk/hl2_csgo/game/server/swarm/asw_spawner.cpp
|
#include "cbase.h"
#include "baseentity.h"
#include "asw_spawner.h"
//#include "asw_simpleai_senses.h"
#include "asw_marine.h"
#include "asw_gamerules.h"
#include "asw_marine_resource.h"
#include "asw_game_resource.h"
#include "entityapi.h"
#include "entityoutput.h"
#include "props.h"
#include "asw_alien.h"
#include "asw_buzzer.h"
#include "asw_director.h"
#include "asw_fail_advice.h"
#include "asw_spawn_manager.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
LINK_ENTITY_TO_CLASS( asw_spawner, CASW_Spawner );
//ConVar asw_uber_drone_chance("asw_uber_drone_chance", "0.25f", FCVAR_CHEAT, "Chance of an uber drone spawning when playing in uber mode");
extern ConVar asw_debug_spawners;
extern ConVar asw_drone_health;
ConVar asw_spawning_enabled( "asw_spawning_enabled", "1", FCVAR_CHEAT, "If set to 0, asw_spawners won't spawn aliens" );
BEGIN_DATADESC( CASW_Spawner )
DEFINE_KEYFIELD( m_nMaxLiveAliens, FIELD_INTEGER, "MaxLiveAliens" ),
DEFINE_KEYFIELD( m_nNumAliens, FIELD_INTEGER, "NumAliens" ),
DEFINE_KEYFIELD( m_bInfiniteAliens, FIELD_BOOLEAN, "InfiniteAliens" ),
DEFINE_KEYFIELD( m_flSpawnInterval, FIELD_FLOAT, "SpawnInterval" ),
DEFINE_KEYFIELD( m_flSpawnIntervalJitter, FIELD_FLOAT, "SpawnIntervalJitter" ),
DEFINE_KEYFIELD( m_AlienClassNum, FIELD_INTEGER, "AlienClass" ),
DEFINE_KEYFIELD( m_SpawnerState, FIELD_INTEGER, "SpawnerState" ),
DEFINE_INPUTFUNC( FIELD_VOID, "SpawnOneAlien", InputSpawnAlien ),
DEFINE_INPUTFUNC( FIELD_VOID, "StartSpawning", InputStartSpawning ),
DEFINE_INPUTFUNC( FIELD_VOID, "StopSpawning", InputStopSpawning ),
DEFINE_INPUTFUNC( FIELD_VOID, "ToggleSpawning", InputToggleSpawning ),
DEFINE_OUTPUT( m_OnAllSpawned, "OnAllSpawned" ),
DEFINE_OUTPUT( m_OnAllSpawnedDead, "OnAllSpawnedDead" ),
DEFINE_FIELD( m_nCurrentLiveAliens, FIELD_INTEGER ),
DEFINE_FIELD( m_AlienClassName, FIELD_STRING ),
DEFINE_THINKFUNC( SpawnerThink ),
END_DATADESC()
CASW_Spawner::CASW_Spawner()
{
m_hAlienOrderTarget = NULL;
}
CASW_Spawner::~CASW_Spawner()
{
}
void CASW_Spawner::InitAlienClassName()
{
if ( m_AlienClassNum < 0 || m_AlienClassNum >= ASWSpawnManager()->GetNumAlienClasses() )
{
m_AlienClassNum = 0;
}
m_AlienClassName = ASWSpawnManager()->GetAlienClass( m_AlienClassNum )->m_iszAlienClass;
}
void CASW_Spawner::Spawn()
{
InitAlienClassName();
BaseClass::Spawn();
m_flSpawnIntervalJitter /= 100.0f;
m_flSpawnIntervalJitter = clamp<float>(m_flSpawnIntervalJitter, 0, 100);
SetSolid( SOLID_NONE );
m_nCurrentLiveAliens = 0;
// trigger any begin state stuff
SetSpawnerState(m_SpawnerState);
}
void CASW_Spawner::Precache()
{
BaseClass::Precache();
InitAlienClassName();
const char *pszNPCName = STRING( m_AlienClassName );
if ( !pszNPCName || !pszNPCName[0] )
{
Warning("asw_spawner %s has no specified alien-to-spawn classname.\n", STRING(GetEntityName()) );
}
else
{
UTIL_PrecacheOther( pszNPCName );
}
}
IASW_Spawnable_NPC* CASW_Spawner::SpawnAlien( const char *szAlienClassName, const Vector &vecHullMins, const Vector &vecHullMaxs )
{
IASW_Spawnable_NPC *pSpawnable = BaseClass::SpawnAlien( szAlienClassName, vecHullMins, vecHullMaxs );
if ( pSpawnable )
{
m_nCurrentLiveAliens++;
if (!m_bInfiniteAliens)
{
m_nNumAliens--;
if (m_nNumAliens <= 0)
{
SpawnedAllAliens();
}
}
else
{
ASWFailAdvice()->OnAlienSpawnedInfinite();
}
}
return pSpawnable;
}
bool CASW_Spawner::CanSpawn( const Vector &vecHullMins, const Vector &vecHullMaxs )
{
if ( !asw_spawning_enabled.GetBool() )
return false;
// too many alive already?
if (m_nMaxLiveAliens>0 && m_nCurrentLiveAliens>=m_nMaxLiveAliens)
return false;
// have we run out?
if (!m_bInfiniteAliens && m_nNumAliens<=0)
return false;
return BaseClass::CanSpawn( vecHullMins, vecHullMaxs );
}
// called when we've spawned all the aliens we can,
// spawner should go to sleep
void CASW_Spawner::SpawnedAllAliens()
{
m_OnAllSpawned.FireOutput( this, this );
SetSpawnerState(SST_Finished); // disables think functions and so on
}
void CASW_Spawner::AlienKilled( CBaseEntity *pVictim )
{
BaseClass::AlienKilled( pVictim );
m_nCurrentLiveAliens--;
if (asw_debug_spawners.GetBool())
Msg("%d AlienKilled NumLive = %d\n", entindex(), m_nCurrentLiveAliens );
// If we're here, we're getting erroneous death messages from children we haven't created
AssertMsg( m_nCurrentLiveAliens >= 0, "asw_spawner receiving child death notice but thinks has no children\n" );
if ( m_nCurrentLiveAliens <= 0 )
{
// See if we've exhausted our supply of NPCs
if (!m_bInfiniteAliens && m_nNumAliens <= 0 )
{
if (asw_debug_spawners.GetBool())
Msg("%d OnAllSpawnedDead (%s)\n", entindex(), STRING(GetEntityName()));
// Signal that all our children have been spawned and are now dead
m_OnAllSpawnedDead.FireOutput( this, this );
}
}
}
// mission started
void CASW_Spawner::MissionStart()
{
if (asw_debug_spawners.GetBool())
Msg("Spawner mission start, always inf=%d infinitealiens=%d\n", HasSpawnFlags( ASW_SF_ALWAYS_INFINITE ), m_bInfiniteAliens );
// remove infinite spawns on easy mode
if ( !HasSpawnFlags( ASW_SF_ALWAYS_INFINITE ) && ASWGameRules() && ASWGameRules()->GetSkillLevel() == 1
&& m_bInfiniteAliens)
{
m_bInfiniteAliens = false;
if (m_nNumAliens < 8)
m_nNumAliens = 8;
if (asw_debug_spawners.GetBool())
Msg(" removed infinite and set num aliens to %d\n", m_nNumAliens);
}
if (m_SpawnerState == SST_StartSpawningWhenMissionStart)
SetSpawnerState(SST_Spawning);
}
void CASW_Spawner::SetSpawnerState(SpawnerState_t newState)
{
m_SpawnerState = newState;
// begin state stuff
if (m_SpawnerState == SST_Spawning)
{
SetThink ( &CASW_Spawner::SpawnerThink );
SetNextThink( gpGlobals->curtime );
}
else if (m_SpawnerState == SST_Finished)
{
// Disable this forever. Don't kill it because it still gets death notices
SetThink( NULL );
SetUse( NULL );
}
else if (m_SpawnerState == SST_WaitForInputs)
{
SetThink( NULL ); // stop thinking
}
}
void CASW_Spawner::SpawnerThink()
{
// calculate jitter
float fInterval = random->RandomFloat(1.0f - m_flSpawnIntervalJitter, 1.0f + m_flSpawnIntervalJitter) * m_flSpawnInterval;
SetNextThink( gpGlobals->curtime + fInterval );
if ( ASWDirector() && ASWDirector()->CanSpawnAlien( this ) )
{
SpawnAlien( STRING( m_AlienClassName ), GetAlienMins(), GetAlienMaxs() );
}
}
// =====================
// Inputs
// =====================
void CASW_Spawner::SpawnOneAlien()
{
SpawnAlien( STRING( m_AlienClassName ), GetAlienMins(), GetAlienMaxs() );
}
void CASW_Spawner::InputSpawnAlien( inputdata_t &inputdata )
{
if (m_SpawnerState == SST_WaitForInputs)
{
if ( ASWDirector() && ASWDirector()->CanSpawnAlien( this ) )
{
SpawnOneAlien();
}
}
}
void CASW_Spawner::InputStartSpawning( inputdata_t &inputdata )
{
if (m_SpawnerState == SST_WaitForInputs)
SetSpawnerState(SST_Spawning);
}
void CASW_Spawner::InputStopSpawning( inputdata_t &inputdata )
{
if (m_SpawnerState == SST_Spawning)
SetSpawnerState(SST_WaitForInputs);
}
void CASW_Spawner::InputToggleSpawning( inputdata_t &inputdata )
{
if (m_SpawnerState == SST_Spawning)
SetSpawnerState(SST_WaitForInputs);
else if (m_SpawnerState == SST_WaitForInputs)
SetSpawnerState(SST_Spawning);
}
const Vector& CASW_Spawner::GetAlienMins()
{
return NAI_Hull::Mins( ASWSpawnManager()->GetAlienClass( m_AlienClassNum )->m_nHullType );
}
const Vector& CASW_Spawner::GetAlienMaxs()
{
return NAI_Hull::Maxs( ASWSpawnManager()->GetAlienClass( m_AlienClassNum )->m_nHullType );
}
bool CASW_Spawner::ApplyCarnageMode( float fScaler, float fInvScaler )
{
if ( m_AlienClassNum == g_nDroneClassEntry || m_AlienClassNum == g_nDroneJumperClassEntry )
{
Msg( "[%d] Found a spawner set to spawn drones or drone jumpers\n", entindex());
Msg( " previous numaliens is %d max live is %d interval %f\n", m_nNumAliens, m_nMaxLiveAliens, m_flSpawnInterval );
m_nNumAliens *= fScaler;
m_nMaxLiveAliens *= fScaler;
m_flSpawnInterval *= fInvScaler;
Msg( " Set its numaliens to %d max live to %d interval %f\n", m_nNumAliens, m_nMaxLiveAliens, m_flSpawnInterval );
return true;
}
Msg( "[%d] Found a spawner but it's not set to spawn drones or drone jumpers\n", entindex() );
return false;
}
int CASW_Spawner::DrawDebugTextOverlays()
{
int text_offset = BaseClass::DrawDebugTextOverlays();
if (m_debugOverlays & OVERLAY_TEXT_BIT)
{
NDebugOverlay::EntityText( entindex(),text_offset,CFmtStr( "Num Live Aliens: %d", m_nCurrentLiveAliens ),0 );
text_offset++;
NDebugOverlay::EntityText( entindex(),text_offset,CFmtStr( "Max Live Aliens: %d", m_nMaxLiveAliens ),0 );
text_offset++;
NDebugOverlay::EntityText( entindex(),text_offset,CFmtStr( "Alien supply: %d", m_bInfiniteAliens ? -1 : m_nNumAliens ),0 );
text_offset++;
}
return text_offset;
}
void ASW_ApplyCarnage_f(float fScaler)
{
if ( fScaler <= 0 )
fScaler = 1.0f;
float fInvScaler = 1.0f / fScaler;
int iNewHealth = fInvScaler * 80.0f; // note: boosted health a bit here so this mode is harder than normal
asw_drone_health.SetValue(iNewHealth);
CBaseEntity* pEntity = NULL;
int iSpawnersChanged = 0;
while ((pEntity = gEntList.FindEntityByClassname( pEntity, "asw_spawner" )) != NULL)
{
CASW_Spawner* pSpawner = dynamic_cast<CASW_Spawner*>(pEntity);
if (pSpawner)
{
if ( pSpawner->ApplyCarnageMode( fScaler, fInvScaler ) )
{
iSpawnersChanged++;
}
}
}
}
void asw_carnage_f(const CCommand &args)
{
if ( args.ArgC() < 2 )
{
Msg( "Please supply a scale\n" );
}
ASW_ApplyCarnage_f( atof( args[1] ) );
}
ConCommand asw_carnage( "asw_carnage", asw_carnage_f, "Scales the number of aliens each spawner will put out", FCVAR_CHEAT );
|
zurl/CauchyDB
|
Services/FileService.h
|
<reponame>zurl/CauchyDB
//
// Created by 张程易 on 2017/3/20.
//
#ifndef DB_FILESERVICE_H
#define DB_FILESERVICE_H
#include "../Common.h"
class FileService{
std::vector<FILE *> files;
std::vector<int> fileBlockCnt;
public:
FileService();
FileService(const FileService & ) = delete;
FileService operator=(const FileService &) = delete;
void createFile(const char * fileName);
int openFile(const char * fileName);
FILE * getFile(int fileID);
int allocBlock(int fileID);
void writeBlock(int fileID, int startOffset, void * data);
int getBlockCnt(int fileID);
void * readBlock(int fileID, int startOffset);
~FileService();
};
#endif //DB_FILESERVICE_H
|
luoyezhe/graphin4vue
|
src/components/graphin/apis/element.js
|
/**
* 高亮节点
* @param graph
*/
export const highlightNodeById = (graph) => (nodeIds) => {
graph.getNodes().forEach(node => {
graph.clearItemStates(node, ['active', 'inactive'])
if (nodeIds.indexOf(node.get('id')) !== -1) {
graph.setItemState(node, 'active', true)
} else {
graph.setItemState(node, 'active', false)
}
})
}
/**
* Focus 节点
* @param graph
*/
export const focusNodeById = (graph) => (nodeId) => {
if (!graph || typeof nodeId !== 'string') {
return
}
const node = graph.findById(nodeId)
if (!node) {
console.warn(`The node ${nodeId} does not exist!`)
return
}
graph.focusItem(nodeId, true, {
duration: 300,
easing: 'easeCubic'
})
graph.setItemState(node, 'selected', true)
node.toFront()
}
|
zoido/yag-conf
|
variable.go
|
package yag
import "strings"
type variable struct {
flag *wrapper
name string
envName string
help string
required bool
parseFlag bool
parseEnv bool
}
func (v *variable) usage() string {
u := make([]string, 1, 10)
u[0] = "\t"
if v.parseFlag {
u = append(u, "-", v.name)
}
if v.parseEnv && v.parseFlag {
u = append(u, " ($", v.envName, ")")
}
if v.parseEnv && !v.parseFlag {
u = append(u, "$", v.envName)
}
if v.required {
u = append(u, " [required]")
}
u = append(u, "\n\t\t", v.help)
return strings.Join(u, "")
}
|
ysn3506/git_bbc
|
src/integration/pages/mostWatchedPage/crossPlatformTests.js
|
<filename>src/integration/pages/mostWatchedPage/crossPlatformTests.js<gh_stars>100-1000
import { runCommonCrossPlatformTests, runMainHeadingTests } from '../../common';
export default service => {
runCommonCrossPlatformTests(service);
runMainHeadingTests();
it('I can see the list items', () => {
const listItemElements = document.querySelectorAll('main ol li');
listItemElements.forEach(itemEl => {
expect(itemEl).toBeInTheDocument();
expect(itemEl.textContent).toBeTruthy();
expect(itemEl.textContent).toMatchSnapshot();
});
});
};
|
DDeAlmeida/near-wallet
|
packages/frontend/src/components/accounts/create/existing_account/ExistingAccountWrapper.js
|
<gh_stars>0
import { getLocation } from 'connected-react-router';
import { parse } from 'query-string';
import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { LINKDROP_GAS, MIN_BALANCE_TO_CREATE } from '../../../../config';
import { Mixpanel } from '../../../../mixpanel';
import {
switchAccount,
getAccountBalance,
redirectTo
} from '../../../../redux/actions/account';
import { showCustomAlert } from '../../../../redux/actions/status';
import { selectAccountAccountsBalances, selectAccountLocalStorageAccountId, selectBalance } from '../../../../redux/slices/account';
import { createNewAccountWithCurrentActiveAccount } from '../../../../redux/slices/account/createAccountThunks';
import { selectAvailableAccounts } from '../../../../redux/slices/availableAccounts';
import {
actions as ledgerActions
} from '../../../../redux/slices/ledger';
import FundNewAccount from './FundNewAccount';
import SelectAccount from './SelectAccount';
const {
checkAndHideLedgerModal
} = ledgerActions;
export function ExistingAccountWrapper({ history }) {
const dispatch = useDispatch();
const [fundingAccountId, setFundingAccountId] = useState('');
const [creatingNewAccount, setCreatingNewAccount] = useState(false);
const signedInAccountId = useSelector(selectAccountLocalStorageAccountId);
const availableAccounts = useSelector(selectAvailableAccounts);
const accountsBalances = useSelector(selectAccountAccountsBalances);
const signedInAccountBalance = useSelector(selectBalance);
const location = useSelector(getLocation);
const URLParams = parse(location.search);
const accountId = URLParams.accountId;
const implicitAccountId = URLParams.implicitAccountId;
const recoveryMethod = URLParams.recoveryMethod;
const hasAllRequiredParams = !!accountId && !!implicitAccountId && !!recoveryMethod;
if (fundingAccountId) {
return (
<FundNewAccount
onClickApprove={async () => {
await Mixpanel.withTracking("CA Create account from existing account",
async () => {
setCreatingNewAccount(true);
await dispatch(createNewAccountWithCurrentActiveAccount({
newAccountId: accountId,
implicitAccountId,
newInitialBalance: MIN_BALANCE_TO_CREATE,
recoveryMethod
})).unwrap();
},
(e) => {
dispatch(showCustomAlert({
success: false,
messageCodeHeader: 'error',
messageCode: 'walletErrorCodes.createNewAccount.error',
errorMessage: e.message
}));
setCreatingNewAccount(false);
throw e;
},
() => {
dispatch(checkAndHideLedgerModal());
}
);
dispatch(redirectTo('/'));
}}
onClickCancel={() => setFundingAccountId('')}
transferAmount={MIN_BALANCE_TO_CREATE}
gasFeeAmount={LINKDROP_GAS}
sender={signedInAccountId}
receiver={accountId}
creatingNewAccount={creatingNewAccount}
hasAllRequiredParams={hasAllRequiredParams}
/>
);
}
return (
<SelectAccount
signedInAccountId={signedInAccountId}
signedInAccountAvailableBalance={signedInAccountBalance?.balanceAvailable}
availableAccounts={availableAccounts}
accountsBalances={accountsBalances}
getAccountBalance={(accountId) => dispatch(getAccountBalance(accountId))}
onSelectAccount={(accountId) => dispatch(switchAccount({ accountId }))}
onSignInToDifferentAccount={() =>
dispatch(redirectTo(`/recover-account?fundWithExistingAccount=${encodeURIComponent(JSON.stringify({ accountId, implicitAccountId, recoveryMethod }))}`))
}
onClickNext={() => {
setFundingAccountId(signedInAccountId);
window.scrollTo(0, 0);
}}
onClickCancel={() => history.goBack()}
hasAllRequiredParams={hasAllRequiredParams}
/>
);
}
|
cmscaltech/sandie-ndn
|
NDNc/mgmt/json_helper.hpp
|
<reponame>cmscaltech/sandie-ndn<filename>NDNc/mgmt/json_helper.hpp<gh_stars>1-10
/*
* N-DISE: NDN for Data Intensive Science Experiments
* Author: <NAME> <<EMAIL>>
*
* MIT License
*
* Copyright (c) 2021 California Institute of Technology
*
* 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.
*/
#ifndef NDNC_MGMT_JSON_HELPER_HPP
#define NDNC_MGMT_JSON_HELPER_HPP
#include <nlohmann/json.hpp>
#include <set>
namespace ndnc {
namespace mgmt {
/**
* @brief GraphQL documents for NDN-DPDK forwarder configuration
*
*/
namespace json_helper {
/**
* @brief GraphQL server operation
*
*/
struct operation {
// GraphQL document
std::string query;
// Operation Name
std::string operationName;
// Query variables
nlohmann::json variables;
};
void to_json(nlohmann::json &json, const operation &req) {
json = nlohmann::json{{"query", req.query},
{"operationName", req.operationName},
{"variables", req.variables}};
}
void from_json(const nlohmann::json &json, operation &req) {
json.at("query").get_to(req.query);
json.at("operationName").get_to(req.operationName);
json.at("variables").get_to(req.variables);
}
nlohmann::json getOperation(std::string query, std::string name,
nlohmann::json variables) {
return operation{query, name, variables};
}
/**
* @brief Query variables: createFace mutation
*
*/
struct createFace {
std::string socketName; // Socket name
std::string scheme = "memif";
int id; // Face ID
int dataroom; // Dataroom size
int rxQueueSize = 1024;
int txQueueSize = 1024;
int ringCapacity = 4096;
};
void to_json(nlohmann::json &json, const createFace &loc) {
json = nlohmann::json{
{"dataroom", loc.dataroom}, {"id", loc.id},
{"socketName", loc.socketName}, {"scheme", loc.scheme},
{"rxQueueSize", loc.rxQueueSize}, {"txQueueSize", loc.txQueueSize},
{"ringCapacity", loc.ringCapacity}};
}
void from_json(const nlohmann::json &json, createFace &loc) {
json.at("dataroom").get_to(loc.dataroom);
json.at("id").get_to(loc.id);
json.at("socketName").get_to(loc.socketName);
json.at("scheme").get_to(loc.scheme);
json.at("rxQueueSize").get_to(loc.rxQueueSize);
json.at("txQueueSize").get_to(loc.txQueueSize);
json.at("ringCapacity").get_to(loc.ringCapacity);
}
/**
* @brief Query variable: delete mutation
*
*/
struct deleteFace {
std::string id; // Face ID on the forwarder side
};
void to_json(nlohmann::json &json, const deleteFace &vars) {
json = nlohmann::json{{"id", vars.id}};
}
void from_json(const nlohmann::json &json, deleteFace &vars) {
json.at("id").get_to(vars.id);
}
/**
* @brief Query variables: insertFibEntry mutation
*
*/
struct insertFibEntry {
std::string name; // Name prefix
std::set<std::string> nextHops; // Next hops: Face ID of this app
// int strategy;
};
void to_json(nlohmann::json &json, const insertFibEntry &vars) {
json = nlohmann::json{{"name", vars.name}, {"nexthops", vars.nextHops}};
}
void from_json(const nlohmann::json &json, insertFibEntry &vars) {
json.at("name").get_to(vars.name);
json.at("nexthops").get_to(vars.nextHops);
}
}; // namespace json_helper
}; // namespace mgmt
}; // namespace ndnc
#endif // NDNC_MGMT_JSON_HELPER_HPP
|
b97tsk/rx
|
operators/isEmpty.go
|
package operators
import (
"context"
"github.com/b97tsk/rx"
)
// IsEmpty emits true if the source emits no items, otherwise it emits false.
func IsEmpty() rx.Operator {
return isEmpty
}
func isEmpty(source rx.Observable) rx.Observable {
return func(ctx context.Context, sink rx.Observer) {
ctx, cancel := context.WithCancel(ctx)
sink = sink.WithCancel(cancel)
var observer rx.Observer
observer = func(t rx.Notification) {
switch {
case t.HasValue:
observer = rx.Noop
sink.Next(false)
sink.Complete()
case t.HasError:
sink(t)
default:
sink.Next(true)
sink.Complete()
}
}
source.Subscribe(ctx, observer.Sink)
}
}
|
jjwilke/sst-macro
|
sstmac/replacements/sched.h
|
<gh_stars>0
#if defined(SSTMAC_INSIDE_STL) || defined(SSTMAC_NO_REPLACEMENTS)
#include_next <sched.h>
#else
#include <sstmac/libraries/pthread/sstmac_sched.h>
#endif
|
matt-ullmer/Diamond
|
src/collectors/ping/test/testping.py
|
#!/usr/bin/python
# coding=utf-8
################################################################################
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from mock import Mock
from mock import patch
from diamond.collector import Collector
from ping import PingCollector
################################################################################
class TestPingCollector(CollectorTestCase):
def setUp(self):
config = get_collector_config('PingCollector', {
'interval': 10,
'target_a': 'localhost',
'bin': 'true'
})
self.collector = PingCollector(config, None)
def test_import(self):
self.assertTrue(PingCollector)
@patch('os.access', Mock(return_value=True))
@patch.object(Collector, 'publish')
def test_should_work_with_real_data_bad_gentoo(self, publish_mock):
patch_communicate = patch(
'subprocess.Popen.communicate',
Mock(return_value=(
self.getFixture('bad_gentoo').getvalue(),
'')))
patch_communicate.start()
self.collector.collect()
patch_communicate.stop()
self.assertPublishedMany(publish_mock, {
'localhost': 10000
})
@patch('os.access', Mock(return_value=True))
@patch.object(Collector, 'publish')
def test_should_work_with_real_data_host_gentoo(self, publish_mock):
patch_communicate = patch(
'subprocess.Popen.communicate',
Mock(return_value=(
self.getFixture('host_gentoo').getvalue(),
'')))
patch_communicate.start()
self.collector.collect()
patch_communicate.stop()
metrics = {
'localhost': 11
}
self.setDocExample(collector=self.collector.__class__.__name__,
metrics=metrics,
defaultpath=self.collector.config['path'])
self.assertPublishedMany(publish_mock, metrics)
@patch('os.access', Mock(return_value=True))
@patch.object(Collector, 'publish')
def test_should_work_with_real_data_ip_gentoo(self, publish_mock):
patch_communicate = patch(
'subprocess.Popen.communicate',
Mock(return_value=(
self.getFixture('ip_gentoo').getvalue(),
'')))
patch_communicate.start()
self.collector.collect()
patch_communicate.stop()
self.assertPublishedMany(publish_mock, {
'localhost': 0
})
@patch('os.access', Mock(return_value=True))
@patch.object(Collector, 'publish')
def test_should_work_with_real_data_longhost_gentoo(self, publish_mock):
patch_communicate = patch(
'subprocess.Popen.communicate',
Mock(return_value=(
self.getFixture(
'longhost_gentoo').getvalue(),
'')))
patch_communicate.start()
self.collector.collect()
patch_communicate.stop()
self.assertPublishedMany(publish_mock, {
'localhost': 10
})
@patch('os.access', Mock(return_value=True))
@patch.object(Collector, 'publish')
def test_should_work_with_real_data_timeout_gentoo(self, publish_mock):
patch_communicate = patch(
'subprocess.Popen.communicate',
Mock(return_value=(
self.getFixture(
'timeout_gentoo').getvalue(),
'')))
patch_communicate.start()
self.collector.collect()
patch_communicate.stop()
self.assertPublishedMany(publish_mock, {
'localhost': 10000
})
@patch('os.access', Mock(return_value=True))
@patch.object(Collector, 'publish')
def test_should_work_with_real_data_host_osx(self, publish_mock):
patch_communicate = patch(
'subprocess.Popen.communicate',
Mock(return_value=(
self.getFixture('host_osx').getvalue(),
'')))
patch_communicate.start()
self.collector.collect()
patch_communicate.stop()
self.assertPublishedMany(publish_mock, {
'localhost': 38
})
@patch('os.access', Mock(return_value=True))
@patch.object(Collector, 'publish')
def test_should_work_with_real_data_ip_osx(self, publish_mock):
patch_communicate = patch(
'subprocess.Popen.communicate',
Mock(return_value=(
self.getFixture('ip_osx').getvalue(),
'')))
patch_communicate.start()
self.collector.collect()
patch_communicate.stop()
self.assertPublishedMany(publish_mock, {
'localhost': 0
})
@patch('os.access', Mock(return_value=True))
@patch.object(Collector, 'publish')
def test_should_work_with_real_data_longhost_osx(self, publish_mock):
patch_communicate = patch(
'subprocess.Popen.communicate',
Mock(return_value=(
self.getFixture('longhost_osx').getvalue(),
'')))
patch_communicate.start()
self.collector.collect()
patch_communicate.stop()
self.assertPublishedMany(publish_mock, {
'localhost': 42
})
@patch('os.access', Mock(return_value=True))
@patch.object(Collector, 'publish')
def test_should_work_with_real_data_timeout_osx(self, publish_mock):
patch_communicate = patch(
'subprocess.Popen.communicate',
Mock(return_value=(
self.getFixture('timeout_osx').getvalue(),
'')))
patch_communicate.start()
self.collector.collect()
patch_communicate.stop()
self.assertPublishedMany(publish_mock, {
'localhost': 10000
})
################################################################################
if __name__ == "__main__":
unittest.main()
|
keob/leetcode-go
|
leetcode/solution123/solution.go
|
<filename>leetcode/solution123/solution.go
package solution123
func maxProfit(prices []int) int {
buy1, sell1 := -prices[0], 0
buy2, sell2 := -prices[0], 0
n := len(prices)
for i := 1; i < n; i++ {
buy1 = max(buy1, -prices[i])
sell1 = max(sell1, buy1+prices[i])
buy2 = max(buy2, sell1-prices[i])
sell2 = max(sell2, buy2+prices[i])
}
return sell2
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}
|
Raffson/Sub-C-compiler
|
subcPrograms/Pmachine/ldo.h
|
// ldo.h
#ifndef LDO_H
#define LDO_H
#include <vector>
#include <typeinfo>
using namespace std;
#include "stackmachine.h"
#include "executionerror.h"
#include "stackelement.h"
#include "instruction.h"
/**
* @doc Implements the ldo-instruction. Load from absolute address.
* @author <NAME>
*/
class Ldo : public Instruction
{
public:
Ldo(StackElementType type, int q);
~Ldo();
void execute(StackMachine *stack);
ostream& print(ostream &os) const;
private:
StackElementType fType;
int fQ;
};
#endif
|
flix-/environment-variable-tracing
|
Test/200-map-to-callee-variable-5/main.c
|
<gh_stars>0
extern char *getenv(const char *name);
struct s1 {
int a;
char *tainted;
char *b;
};
void
foo(char *tainted_foo)
{
char *also_tainted_foo = tainted_foo;
}
int
main()
{
struct s1 s;
s.tainted = getenv("gude");
foo(s.tainted);
return 0;
}
|
jmoraleda/flowable-engine
|
modules/flowable-cmmn-engine/src/main/java/org/flowable/cmmn/engine/interceptor/StartCaseInstanceBeforeContext.java
|
/* 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 org.flowable.cmmn.engine.interceptor;
import java.util.Map;
import org.flowable.cmmn.api.repository.CaseDefinition;
import org.flowable.cmmn.model.Case;
import org.flowable.cmmn.model.CmmnModel;
public class StartCaseInstanceBeforeContext extends AbstractStartCaseInstanceBeforeContext {
protected String callbackId;
protected String callbackType;
protected String parentId;
protected Map<String, Object> transientVariables;
protected String tenantId;
protected String initiatorVariableName;
protected String overrideDefinitionTenantId;
protected String predefinedCaseInstanceId;
public StartCaseInstanceBeforeContext() {
}
public StartCaseInstanceBeforeContext(String businessKey, String caseInstanceName, String callbackId, String callbackType,
String parentId, Map<String, Object> variables, Map<String, Object> transientVariables, String tenantId,
String initiatorVariableName, Case caseModel, CaseDefinition caseDefinition, CmmnModel cmmnModel,
String overrideDefinitionTenantId, String predefinedCaseInstanceId) {
super(businessKey, caseInstanceName, variables, caseModel, caseDefinition, cmmnModel);
this.callbackId = callbackId;
this.callbackType = callbackType;
this.parentId = parentId;
this.transientVariables = transientVariables;
this.tenantId = tenantId;
this.initiatorVariableName = initiatorVariableName;
this.overrideDefinitionTenantId = overrideDefinitionTenantId;
this.predefinedCaseInstanceId = predefinedCaseInstanceId;
}
public String getCallbackId() {
return callbackId;
}
public void setCallbackId(String callbackId) {
this.callbackId = callbackId;
}
public String getCallbackType() {
return callbackType;
}
public void setCallbackType(String callbackType) {
this.callbackType = callbackType;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public Map<String, Object> getTransientVariables() {
return transientVariables;
}
public void setTransientVariables(Map<String, Object> transientVariables) {
this.transientVariables = transientVariables;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getInitiatorVariableName() {
return initiatorVariableName;
}
public void setInitiatorVariableName(String initiatorVariableName) {
this.initiatorVariableName = initiatorVariableName;
}
public String getOverrideDefinitionTenantId() {
return overrideDefinitionTenantId;
}
public void setOverrideDefinitionTenantId(String overrideDefinitionTenantId) {
this.overrideDefinitionTenantId = overrideDefinitionTenantId;
}
public String getPredefinedCaseInstanceId() {
return predefinedCaseInstanceId;
}
public void setPredefinedCaseInstanceId(String predefinedCaseInstanceId) {
this.predefinedCaseInstanceId = predefinedCaseInstanceId;
}
}
|
ricardyn/ironpython-stubs
|
stubs.min/System/Windows/Controls/__init___parts/MediaState.py
|
class MediaState(Enum,IComparable,IFormattable,IConvertible):
"""
Specifies the states that can be applied to a System.Windows.Controls.MediaElement for the System.Windows.Controls.MediaElement.LoadedBehavior and System.Windows.Controls.MediaElement.UnloadedBehavior properties.
enum MediaState,values: Close (2),Manual (0),Pause (3),Play (1),Stop (4)
"""
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self,*args):
""" __format__(formattable: IFormattable,format: str) -> str """
pass
def __ge__(self,*args):
pass
def __gt__(self,*args):
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __le__(self,*args):
pass
def __lt__(self,*args):
pass
def __ne__(self,*args):
pass
def __reduce_ex__(self,*args):
pass
def __str__(self,*args):
pass
Close=None
Manual=None
Pause=None
Play=None
Stop=None
value__=None
|
Actinium-project/ACM-LN-Desktop
|
app/components/Channels/ChannelCloseDialog.js
|
import React from 'react'
import PropTypes from 'prop-types'
import { Flex, Box } from 'rebass'
import { FormattedMessage, injectIntl, intlShape } from 'react-intl'
import { withFieldState } from 'informed'
import Delete from 'components/Icon/Delete'
import { Dialog, Text, Heading, Button, Checkbox, Form, DialogOverlay } from 'components/UI'
import { useCloseOnUnmount } from 'hooks'
import messages from './messages'
const DialogWrapper = ({ intl, isForceClose, isOpen, onClose, onCancel, csvDelay }) => {
useCloseOnUnmount(isOpen, onCancel)
if (!isOpen) {
return null
}
const checkboxFieldName = 'actionACK'
// bind button disabled state to a form field
const CloseChannelButton = withFieldState(checkboxFieldName)(({ fieldState, ...rest }) => (
<Button isDisabled={isForceClose && !fieldState.value} {...rest} />
))
const buttons = (
<>
<CloseChannelButton type="submit" variant="danger">
<FormattedMessage
{...(isForceClose
? messages.close_channel_dialog_force_close_text
: messages.close_channel_dialog_close_text)}
/>
</CloseChannelButton>
<Button onClick={onCancel} type="button" variant="secondary">
<FormattedMessage {...messages.close_channel_dialog_cancel_text} />
</Button>
</>
)
const header = (
<Flex alignItems="center" flexDirection="column" mb={4}>
<Box color="superRed" mb={2}>
<Delete height={72} width={72} />
</Box>
<Heading.h1>
<FormattedMessage {...messages.close_channel_dialog_header} />
</Heading.h1>
</Flex>
)
const handleSubmit = () => onClose(intl.formatMessage({ ...messages.close_channel_notification }))
return (
<DialogOverlay alignItems="center" justifyContent="center">
<Form onSubmit={handleSubmit}>
<Dialog buttons={buttons} header={header} onClose={onCancel} width={640}>
<Flex alignItems="center" flexDirection="column">
<Text color="gray" mb={2} textAlign={isForceClose ? 'left' : 'center'} width={500}>
<FormattedMessage
{...(isForceClose
? messages.close_channel_dialog_force_warning
: messages.close_channel_dialog_warning)}
values={{ csvDelay: csvDelay }}
/>
</Text>
{isForceClose && (
<Checkbox
field={checkboxFieldName}
label={intl.formatMessage({ ...messages.close_channel_dialog_acknowledgement })}
mt={4}
/>
)}
</Flex>
</Dialog>
</Form>
</DialogOverlay>
)
}
DialogWrapper.propTypes = {
csvDelay: PropTypes.number.isRequired,
intl: intlShape.isRequired,
isForceClose: PropTypes.bool.isRequired,
isOpen: PropTypes.bool.isRequired,
onCancel: PropTypes.func.isRequired,
onClose: PropTypes.func.isRequired,
}
export default injectIntl(DialogWrapper)
|
1and1/camunda-bpm-platform
|
webapps/camunda-webapp/webapp/src/main/webapp/app/admin/filters/main.js
|
<gh_stars>1-10
ngDefine('admin.filters', [
], function(module) {
});
|
fabriciofmsilva/javascript-libs
|
src/references/html-text/element-text-content.js
|
var elem = document.querySelector('#some-elem');
// Get text content
var text = elem.textContent;
// Set text content
elem.textContent = 'We can dynamically change the content.';
// Add text to the end of an element's existing content
elem.textContent += ' Add this after what is already there.';
// Add text to the beginning of an element's existing content
elem.textContent = 'We can add this to the beginning. ' + elem.textContent;
|
aeon-engine/libaeon
|
src/mono/public/aeon/mono/mono_class.h
|
// Distributed under the BSD 2-Clause License - Copyright 2012-2021 <NAME>
#pragma once
#if (AEON_PLATFORM_OS_WINDOWS)
#ifndef MONO_DLL_IMPORT
#define MONO_DLL_IMPORT
#endif
#endif
#include <aeon/mono/mono_static_function.h>
#include <aeon/common/type_traits.h>
#include <aeon/common/compilers.h>
AEON_IGNORE_VS_WARNING_PUSH(4201)
#include <mono/jit/jit.h>
AEON_IGNORE_VS_WARNING_POP()
#include <string>
namespace aeon::mono
{
class mono_assembly;
class mono_class_field;
class mono_class
{
public:
mono_class() noexcept;
explicit mono_class(const mono_assembly *assembly, MonoClass *cls) noexcept;
explicit mono_class(const mono_assembly *assembly, MonoImage *image, const std::string &name);
explicit mono_class(const mono_assembly *assembly, MonoImage *image, const std::string &name_space,
const std::string &name);
virtual ~mono_class();
mono_class(const mono_class &) = delete;
[[nodiscard]] auto operator=(const mono_class &) -> mono_class & = delete;
mono_class(mono_class &&) noexcept;
[[nodiscard]] auto operator=(mono_class &&) noexcept -> mono_class &;
[[nodiscard]] auto get_static_function(const std::string &name, int argc = 0) const -> mono_static_function;
template <typename function_signature_t>
[[nodiscard]] auto get_static_function_thunk(const std::string &name) const;
[[nodiscard]] auto get_mono_class_ptr() const noexcept -> MonoClass *;
[[nodiscard]] auto get_field(const std::string &name) const -> mono_class_field;
private:
MonoClass *class_;
const mono_assembly *assembly_;
};
template <typename function_signature_t>
[[nodiscard]] auto mono_class::get_static_function_thunk(const std::string &name) const
{
constexpr auto arg_count = common::type_traits::function_signature_argument_count<function_signature_t>::value;
auto func = get_static_function(name, arg_count);
return func.template get_thunk<function_signature_t>();
}
} // namespace aeon::mono
|
matthieu-vergne/Parsing
|
parsing-core/src/main/java/fr/vergne/parsing/layer/util/Time.java
|
<reponame>matthieu-vergne/Parsing
package fr.vergne.parsing.layer.util;
import fr.vergne.parsing.layer.standard.Atom;
import fr.vergne.parsing.layer.standard.Formula;
import fr.vergne.parsing.layer.standard.Option;
import fr.vergne.parsing.layer.standard.Suite;
public class Time extends Suite {
public Time() {
super(new Formula("[0-9]{1,2}"), new Atom(":"), new Formula(
"[0-9]{1,2}"), new Option<Suite>(new Suite(new Atom(":"),
new Formula("[0-9]{1,2}"), new Option<Suite>(new Suite(
new Atom("."), new Formula("[0-9]{1,3}"))))));
}
public Integer getHours() {
Formula formula = get(0);
return Integer.parseInt(formula.getContent());
}
public Integer getMinutes() {
Formula formula = get(2);
return Integer.parseInt(formula.getContent());
}
public Integer getSeconds() {
Option<Suite> option = get(3);
if (option.isPresent()) {
Formula formula = option.getOption().get(1);
return Integer.parseInt(formula.getContent());
} else {
return null;
}
}
public Integer getMilliseconds() {
Option<Suite> option = get(3);
if (option.isPresent()) {
Option<Suite> option2 = option.getOption().get(2);
if (option2.isPresent()) {
Formula formula = option2.getOption().get(1);
String content = formula.getContent();
while (content.length() < 3) {
content += "0";
}
return Integer.parseInt(content);
} else {
return null;
}
} else {
return null;
}
}
}
|
anyulled/react-boilerplate
|
app/components/Version4/counterparty/AddCounterpartyStep2Component/index.js
|
<reponame>anyulled/react-boilerplate
/**
*
* AddCounterpartyStep2Component
*
*/
import React, { PropTypes } from 'react';
import { Row, FormGroup, ControlLabel, Checkbox } from 'react-bootstrap';
import StepsHeaderComponent from '../../common/StepsHeaderComponent';
import RadioGroupAddDeal from '../../common/RadioGroupAddDeal';
import CounterpartyItemComponent from '../CounterpartyItemComponent';
function AddCounterpartyStep2Component({ showStep2, RadioGroupAddDealData }) {
return (
<div className="step2">
<StepsHeaderComponent title="Configure limits for the selected counterparties" step={2} />
{showStep2 &&
<Row className="row-eq-height counterparties">
<div className="content-pane pane-2 col-md-6">
<div className="content-block">
<form>
<FormGroup>
<ControlLabel>Selected counterparties (Mark counterparties to restrict)</ControlLabel>
<div className="counterparty-list">
<FormGroup>
<Checkbox inline>
<CounterpartyItemComponent title="CLIENTS & OBLIGORS" btnGroup />
</Checkbox>
<FormGroup>
<Checkbox inline>
<CounterpartyItemComponent title="GUARANTOR" />
</Checkbox>
</FormGroup>
</FormGroup>
<FormGroup>
<Checkbox inline>
<CounterpartyItemComponent title="CLIENTS" />
</Checkbox>
<FormGroup>
<Checkbox inline>
<CounterpartyItemComponent title="GUARANTOR" />
</Checkbox>
</FormGroup>
<FormGroup>
<Checkbox inline>
<CounterpartyItemComponent title="OBLIGORS" btnGroup />
</Checkbox>
</FormGroup>
<FormGroup>
<Checkbox inline>
<CounterpartyItemComponent btnGroup />
</Checkbox>
<FormGroup>
<Checkbox inline>
<CounterpartyItemComponent title="GUARANTOR" />
</Checkbox>
</FormGroup>
</FormGroup>
</FormGroup>
<FormGroup>
<Checkbox inline>
<CounterpartyItemComponent />
</Checkbox>
</FormGroup>
</div>
</FormGroup>
</form>
</div>
</div>
<div className="content-pane pane-2 col-md-6">
<RadioGroupAddDeal data={RadioGroupAddDealData} />
</div>
</Row>
}
</div>
);
}
AddCounterpartyStep2Component.propTypes = {
RadioGroupAddDealData: PropTypes.object.isRequired,
showStep2: PropTypes.bool,
};
export default AddCounterpartyStep2Component;
|
LeandroTk/Algorithms
|
computer_science/data_structures/stack/stack_class.js
|
class Stack {
constructor() {
this.items = [];
}
push(item) {
this.items.push(item);
}
pop() {
return this.items.pop();
}
top() {
return this.items[this.items.length - 1];
}
isEmpty() {
return this.size() === 0;
}
size() {
return this.items.length;
}
}
// testing
const stack = new Stack();
console.log(stack.isEmpty());
stack.push(1);
console.log(stack.items);
stack.push(2);
console.log(stack.items);
stack.push(3);
console.log(stack.items);
stack.push(4);
console.log(stack.items);
stack.push(5);
console.log(stack.items);
console.log(stack.isEmpty());
console.log(stack.top());
stack.pop();
console.log(stack.items);
stack.pop();
console.log(stack.items);
stack.pop();
console.log(stack.items);
stack.pop();
console.log(stack.items);
console.log(stack.isEmpty());
stack.pop();
console.log(stack.items);
console.log(stack.isEmpty());
console.log(stack.top());
// Reversing a list with the stack data structure
function reverse(list) {
const stack = new Stack();
for (item of list) {
stack.push(item);
}
const reversedList = [];
while (!stack.isEmpty()) {
reversedList.push(stack.pop());
}
return reversedList;
}
const reversedBooks = reverse([
'<NAME>',
'Atomic Habits',
'<NAME>',
'Sapiens',
'Peak',
]);
console.log(reversedBooks);
|
alfred-landrum/pravega
|
controller/src/main/java/io/pravega/controller/store/stream/records/Subscribers.java
|
<filename>controller/src/main/java/io/pravega/controller/store/stream/records/Subscribers.java<gh_stars>0
/**
* Copyright Pravega Authors.
*
* 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 io.pravega.controller.store.stream.records;
import com.google.common.collect.ImmutableSet;
import io.pravega.common.ObjectBuilder;
import io.pravega.common.io.serialization.RevisionDataInput;
import io.pravega.common.io.serialization.RevisionDataOutput;
import io.pravega.common.io.serialization.VersionedSerializer;
import lombok.Data;
import lombok.Getter;
import lombok.NonNull;
import lombok.Builder;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
* Data class containing the list of subscribers registered to a Stream.
*/
@Slf4j
@Data
public class Subscribers {
public static final Subscribers EMPTY_SET = new Subscribers(ImmutableSet.of());
public static final SubscriberSetSerializer SERIALIZER = new SubscriberSetSerializer();
@Getter
private final ImmutableSet<String> subscribers;
@Builder
public Subscribers(@NonNull ImmutableSet<String> subscribers) {
this.subscribers = subscribers;
}
/**
* This method adds a new subscriber to the subscriberSet.
* @param subscriberSet Subscriber Set.
* @param subscriber subscriber to be added.
* @return updated Subscriber Set.
*/
public static Subscribers add(@NonNull Subscribers subscriberSet, @NonNull String subscriber) {
ImmutableSet.Builder<String> builder = ImmutableSet.builder();
builder.addAll(subscriberSet.subscribers);
builder.add(subscriber);
return new Subscribers(builder.build());
}
/**
* This method removes a subscriber from the subscriberSet.
* @param subscriberSet Subscriber Set.
* @param subscriber subscriber to be removed.
* @return updated Subscriber Set.
*/
public static Subscribers remove(@NonNull Subscribers subscriberSet, @NonNull String subscriber) {
ImmutableSet.Builder<String> builder = ImmutableSet.builder();
subscriberSet.getSubscribers().forEach(s -> {
if (!s.equals(subscriber)) {
builder.add(s);
}
});
return new Subscribers(builder.build());
}
private static class SubscribersBuilder implements ObjectBuilder<Subscribers> {
}
@SneakyThrows(IOException.class)
public static Subscribers fromBytes(final byte[] data) {
return SERIALIZER.deserialize(data);
}
@SneakyThrows(IOException.class)
public byte[] toBytes() {
return SERIALIZER.serialize(this).getCopy();
}
private static class SubscriberSetSerializer
extends VersionedSerializer.WithBuilder<Subscribers, Subscribers.SubscribersBuilder> {
@Override
protected byte getWriteVersion() {
return 0;
}
@Override
protected void declareVersions() {
version(0).revision(0, this::write00, this::read00);
}
private void read00(RevisionDataInput revisionDataInput, Subscribers.SubscribersBuilder recordBuilder)
throws IOException {
ImmutableSet.Builder<String> builder = ImmutableSet.builder();
revisionDataInput.readCollection(DataInput::readUTF, builder);
recordBuilder.subscribers(builder.build());
}
private void write00(Subscribers subscribersRecord, RevisionDataOutput revisionDataOutput) throws IOException {
revisionDataOutput.writeCollection(subscribersRecord.getSubscribers(), DataOutput::writeUTF);
}
@Override
protected Subscribers.SubscribersBuilder newBuilder() {
return Subscribers.builder();
}
}
}
|
jimcoles/actionable
|
actionables-pmc-ref/src/main/java/com/oculussoftware/util/IRElementNameLister.java
|
package com.oculussoftware.util;
/*
* $Workfile: IRElementNameLister.java $
* Date: 9-06-00
* Description: Supports building lists of things.
*
* Copyright 7-01-2000 productmarketing.com. All Rights Reserved.
*
* Author: <NAME>
* Version 1.2
*/
import com.oculussoftware.api.repi.*;
import com.oculussoftware.api.sysi.*;
public class IRElementNameLister implements Lister
{
// enum the singleton instance
public static Lister INSTANCE = new IRElementNameLister();
// constructor
private IRElementNameLister() { }
// Lister.getListString()
public String getListString(Object obj)
{
String retVal = "(bad IRElement)";
if (obj instanceof IRElement) {
try {
retVal = ((IRElement) obj).getName();
}
catch (OculusException ex) {
retVal = "err: " + ex.getMessage();
}
}
return retVal;
}
}
|
vbondarevsky/c-plus-plus-white
|
white/structure-lecture-title/LectureTitle.cpp
|
#include <string>
using namespace std;
struct Specialization
{
string value;
explicit Specialization(const string& new_value)
{
value = new_value;
}
};
struct Course
{
string value;
explicit Course(const string& new_value)
{
value = new_value;
}
};
struct Week
{
string value;
explicit Week(const string& new_value)
{
value = new_value;
}
};
struct LectureTitle
{
string specialization;
string course;
string week;
LectureTitle(const Specialization& s, const Course& c, const Week& w)
{
specialization = s.value;
course = c.value;
week = w.value;
}
};
|
lechium/tvOS130Headers
|
System/Library/PrivateFrameworks/WebKitLegacy.framework/WebInspectorFrontend.h
|
<reponame>lechium/tvOS130Headers<gh_stars>10-100
/*
* This header is generated by classdump-dyld 1.0
* on Tuesday, November 5, 2019 at 2:47:03 AM Mountain Standard Time
* Operating System: Version 13.0 (Build 17J586)
* Image Source: /System/Library/PrivateFrameworks/WebKitLegacy.framework/WebKitLegacy
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
#import <WebKitLegacy/WebKitLegacy-Structs.h>
@interface WebInspectorFrontend : NSObject {
WebInspectorFrontendClient* m_frontendClient;
}
-(void)close;
-(void)setDebuggingEnabled:(BOOL)arg1 ;
-(void)detach;
-(void)attach;
-(void)showConsole;
-(BOOL)isDebuggingEnabled;
-(BOOL)isTimelineProfilingEnabled;
-(void)setTimelineProfilingEnabled:(BOOL)arg1 ;
-(BOOL)isProfilingJavaScript;
-(id)initWithFrontendClient:(WebInspectorFrontendClient*)arg1 ;
-(void)startProfilingJavaScript;
-(void)stopProfilingJavaScript;
@end
|
jnthn/intellij-community
|
plugins/xslt-debugger/engine/impl/src/org/intellij/plugins/xsltDebugger/rt/engine/local/saxon/SaxonTraceListener.java
|
<filename>plugins/xslt-debugger/engine/impl/src/org/intellij/plugins/xsltDebugger/rt/engine/local/saxon/SaxonTraceListener.java
/*
* Copyright 2007 <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 org.intellij.plugins.xsltDebugger.rt.engine.local.saxon;
import com.icl.saxon.Context;
import com.icl.saxon.Controller;
import com.icl.saxon.Mode;
import com.icl.saxon.NodeHandler;
import com.icl.saxon.om.NamePool;
import com.icl.saxon.om.Navigator;
import com.icl.saxon.om.NodeInfo;
import com.icl.saxon.output.Emitter;
import com.icl.saxon.output.GeneralOutputter;
import com.icl.saxon.style.StyleElement;
import com.icl.saxon.trace.TraceListener;
import org.intellij.plugins.xsltDebugger.rt.engine.local.LocalDebugger;
import org.intellij.plugins.xsltDebugger.rt.engine.local.OutputEventQueueImpl;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerException;
import java.lang.reflect.Field;
import java.util.Properties;
/**
* A Simple trace listener that writes messages to System.err
*/
public class SaxonTraceListener implements TraceListener {
private static final boolean TRACE = "true".equals(System.getProperty("xslt.debugger.trace", "false"));
private String indent = "";
private final LocalDebugger myDebugger;
private final Controller myController;
private boolean myIsInitialized;
public SaxonTraceListener(LocalDebugger debugger, Controller controller) {
myDebugger = debugger;
myController = controller;
}
/**
* Called at start
*/
public void open() {
myDebugger.getEventQueue().startDocument();
if (TRACE) {
trace("<trace>");
}
}
private static void trace(String s) {
if (TRACE) {
System.err.println(s);
}
}
/**
* Called at end
*/
public void close() {
myDebugger.getEventQueue().endDocument();
// myDebugger.stopped();
if (TRACE) {
trace("</trace>");
}
}
/**
* Called for all top level elements
*/
public void toplevel(NodeInfo element) {
if (!myIsInitialized) {
myIsInitialized = true;
final Properties properties = myController.getOutputProperties();
final String method = properties.getProperty(OutputKeys.METHOD);
if (method == null || "xml".equals(method) || "html".equals(method)) {
try {
final Emitter emitter = myController.getOutputter().getEmitter();
final GeneralOutputter outputter = new TracingOutputter(emitter, myController.getNamePool());
final Field fOutputter = Controller.class.getDeclaredField("currentOutputter");
fOutputter.setAccessible(true);
fOutputter.set(myController, outputter);
} catch (Exception e1) {
System.err.println("Failed to change output emitter");
e1.printStackTrace();
}
}
}
if (TRACE) {
StyleElement e = (StyleElement)element;
trace("<Top-level element=\"" + e.getDisplayName() + "\" line=\"" + e.getLineNumber() +
"\" file=\"" + e.getSystemId() + "\" precedence=\"" + e.getPrecedence() + "\"/>");
}
}
/**
* Called when a node of the source tree gets processed
*/
public void enterSource(NodeHandler handler, Context context) {
NodeInfo curr = context.getContextNodeInfo();
final String path = Navigator.getPath(curr);
if (TRACE) {
trace(indent + "<Source node=\"" + path
+ "\" line=\"" + curr.getLineNumber()
+ "\" mode=\"" + getModeName(context) + "\">");
indent += " ";
}
myDebugger.pushSource(new SaxonSourceFrame(myDebugger.getSourceFrame(), curr));
}
/**
* Called after a node of the source tree got processed
*/
public void leaveSource(NodeHandler handler, Context context) {
if (TRACE) {
indent = indent.substring(0, indent.length() - 1);
trace(indent + "</Source><!-- " +
Navigator.getPath(context.getContextNodeInfo()) + " -->");
}
myDebugger.popSource();
}
/**
* Called when an element of the stylesheet gets processed
*/
public void enter(NodeInfo element, Context context) {
if (element.getNodeType() == NodeInfo.ELEMENT) {
if (TRACE) {
trace(indent + "<Instruction element=\"" + element.getDisplayName() + "\" line=\"" + element.getLineNumber() + "\">");
indent += " ";
}
myDebugger.enter(new SaxonFrameImpl(myDebugger.getCurrentFrame(), context, (StyleElement)element));
}
}
/**
* Called after an element of the stylesheet got processed
*/
public void leave(NodeInfo element, Context context) {
if (element.getNodeType() == NodeInfo.ELEMENT) {
// final int lineNumber = element.getLineNumber();
// final String uri = element.getSystemId();
myDebugger.leave();
if (TRACE) {
indent = indent.substring(0, indent.length() - 1);
trace(indent + "</Instruction> <!-- " +
element.getDisplayName() + " -->");
}
}
}
static String getModeName(Context context) {
Mode mode = context.getMode();
if (mode == null) return "#none";
int nameCode = mode.getNameCode();
if (nameCode == -1) {
return "#default";
} else {
return context.getController().getNamePool().getDisplayName(nameCode);
}
}
private final class TracingOutputter extends GeneralOutputter {
private final NamePool myNamePool;
private final OutputEventQueueImpl myEventQueue;
TracingOutputter(Emitter emitter, NamePool namePool) {
super(namePool);
this.emitter = emitter;
myNamePool = namePool;
myEventQueue = myDebugger.getEventQueue();
}
@Override
public void writeAttribute(int nameCode, String value, boolean noEscape) throws TransformerException {
if (myEventQueue.isEnabled()) {
final String localName = myNamePool.getLocalName(nameCode);
final String prefix = myNamePool.getPrefix(nameCode);
myEventQueue.attribute(prefix, localName, myNamePool.getURI(nameCode), value);
}
super.writeAttribute(nameCode, value, noEscape);
}
@Override
public void writeComment(String comment) throws TransformerException {
myEventQueue.comment(comment);
super.writeComment(comment);
}
@Override
public void writeContent(char[] chars, int start, int length) throws TransformerException {
myEventQueue.characters(new String(chars, start, length));
super.writeContent(chars, start, length);
}
@Override
public void writeContent(StringBuffer chars, int start, int len) throws TransformerException {
myEventQueue.characters(chars.substring(start, start + len));
super.writeContent(chars, start, len);
}
@Override
public void writeEndTag(int nameCode) throws TransformerException {
myEventQueue.endElement();
super.writeEndTag(nameCode);
}
@Override
public void writePI(String target, String data) throws TransformerException {
myEventQueue.pi(target, data);
super.writePI(target, data);
}
@Override
public void writeStartTag(int nameCode) throws TransformerException {
if (myEventQueue.isEnabled()) {
final String localName = myNamePool.getLocalName(nameCode);
final String prefix = myNamePool.getPrefix(nameCode);
myEventQueue.startElement(prefix, localName, myNamePool.getURI(nameCode));
}
super.writeStartTag(nameCode);
}
}
}
|
Xwudao/ujuji_backend
|
src/main/java/com/ujuji/navigation/util/VerifyCodeUtils.java
|
<gh_stars>10-100
package com.ujuji.navigation.util;
import com.ujuji.navigation.model.dto.VerifyCodeDto;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.SpecCaptcha;
import org.apache.commons.lang3.RandomUtils;
public class VerifyCodeUtils {
public static VerifyCodeDto getRandomCode() {
int num = RandomUtils.nextInt(1, 100);
int r = num % 2;
VerifyCodeDto verifyCodeDto = new VerifyCodeDto();
switch (r) {
// case 2:
// // 中文类型
// ChineseCaptcha chineseCaptcha = new ChineseCaptcha(120, 40, 3);
// verifyCodeDto.setCode(chineseCaptcha.text());
// verifyCodeDto.setImage(chineseCaptcha.toBase64());
// break;
case 1:
//png
SpecCaptcha captcha = new SpecCaptcha(120, 40, 4);
verifyCodeDto.setCode(captcha.text());
verifyCodeDto.setImage(captcha.toBase64());
break;
case 0://算术
ArithmeticCaptcha arithmeticCaptcha = new ArithmeticCaptcha(120, 40, 2);
verifyCodeDto.setCode(arithmeticCaptcha.text());
verifyCodeDto.setImage(arithmeticCaptcha.toBase64());
break;
}
return verifyCodeDto;
}
}
|
mmatoscom/serenity
|
Kernel/DoubleBuffer.h
|
<reponame>mmatoscom/serenity
#pragma once
#include <AK/Types.h>
#include <AK/Vector.h>
#include <Kernel/Lock.h>
class DoubleBuffer {
public:
DoubleBuffer()
: m_write_buffer(&m_buffer1)
, m_read_buffer(&m_buffer2)
{
}
ssize_t write(const byte*, ssize_t);
ssize_t read(byte*, ssize_t);
bool is_empty() const { return m_empty; }
// FIXME: Isn't this racy? What if we get interrupted between getting the buffer pointer and dereferencing it?
ssize_t bytes_in_write_buffer() const { return (ssize_t)m_write_buffer->size(); }
private:
void flip();
void compute_emptiness();
Vector<byte>* m_write_buffer { nullptr };
Vector<byte>* m_read_buffer { nullptr };
Vector<byte> m_buffer1;
Vector<byte> m_buffer2;
ssize_t m_read_buffer_index { 0 };
bool m_empty { true };
Lock m_lock { "DoubleBuffer" };
};
|
wilebeast/FireFox-OS
|
B2G/gecko/js/src/jit-test/tests/proxy/testDirectProxyHas1.js
|
<filename>B2G/gecko/js/src/jit-test/tests/proxy/testDirectProxyHas1.js
// Forward to the target if the trap is not defined
var proxy = new Proxy(Object.create(Object.create(null, {
'foo': {
configurable: true
}
}), {
'bar': {
configurable: true
}
}), {});
assertEq('foo' in proxy, true);
assertEq('bar' in proxy, true);
assertEq('baz' in proxy, false);
|
dulibrarytech/digcoll-frontend
|
public/assets/js/downloader.js
|
/**
Copyright 2020 University of Denver
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.
*/
"use strict";
import { ProgressBar } from './progress-bar.js';
export const Downloader = (function () {
var downloadBatch = function(downloadUrl, socketUrl) {
var progressBar = new ProgressBar("file-download-progress", "100");
progressBar.displayMessage("Connecting to server...");
const button = document.createElement("BUTTON");
button.setAttribute("id", "batch-file-download-cancel");
button.innerHTML = "Cancel";
button.disabled = true;
document.getElementById("file-download-progress").appendChild(button);
disableDownloadControls(true);
var socket = new WebSocket(socketUrl);
socket.onopen = function(event) {
console.log("Connection to socket established.");
socket.onmessage = function (event) {
var msg = JSON.parse(event.data);
try {
switch(msg.status) {
// Begin file transfer
case "1":
progressBar.displayMessage("Retrieving files, please wait...");
progressBar.setMaxValue(msg.itemCount);
break;
// Single file was transferred
case "2":
button.disabled = false;
progressBar.increment(1);
break;
// File transfer complete
case "3":
progressBar.displayMessage("Downloading...");
break;
// Download complete
case "4":
progressBar.remove();
console.log("Closing socket");
socket.close();
disableDownloadControls(false);
break;
// Error
case "5":
progressBar.remove();
console.log("Socket error");
socket.close();
disableDownloadControls(false);
break;
// Server received abort command
case "6":
progressBar.remove();
console.log("Closing socket");
socket.close();
disableDownloadControls(false);
break;
default:
console.log("Socket error");
socket.close();
disableDownloadControls(false);
break;
}
if(msg.message) {
console.log(msg.message);
}
} catch (e) {
console.log(e);
}
}
socket.onerror = function(event) {
socket.close();
console.log(event);
};
button.addEventListener("click", function(event) {
cancelDownload(socket);
});
submitLinkRequest(downloadUrl, "");
};
}
var cancelDownload = function(socket) {
console.log("Cancelling download");
socket.send(JSON.stringify({abort: true}));
}
var submitLinkRequest = function(url, filename) {
var anchor = document.createElement('a');
anchor.style.display = 'none';
anchor.href = url;
anchor.download = '';
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
}
var disableDownloadControls = function(disable=true) {
for(var downloadButton of document.getElementsByClassName("batch-download-button")) {
downloadButton.disabled = disable;
}
document.getElementById("download-links-select").disabled = disable;
}
return {
downloadBatch: function(downloadUrl, socketUrl) {
return downloadBatch(downloadUrl, socketUrl);
},
submitLinkRequest: function(url, filename) {
submitLinkRequest(url, filename);
}
}
}());
|
rfedorenkov/JavaRushTasks
|
1.JavaSyntax/src/com/javarush/task/jdk13/task07/task0717/Solution.java
|
package com.javarush.task.jdk13.task07.task0717;
import java.util.ArrayList;
import java.util.Scanner;
/**
* Удвой слова
* 1. Введи с клавиатуры 10 слов в список строк.
* 2. Метод doubleValues должен удваивать слова по принципу
* "альфа", "бета", "гамма" -> "альфа", "альфа", "бета", "бета", "гамма", "гамма".
* 3. Выведи результат на экран, каждое значение с новой строки.
*
* Требования:
* 1. Объяви переменную типа список строк и сразу проинициализируй ee.
* 2. Считай 10 строк с клавиатуры и добавь их в список.
* 3. Метод doubleValues должен удваивать элементы списка по принципу
* "альфа", "бета", "гамма" -> "альфа", "альфа", "бета", "бета", "гамма", "гамма".
* 4. Выведи получившийся список на экран, каждый элемент с новой строки.
*/
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add(scanner.next());
}
ArrayList<String> result = doubleValues(list);
result.forEach(System.out::println);
}
public static ArrayList<String> doubleValues(ArrayList<String> list) {
for (int i = 0; i < list.size(); i += 2) {
list.add(i, list.get(i));
}
return list;
}
}
|
Pro100Tema/ostap
|
ostap/logger/logger.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# =============================================================================
# Copyright Ostap developers
# =============================================================================
"""Ostap simple logger.
Bsed on the logging of the Gaudi software project of CERN:
- Simple control (global and local) over logging threshold.
Primitive utilities for colorized logging.
"""
# =============================================================================
import logging
# =============================================================================
__all__ = (
'getLogger' , ## get (configured) logger
'setLogging' , ## set disable level according to MSG.Level
'LogLevel' , ## context manager to control output level
'logLevel' , ## helper function to control output level
'logVerbose' , ## helper function to control output level
'logDebug' , ## helper function to control output level
'logInfo' , ## helper function to control output level
'logWarning' , ## helper function to control output level
'logError' , ## helper function to control output level
'logColor' , ## context manager to switch on color logging locally
'logNoColor' , ## context manager to switch off color logging locally
'noColor' , ## context manager to switch off color logging locally
'make_colors' , ## force colored logging
'reset_colors' , ## reset colored logging
'colored_string' , ## make a colored string
'attention' , ## make "attention" string
'allright' , ## make "allright" string
##
'ALL', 'VERBOSE', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'FATAL' ,
)
# =============================================================================
# Message levels
ALL = 0
VERBOSE = 1
DEBUG = 2
INFO = 3
WARNING = 4
ERROR = 5
FATAL = 6
# =============================================================================
## some manipulations with logging module
if not hasattr ( logging , 'VERBOSE' ) : logging.VERBOSE = 5
# =============================================================================
## Log message with severity 'VERBOSE'
def _verbose1_(self, msg, *args, **kwargs):
"""Log 'msg % args' with severity 'VERBOSE'.
"""
if self.isEnabledFor(logging.VERBOSE):
self._log(logging.VERBOSE, msg, args, **kwargs)
# =============================================================================
## Log message with severity 'VERBOSE'
def _verbose2_(msg, *args, **kwargs):
"""Log a message with severity 'VERBOSE' on the root logger.
"""
if len(logging.root.handlers) == 0 : logging.basicConfig()
logging.root.verbose (msg, *args, **kwargs)
# =============================================================================
## add method 'verbose' to logger
logging.Logger.verbose = _verbose1_
# =============================================================================
## add method 'verbose' to root logger
logging.verbose = _verbose2_
# =============================================================================
## convert MSG::Level into logging level
def setLogging ( output_level ) :
"""Convert MSG::Level into logging level
"""
if FATAL <= output_level : logging.disable ( logging.FATAL - 1 )
elif ERROR <= output_level : logging.disable ( logging.ERROR - 1 )
elif WARNING <= output_level : logging.disable ( logging.WARNING - 1 )
elif INFO <= output_level : logging.disable ( logging.INFO - 1 )
elif DEBUG <= output_level : logging.disable ( logging.DEBUG - 1 )
elif VERBOSE <= output_level : logging.disable ( logging.VERBOSE - 1 )
## define standard logging names
logging.addLevelName ( logging.CRITICAL , 'FATAL ' )
logging.addLevelName ( logging.WARNING , 'WARNING' )
logging.addLevelName ( logging.DEBUG , 'DEBUG ' )
logging.addLevelName ( logging.INFO , 'INFO ' )
logging.addLevelName ( logging.ERROR , 'ERROR ' )
logging.addLevelName ( logging.VERBOSE , 'VERBOSE' )
# =============================================================================
# - is sys.stdout attached to terminal or not ?
# - do we run IPYTHON ?
from ostap.utils.basic import isatty
# =============================================================================
# COLORS:
# =============================================================================
## global flag to indicate if we use colored logging
__with_colors__ = False
# =============================================================================
## Is colorization enabled ?
def with_colors() :
"""Is colorization enabled ?"""
global __with_colors__
return bool(__with_colors__) and isatty()
# =============================================================================
## reset colorization of logging
def reset_colors() :
"""Reset colorization of logging
>>> reset_colors()
"""
logging.addLevelName ( logging.CRITICAL , 'FATAL ' )
logging.addLevelName ( logging.WARNING , 'WARNING' )
logging.addLevelName ( logging.DEBUG , 'DEBUG ' )
logging.addLevelName ( logging.INFO , 'INFO ' )
logging.addLevelName ( logging.ERROR , 'ERROR ' )
logging.addLevelName ( logging.VERBOSE , 'VERBOSE' )
#
global __with_colors__
__with_colors__ = False
return with_colors()
# =============================================================================
## get configured logger
# @code
# logger1 = getLogger ( 'LOGGER1' )
# logger2 = getLogger ( 'LOGGER2' , level = logging.INFO )
# @endcode
def getLogger ( name ,
fmt = '# %(name)-25s %(levelname)-7s %(message)s' ,
level = logging.VERBOSE - 2 ,
stream = None ) :
"""Get the proper logger
>>> logger1 = getLogger ( 'LOGGER1' )
>>> logger2 = getLogger ( 'LOGGER2' , level = logging.INFO )
"""
#
logger = logging.getLogger ( name )
logger.propagate = False
##logger.propagate = True
#
while logger.handlers :
logger.removeHandler ( logger.handlers[0] )
#
if not stream :
import sys
stream = sys.stdout
lh = logging.StreamHandler ( stream )
fmt = logging.Formatter ( fmt )
lh . setFormatter ( fmt )
logger.addHandler ( lh )
#
logger.setLevel ( level )
#
return logger
# =============================================================================
## @class LogLevel
# Temporarily enable/disable certain logger levels
# @code
# with LogLevel( logging.CRITICAL ) :
# ...do something...
# @endcode
class LogLevel(object) :
"""Temporarily enable/disable certain logger levels
>>> with LogLevel( logging.CRITICAL ) :
... do something here ...
"""
def __init__ ( self , level = logging.INFO - 1 ) :
self.new_level = level
self.old_level = logging.root.manager.disable
## context manager: ENTER
def __enter__ ( self ) :
self.old_level = logging.root.manager.disable
logging.disable ( self.new_level )
return self
## context manager: EXIT
def __exit__ ( self , *_ ) :
logging.disable ( self.old_level )
# =============================================================================
# Temporarily enable/disable certain logger levels
# @code
# with logLevel( logging.CRITICAL ) :
# ...do something...
# @endcode
def logLevel ( level = logging.INFO - 1 ) :
"""Temporarily enable/disable certain logger levels
>>> with logLevel( logging.CRITICAL ) :
>>> ...do something...
"""
return LogLevel ( level )
# =============================================================================
# Temporarily enable/disable all loggers with level less then DEBUG
# @code
# with logVerbose() :
# ...do something...
# @endcode
def logVerbose () :
"""Temporarily disable all loggers with level less then INFO
>>> with logVerbose() :
>>> ...do something...
"""
return logLevel ( logging.VERBOSE - 1 )
# =============================================================================
# Temporarily enable/disable all loggers with level less then DEBUG
# @code
# with logInfo() :
# ...do something...
# @endcode
def logDebug () :
"""Temporarily disable all loggers with level less then INFO
>>> with logDebug() :
>>> ...do something...
"""
return logLevel ( logging.DEBUG - 1 )
# =============================================================================
# Temporarily enable/disable all loggers with level less then INFO
# @code
# with logInfo() :
# ...do something...
# @endcode
def logInfo () :
"""Temporarily disable all loggers with level less then INFO
>>> with logInfo() :
>>> ...do something...
"""
return logLevel ( logging.INFO - 1 )
# =============================================================================
# Temporarily enable/disable all loggers with level less then WARNING
# @code
# with logInfo() :
# ...do something...
# @endcode
def logWarning () :
"""Temporarily disable all loggers with level less then WARNING
>>> with logWarning() :
>>> ...do something...
"""
return logLevel ( logging.WARNING - 1 )
# =============================================================================
# Temporarily enable/disable all loggers with level less then ERROR
# @code
# with logError() :
# ...do something...
# @endcode
def logError () :
"""Temporarily disable all loggers with level less then ERROR
>>> with logWarning() :
>>> ...do something...
"""
return logLevel ( logging.ERROR - 1 )
## ASCII colors :
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = list ( range ( 8 ) )
# =============================================================================
## provide colored string
# @code
# print colored_string ( 'Hello' , foreground = RED , background = YELLOW , bold = True )
# @endcode
def colored_string ( what ,
foreground = None ,
background = None ,
bold = False ,
blink = False ,
underline = False ) :
"""
>>> print colored_string ( 'Hello' , foreground = RED , background = YELLOW , bold = True , blink = True , underline = True )
"""
## nothing to colorize or no coloring is activated
if not what or not with_colors() or not isatty() : return what
## nothing to do
if ( foreground is None ) and ( background is None ) :
if ( not bold ) and ( not blink ) and ( not underline ) : return what
RESET_SEQ = "\033[0m"
COLOR_SEQ = "\033[1;%dm"
BOLD_SEQ = "\033[1m" if bold else ''
BLINK_SEQ = "\033[5m" if blink else ''
ULINE_SEQ = "\033[4m" if underline else ''
fg = COLOR_SEQ % ( 30 + ( foreground % 8 ) ) if not foreground is None else ''
bg = COLOR_SEQ % ( 40 + ( background % 8 ) ) if not background is None else ''
return '{foreground}{background}{underline}{bold}{blink}{what}{reset}'.format (
foreground = fg ,
background = bg ,
underline = ULINE_SEQ ,
bold = BOLD_SEQ ,
blink = BLINK_SEQ ,
what = what ,
reset = RESET_SEQ )
# =============================================================================
## attention!
def attention ( what ) :
"""Attention string """
return colored_string ( what ,
foreground = YELLOW ,
background = RED ,
bold = True ,
blink = True ,
underline = True )
# =============================================================================
## allright
def allright ( what ) :
"""Allright string """
return colored_string ( what ,
foreground = YELLOW ,
background = GREEN ,
bold = True ,
blink = False ,
underline = False )
# =============================================================================
## make colors
def make_colors () :
"""Colorize logging
"""
if with_colors() : return
if not isatty () : return ## no colorization for non-TTY output
global __with_colors__
__with_colors__ = True
def makeName ( level , fg = None , bg = None , blink = False , underline = False ) :
name = logging.getLevelName ( level )
bold = fg is None and bg is None and not uderline
return colored_string ( name , fg , bg , bold , blink , underline )
logging.addLevelName ( logging.CRITICAL , makeName ( logging.CRITICAL , fg = RED , bg = BLUE , blink = True ) )
logging.addLevelName ( logging.WARNING , makeName ( logging.WARNING , fg = RED , bg = YELLOW , underline = True ) )
logging.addLevelName ( logging.ERROR , makeName ( logging.ERROR , fg = YELLOW , bg = RED , blink = True ) )
logging.addLevelName ( logging.INFO , makeName ( logging.INFO , bg = BLUE , fg = WHITE ) )
logging.addLevelName ( logging.DEBUG , makeName ( logging.DEBUG , bg = GREEN , fg = WHITE ) )
return with_colors()
# =============================================================================
## @class ColorLogging
# Simple context manager to swicth on coloring
# @code
# with ColorLogging():
# ... do something ...
# @endcode
class ColorLogging(object) :
"""Simple context manager to swith on coloring
>>> with ColorLogging() :
... do something ...
"""
def __init__ ( self , color = True ) :
self.color = color
def __enter__ ( self ) :
self.with_color = with_colors()
if self.color and not self.with_color : make_colors ()
elif self.with_color and not self.color : reset_colors ()
return self
def __exit__ ( self , *_ ) :
if self.color and not self.with_color : reset_colors ()
elif self.with_color and not self.color : make_colors ()
# =============================================================================
## simple context manager to switch on color logging
# @code
# with logColor() :
# ... do something ...
# @endcode
def logColor ( color = True ) :
"""Simple context manager to switch on coloring
>>> with logColor () :
... do something ...
"""
return ColorLogging ( color )
# =============================================================================
## simple context manager to switch off color logging
# @code
# with logNoColor() :
# ... do something ...
# @endcode
def logNoColor () :
"""Simple context manager to switch on coloring
>>> with logNoColor () :
... do something ...
"""
return ColorLogging ( False )
# =============================================================================
## simple context manager to switch off color logging
# @code
# with noColor() :
# ... do something ...
# @endcode
def noColor () :
"""Simple context manager to switch on coloring
>>> with noColor () :
... do something ...
"""
return ColorLogging ( False )
# =============================================================================
## @class KeepColorLogging
# Simple context manager to preserve coloring
# @code
# with KeepColorLogging():
# ... do something ...
# @endcode
class KeepColorLogging(object) :
"""Simple context manager to preserve coloring
>>> with KeepColorLogging() :
... do something ...
"""
def __enter__ ( self ) :
self.with_color = with_colors()
return self
def __exit__ ( self , *_ ) :
if self.with_color and not with_colors() : make_colors ()
elif with_colors() and not self.with_color : reset_colors ()
# =============================================================================
## simple context manager to preserve color logging
# @code
# with keepColor() :
# ... do something ...
# @endcode
def keepColor () :
"""Simple context manager to preserve color logging
>>> with keepColor () :
... do something ...
"""
return KeepColorLogging ()
## reset colors
## for ipython mode and TTY output activate colors
## if with_ipython() and isatty () :
if isatty () :
make_colors()
## define default logging thresholds as 'INFO'
setLogging ( 3 )
# =============================================================================
if __name__ == '__main__' :
setLogging ( 0 )
logger = getLogger ( 'ostap.logger')
from ostap.utils.docme import docme
docme ( __name__ , logger = logger )
logger.verbose ( 'This is VERBOSE message' )
logger.debug ( 'This is DEBUG message' )
logger.info ( 'This is INFO message' )
logger.warning ( 'This is WARNING message' )
logger.error ( 'This is ERROR message' )
logger.fatal ( 'This is FATAL message' )
logger.critical ( 'This is CRITICAL message' )
with logColor() :
logger.verbose ( 'This is VERBOSE message' )
logger.debug ( 'This is DEBUG message' )
logger.info ( 'This is INFO message' )
logger.warning ( 'This is WARNING message' )
logger.error ( 'This is ERROR message' )
logger.fatal ( 'This is FATAL message' )
logger.critical ( 'This is CRITICAL message' )
with noColor () :
logger.verbose ( 'This is VERBOSE message' )
logger.debug ( 'This is DEBUG message' )
logger.info ( 'This is INFO message' )
logger.warning ( 'This is WARNING message' )
logger.error ( 'This is ERROR message' )
logger.fatal ( 'This is FATAL message' )
logger.critical ( 'This is CRITICAL message' )
logger.verbose ( 'This is VERBOSE message' )
logger.debug ( 'This is DEBUG message' )
logger.info ( 'This is INFO message' )
logger.warning ( 'This is WARNING message' )
logger.error ( 'This is ERROR message' )
logger.fatal ( 'This is FATAL message' )
logger.critical ( 'This is CRITICAL message' )
with keepColor() :
logger.verbose ( 'This is VERBOSE message' )
logger.debug ( 'This is DEBUG message' )
logger.info ( 'This is INFO message' )
logger.warning ( 'This is WARNING message' )
make_colors()
logger.error ( 'This is ERROR message' )
logger.fatal ( 'This is FATAL message' )
logger.critical ( 'This is CRITICAL message' )
logger.verbose ( 'This is VERBOSE message' )
logger.debug ( 'This is DEBUG message' )
logger.info ( 'This is INFO message' )
logger.warning ( 'This is WARNING message' )
logger.error ( 'This is ERROR message' )
logger.fatal ( 'This is FATAL message' )
logger.critical ( 'This is CRITICAL message' )
logger.info ( 80*'*' )
# =============================================================================
# The END
# =============================================================================
|
aimuch/NVIDIA_CUDA_Samples
|
NVIDIA_CUDA-9.0_Samples/7_CUDALibraries/cuSolverSp_LinearSolver/cuSolverSp_LinearSolver.cpp
|
/*
* Copyright 2015 NVIDIA Corporation. All rights reserved.
*
* Please refer to the NVIDIA end user license agreement (EULA) associated
* with this source code for terms and conditions that govern your use of
* this software. Any use, reproduction, disclosure, or distribution of
* this software and related documentation outside the terms of the EULA
* is strictly prohibited.
*
*/
/*
* Test three linear solvers, including Cholesky, LU and QR.
* The user has to prepare a sparse matrix of "matrix market format" (with extension .mtx).
* For example, the user can download matrices in Florida Sparse Matrix Collection.
* (http://www.cise.ufl.edu/research/sparse/matrices/)
*
* The user needs to choose a solver by the switch -R<solver> and
* to provide the path of the matrix by the switch -F<file>, then
* the program solves
* A*x = b where b = ones(m,1)
* and reports relative error
* |b-A*x|/(|A|*|x|)
*
* The elapsed time is also reported so the user can compare efficiency of different solvers.
*
* The runtime of linear solver contains symbolic analysis, numerical factorization and solve.
* The user can set environmental variable OMP_NUM_THREADS to configure number of cores in CPU path.
*
* How to use
/cuSolverSp_LinearSolver // Default: Cholesky, symrcm & file=lap2D_5pt_n100.mtx
* ./cuSolverSp_LinearSolver -R=chol -file=<file> // cholesky factorization
* ./cuSolverSp_LinearSolver -R=lu -P=symrcm -file=<file> // symrcm + LU with partial pivoting
* ./cuSolverSp_LinearSolver -R=qr -P=symamd -file=<file> // symamd + QR factorization
*
*
* Remark: the absolute error on solution x is meaningless without knowing condition number of A.
* The relative error on residual should be close to machine zero, i.e. 1.e-15.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <cuda_runtime.h>
#include "cusparse.h"
#include "cusolverSp.h"
#include "helper_cuda.h"
#include "helper_cusolver.h"
template <typename T_ELEM>
int loadMMSparseMatrix(
char *filename,
char elem_type,
bool csrFormat,
int *m,
int *n,
int *nnz,
T_ELEM **aVal,
int **aRowInd,
int **aColInd,
int extendSymMatrix);
void UsageSP(void)
{
printf( "<options>\n");
printf( "-h : display this help\n");
printf( "-R=<name> : choose a linear solver\n");
printf( " chol (cholesky factorization), this is default\n");
printf( " qr (QR factorization)\n");
printf( " lu (LU factorization)\n");
printf( "-P=<name> : choose a reordering\n");
printf( " symrcm (Reverse Cuthill-McKee)\n");
printf( " symamd (Approximate Minimum Degree)\n");
printf( "-file=<filename> : filename containing a matrix in MM format\n");
printf( "-device=<device_id> : <device_id> if want to run on specific GPU\n");
exit( 0 );
}
void parseCommandLineArguments(int argc, char *argv[], struct testOpts &opts)
{
memset(&opts, 0, sizeof(opts));
if (checkCmdLineFlag(argc, (const char **)argv, "-h"))
{
UsageSP();
}
if (checkCmdLineFlag(argc, (const char **)argv, "R"))
{
char *solverType = NULL;
getCmdLineArgumentString(argc, (const char **)argv, "R", &solverType);
if (solverType)
{
if ((STRCASECMP(solverType, "chol") != 0) && (STRCASECMP(solverType, "lu") != 0) && (STRCASECMP(solverType, "qr") != 0))
{
printf("\nIncorrect argument passed to -R option\n");
UsageSP();
}
else
{
opts.testFunc = solverType;
}
}
}
if (checkCmdLineFlag(argc, (const char **)argv, "P"))
{
char *reorderType = NULL;
getCmdLineArgumentString(argc, (const char **)argv, "P", &reorderType);
if (reorderType)
{
if ((STRCASECMP(reorderType, "symrcm") != 0) && (STRCASECMP(reorderType, "symamd") != 0))
{
printf("\nIncorrect argument passed to -P option\n");
UsageSP();
}
else
{
opts.reorder = reorderType;
}
}
}
if (!opts.reorder)
{
opts.reorder = "symrcm"; // Setting default reordering to be symrcm.
}
if (checkCmdLineFlag(argc, (const char **)argv, "file"))
{
char *fileName = 0;
getCmdLineArgumentString(argc, (const char **)argv, "file", &fileName);
if (fileName)
{
opts.sparse_mat_filename = fileName;
}
else
{
printf("\nIncorrect filename passed to -file \n ");
UsageSP();
}
}
}
int main (int argc, char *argv[])
{
struct testOpts opts;
cusolverSpHandle_t handle = NULL;
cusparseHandle_t cusparseHandle = NULL; // used in residual evaluation
cudaStream_t stream = NULL;
cusparseMatDescr_t descrA = NULL;
int rowsA = 0; // number of rows of A
int colsA = 0; // number of columns of A
int nnzA = 0; // number of nonzeros of A
int baseA = 0; // base index in CSR format
// CSR(A) from I/O
int *h_csrRowPtrA = NULL;
int *h_csrColIndA = NULL;
double *h_csrValA = NULL;
double *h_x = NULL; // x = A \ b
double *h_b = NULL; // b = ones(m,1)
double *h_r = NULL; // r = b - A*x
int *h_Q = NULL; // <int> n
// reorder to reduce zero fill-in
// Q = symrcm(A) or Q = symamd(A)
// B = Q*A*Q^T
int *h_csrRowPtrB = NULL; // <int> n+1
int *h_csrColIndB = NULL; // <int> nnzA
double *h_csrValB = NULL; // <double> nnzA
int *h_mapBfromA = NULL; // <int> nnzA
size_t size_perm = 0;
void *buffer_cpu = NULL; // working space for permutation: B = Q*A*Q^T
int *d_csrRowPtrA = NULL;
int *d_csrColIndA = NULL;
double *d_csrValA = NULL;
double *d_x = NULL; // x = A \ b
double *d_b = NULL; // a copy of h_b
double *d_r = NULL; // r = b - A*x
double tol = 1.e-12;
int reorder = 0; // no reordering
int singularity = 0; // -1 if A is invertible under tol.
// the constants are used in residual evaluation, r = b - A*x
const double minus_one = -1.0;
const double one = 1.0;
double x_inf = 0.0;
double r_inf = 0.0;
double A_inf = 0.0;
int errors = 0;
int issym = 0;
double start, stop;
double time_solve_cpu;
double time_solve_gpu;
parseCommandLineArguments(argc, argv, opts);
if (NULL == opts.testFunc)
{
opts.testFunc = "chol"; // By default running Cholesky as NO solver selected with -R option.
}
findCudaDevice(argc, (const char **)argv);
if (opts.sparse_mat_filename == NULL)
{
opts.sparse_mat_filename = sdkFindFilePath("lap2D_5pt_n100.mtx", argv[0]);
if (opts.sparse_mat_filename != NULL)
printf("Using default input file [%s]\n", opts.sparse_mat_filename);
else
printf("Could not find lap2D_5pt_n100.mtx\n");
}
else
{
printf("Using input file [%s]\n", opts.sparse_mat_filename);
}
printf("step 1: read matrix market format\n");
if (opts.sparse_mat_filename == NULL)
{
fprintf(stderr, "Error: input matrix is not provided\n");
return EXIT_FAILURE;
}
if (loadMMSparseMatrix<double>(opts.sparse_mat_filename, 'd', true , &rowsA, &colsA,
&nnzA, &h_csrValA, &h_csrRowPtrA, &h_csrColIndA, true))
{
exit(EXIT_FAILURE);
}
baseA = h_csrRowPtrA[0]; // baseA = {0,1}
printf("sparse matrix A is %d x %d with %d nonzeros, base=%d\n", rowsA, colsA, nnzA, baseA);
if ( rowsA != colsA ){
fprintf(stderr, "Error: only support square matrix\n");
return 1;
}
checkCudaErrors(cusolverSpCreate(&handle));
checkCudaErrors(cusparseCreate(&cusparseHandle));
checkCudaErrors(cudaStreamCreate(&stream));
checkCudaErrors(cusolverSpSetStream(handle, stream));
checkCudaErrors(cusparseSetStream(cusparseHandle, stream));
checkCudaErrors(cusparseCreateMatDescr(&descrA));
checkCudaErrors(cusparseSetMatType(descrA, CUSPARSE_MATRIX_TYPE_GENERAL));
if (baseA)
{
checkCudaErrors(cusparseSetMatIndexBase(descrA, CUSPARSE_INDEX_BASE_ONE));
}
else
{
checkCudaErrors(cusparseSetMatIndexBase(descrA, CUSPARSE_INDEX_BASE_ZERO));
}
h_x = (double*)malloc(sizeof(double)*colsA);
h_b = (double*)malloc(sizeof(double)*rowsA);
h_r = (double*)malloc(sizeof(double)*rowsA);
assert(NULL != h_x);
assert(NULL != h_b);
assert(NULL != h_r);
checkCudaErrors(cudaMalloc((void **)&d_csrRowPtrA, sizeof(int)*(rowsA+1)));
checkCudaErrors(cudaMalloc((void **)&d_csrColIndA, sizeof(int)*nnzA));
checkCudaErrors(cudaMalloc((void **)&d_csrValA , sizeof(double)*nnzA));
checkCudaErrors(cudaMalloc((void **)&d_x, sizeof(double)*colsA));
checkCudaErrors(cudaMalloc((void **)&d_b, sizeof(double)*rowsA));
checkCudaErrors(cudaMalloc((void **)&d_r, sizeof(double)*rowsA));
// verify if A has symmetric pattern or not
checkCudaErrors(cusolverSpXcsrissymHost(
handle, rowsA, nnzA, descrA, h_csrRowPtrA, h_csrRowPtrA+1, h_csrColIndA, &issym));
if ( 0 == strcmp(opts.testFunc, "chol") )
{
if (!issym)
{
printf("Error: A has no symmetric pattern, please use LU or QR \n");
exit(EXIT_FAILURE);
}
}
if (NULL != opts.reorder)
{
printf("step 2: reorder the matrix A to minimize zero fill-in\n");
printf(" if the user choose a reordering by -P=symrcm or -P=symamd\n");
printf(" The reordering will overwrite A such that \n");
printf(" A := A(Q,Q) where Q = symrcm(A) or Q = symamd(A)\n");
h_Q = (int* )malloc(sizeof(int)*colsA);
h_csrRowPtrB = (int* )malloc(sizeof(int)*(rowsA+1));
h_csrColIndB = (int* )malloc(sizeof(int)*nnzA);
h_csrValB = (double*)malloc(sizeof(double)*nnzA);
h_mapBfromA = (int* )malloc(sizeof(int)*nnzA);
assert(NULL != h_Q);
assert(NULL != h_csrRowPtrB);
assert(NULL != h_csrColIndB);
assert(NULL != h_csrValB );
assert(NULL != h_mapBfromA);
if ( 0 == strcmp(opts.reorder, "symrcm") )
{
checkCudaErrors(cusolverSpXcsrsymrcmHost(
handle, rowsA, nnzA,
descrA, h_csrRowPtrA, h_csrColIndA,
h_Q));
}
else if ( 0 == strcmp(opts.reorder, "symamd") )
{
checkCudaErrors(cusolverSpXcsrsymamdHost(
handle, rowsA, nnzA,
descrA, h_csrRowPtrA, h_csrColIndA,
h_Q));
}
else
{
fprintf(stderr, "Error: %s is unknown reordering\n", opts.reorder);
return 1;
}
// B = Q*A*Q^T
memcpy(h_csrRowPtrB, h_csrRowPtrA, sizeof(int)*(rowsA+1));
memcpy(h_csrColIndB, h_csrColIndA, sizeof(int)*nnzA);
checkCudaErrors(cusolverSpXcsrperm_bufferSizeHost(
handle, rowsA, colsA, nnzA,
descrA, h_csrRowPtrB, h_csrColIndB,
h_Q, h_Q,
&size_perm));
if (buffer_cpu)
{
free(buffer_cpu);
}
buffer_cpu = (void*)malloc(sizeof(char)*size_perm);
assert(NULL != buffer_cpu);
// h_mapBfromA = Identity
for(int j = 0 ; j < nnzA ; j++)
{
h_mapBfromA[j] = j;
}
checkCudaErrors(cusolverSpXcsrpermHost(
handle, rowsA, colsA, nnzA,
descrA, h_csrRowPtrB, h_csrColIndB,
h_Q, h_Q,
h_mapBfromA,
buffer_cpu));
// B = A( mapBfromA )
for(int j = 0 ; j < nnzA ; j++)
{
h_csrValB[j] = h_csrValA[ h_mapBfromA[j] ];
}
// A := B
memcpy(h_csrRowPtrA, h_csrRowPtrB, sizeof(int)*(rowsA+1));
memcpy(h_csrColIndA, h_csrColIndB, sizeof(int)*nnzA);
memcpy(h_csrValA , h_csrValB , sizeof(double)*nnzA);
printf("step 2.1: set right hand side vector (b) to 1\n");
}
else
{
printf("step 2: set right hand side vector (b) to 1\n");
}
for(int row = 0 ; row < rowsA ; row++)
{
h_b[row] = 1.0;
}
printf("step 3: prepare data on device\n");
checkCudaErrors(cudaMemcpy(d_csrRowPtrA, h_csrRowPtrA, sizeof(int)*(rowsA+1), cudaMemcpyHostToDevice));
checkCudaErrors(cudaMemcpy(d_csrColIndA, h_csrColIndA, sizeof(int)*nnzA , cudaMemcpyHostToDevice));
checkCudaErrors(cudaMemcpy(d_csrValA , h_csrValA , sizeof(double)*nnzA , cudaMemcpyHostToDevice));
checkCudaErrors(cudaMemcpy(d_b, h_b, sizeof(double)*rowsA, cudaMemcpyHostToDevice));
printf("step 4: solve A*x = b on CPU\n");
// A and b are read-only
start = second();
start = second();
if ( 0 == strcmp(opts.testFunc, "chol") )
{
checkCudaErrors(cusolverSpDcsrlsvcholHost(
handle, rowsA, nnzA,
descrA, h_csrValA, h_csrRowPtrA, h_csrColIndA,
h_b, tol, reorder, h_x, &singularity));
}
else if ( 0 == strcmp(opts.testFunc, "lu") )
{
checkCudaErrors(cusolverSpDcsrlsvluHost(
handle, rowsA, nnzA,
descrA, h_csrValA, h_csrRowPtrA, h_csrColIndA,
h_b, tol, reorder, h_x, &singularity));
}
else if ( 0 == strcmp(opts.testFunc, "qr") )
{
checkCudaErrors(cusolverSpDcsrlsvqrHost(
handle, rowsA, nnzA,
descrA, h_csrValA, h_csrRowPtrA, h_csrColIndA,
h_b, tol, reorder, h_x, &singularity));
}
else
{
fprintf(stderr, "Error: %s is unknown function\n", opts.testFunc);
return 1;
}
stop = second();
time_solve_cpu = stop - start;
if (0 <= singularity)
{
printf("WARNING: the matrix is singular at row %d under tol (%E)\n", singularity, tol);
}
printf("step 5: evaluate residual r = b - A*x (result on CPU)\n");
checkCudaErrors(cudaMemcpy(d_r, h_b, sizeof(double)*rowsA, cudaMemcpyHostToDevice));
checkCudaErrors(cudaMemcpy(d_x, h_x, sizeof(double)*colsA, cudaMemcpyHostToDevice));
checkCudaErrors(cusparseDcsrmv(cusparseHandle,
CUSPARSE_OPERATION_NON_TRANSPOSE,
rowsA,
colsA,
nnzA,
&minus_one,
descrA,
d_csrValA,
d_csrRowPtrA,
d_csrColIndA,
d_x,
&one,
d_r));
checkCudaErrors(cudaMemcpy(h_r, d_r, sizeof(double)*rowsA, cudaMemcpyDeviceToHost));
x_inf = vec_norminf(colsA, h_x);
r_inf = vec_norminf(rowsA, h_r);
A_inf = csr_mat_norminf(rowsA, colsA, nnzA, descrA, h_csrValA, h_csrRowPtrA, h_csrColIndA);
printf("(CPU) |b - A*x| = %E \n", r_inf);
printf("(CPU) |A| = %E \n", A_inf);
printf("(CPU) |x| = %E \n", x_inf);
printf("(CPU) |b - A*x|/(|A|*|x|) = %E \n", r_inf/(A_inf * x_inf));
printf("step 6: solve A*x = b on GPU\n");
// d_A and d_b are read-only
start = second();
start = second();
if ( 0 == strcmp(opts.testFunc, "chol") )
{
checkCudaErrors(cusolverSpDcsrlsvchol(
handle, rowsA, nnzA,
descrA, d_csrValA, d_csrRowPtrA, d_csrColIndA,
d_b, tol, reorder, d_x, &singularity));
}
else if ( 0 == strcmp(opts.testFunc, "lu") )
{
printf("WARNING: no LU available on GPU \n");
}
else if ( 0 == strcmp(opts.testFunc, "qr") )
{
checkCudaErrors(cusolverSpDcsrlsvqr(
handle, rowsA, nnzA,
descrA, d_csrValA, d_csrRowPtrA, d_csrColIndA,
d_b, tol, reorder, d_x, &singularity));
}
else
{
fprintf(stderr, "Error: %s is unknow function\n", opts.testFunc);
return 1;
}
checkCudaErrors(cudaDeviceSynchronize());
stop = second();
time_solve_gpu = stop - start;
if (0 <= singularity)
{
printf("WARNING: the matrix is singular at row %d under tol (%E)\n", singularity, tol);
}
printf("step 7: evaluate residual r = b - A*x (result on GPU)\n");
checkCudaErrors(cudaMemcpy(d_r, d_b, sizeof(double)*rowsA, cudaMemcpyDeviceToDevice));
checkCudaErrors(cusparseDcsrmv(cusparseHandle,
CUSPARSE_OPERATION_NON_TRANSPOSE,
rowsA,
colsA,
nnzA,
&minus_one,
descrA,
d_csrValA,
d_csrRowPtrA,
d_csrColIndA,
d_x,
&one,
d_r));
checkCudaErrors(cudaMemcpy(h_x, d_x, sizeof(double)*colsA, cudaMemcpyDeviceToHost));
checkCudaErrors(cudaMemcpy(h_r, d_r, sizeof(double)*rowsA, cudaMemcpyDeviceToHost));
x_inf = vec_norminf(colsA, h_x);
r_inf = vec_norminf(rowsA, h_r);
if ( 0 != strcmp(opts.testFunc, "lu") )
{
// only cholesky and qr have GPU version
printf("(GPU) |b - A*x| = %E \n", r_inf);
printf("(GPU) |A| = %E \n", A_inf);
printf("(GPU) |x| = %E \n", x_inf);
printf("(GPU) |b - A*x|/(|A|*|x|) = %E \n", r_inf/(A_inf * x_inf));
}
fprintf (stdout, "timing %s: CPU = %10.6f sec , GPU = %10.6f sec\n", opts.testFunc, time_solve_cpu, time_solve_gpu);
if (handle) { checkCudaErrors(cusolverSpDestroy(handle)); }
if (cusparseHandle) { checkCudaErrors(cusparseDestroy(cusparseHandle)); }
if (stream) { checkCudaErrors(cudaStreamDestroy(stream)); }
if (descrA) { checkCudaErrors(cusparseDestroyMatDescr(descrA)); }
if (h_csrValA ) { free(h_csrValA); }
if (h_csrRowPtrA) { free(h_csrRowPtrA); }
if (h_csrColIndA) { free(h_csrColIndA); }
if (h_x) { free(h_x); }
if (h_b) { free(h_b); }
if (h_r) { free(h_r); }
if (h_Q) { free(h_Q); }
if (h_csrRowPtrB) { free(h_csrRowPtrB); }
if (h_csrColIndB) { free(h_csrColIndB); }
if (h_csrValB ) { free(h_csrValB ); }
if (h_mapBfromA ) { free(h_mapBfromA ); }
if (buffer_cpu) { free(buffer_cpu); }
if (d_csrValA ) { checkCudaErrors(cudaFree(d_csrValA)); }
if (d_csrRowPtrA) { checkCudaErrors(cudaFree(d_csrRowPtrA)); }
if (d_csrColIndA) { checkCudaErrors(cudaFree(d_csrColIndA)); }
if (d_x) { checkCudaErrors(cudaFree(d_x)); }
if (d_b) { checkCudaErrors(cudaFree(d_b)); }
if (d_r) { checkCudaErrors(cudaFree(d_r)); }
return 0;
}
|
appscode/stash
|
vendor/stash.appscode.dev/apimachinery/pkg/invoker/interfaces.go
|
<reponame>appscode/stash
/*
Copyright AppsCode Inc. and Contributors
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 invoker
import (
"stash.appscode.dev/apimachinery/apis/stash/v1alpha1"
"stash.appscode.dev/apimachinery/apis/stash/v1beta1"
core "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kmapi "kmodules.xyz/client-go/api/v1"
appcatalog_cs "kmodules.xyz/custom-resources/client/clientset/versioned"
)
type MetadataHandler interface {
GetObjectMeta() metav1.ObjectMeta
GetTypeMeta() metav1.TypeMeta
GetObjectRef() (*core.ObjectReference, error)
GetOwnerRef() *metav1.OwnerReference
GetLabels() map[string]string
AddFinalizer() error
RemoveFinalizer() error
}
type ConditionHandler interface {
HasCondition(target *v1beta1.TargetRef, conditionType string) (bool, error)
GetCondition(target *v1beta1.TargetRef, conditionType string) (int, *kmapi.Condition, error)
SetCondition(target *v1beta1.TargetRef, newCondition kmapi.Condition) error
IsConditionTrue(target *v1beta1.TargetRef, conditionType string) (bool, error)
}
type RepositoryGetter interface {
GetRepoRef() kmapi.ObjectReference
GetRepository() (*v1alpha1.Repository, error)
}
type DriverHandler interface {
GetDriver() v1beta1.Snapshotter
}
type TimeOutGetter interface {
GetTimeOut() string
}
type Eventer interface {
CreateEvent(eventType, source, reason, message string) error
}
type KubeDBIntegrator interface {
EnsureKubeDBIntegration(appClient appcatalog_cs.Interface) error
}
type ObjectFormatter interface {
GetHash() string
GetObjectJSON() (string, error)
}
type Summarizer interface {
GetSummary(target v1beta1.TargetRef, session kmapi.ObjectReference) *v1beta1.Summary
}
|
dhavalgoti24/BoxIt-IME-indic
|
app/native/jni/src/dictionary/structure/backward/v402/content/bigram_entry.h
|
/*
* Copyright (C) 2013, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* !!!!! DO NOT EDIT THIS FILE !!!!!
*
* This file was generated from
* dictionary/structure/v4/content/bigram_entry.h
*/
#ifndef LATINIME_BACKWARD_V402_BIGRAM_ENTRY_H
#define LATINIME_BACKWARD_V402_BIGRAM_ENTRY_H
#include "defines.h"
#include "dictionary/property/historical_info.h"
#include "dictionary/structure/backward/v402/ver4_dict_constants.h"
namespace latinime {
namespace backward {
namespace v402 {
class BigramEntry {
public:
BigramEntry(const BigramEntry& bigramEntry)
: mHasNext(bigramEntry.mHasNext), mProbability(bigramEntry.mProbability),
mHistoricalInfo(), mTargetTerminalId(bigramEntry.mTargetTerminalId) {}
// Entry with historical information.
BigramEntry(const bool hasNext, const int probability, const int targetTerminalId)
: mHasNext(hasNext), mProbability(probability), mHistoricalInfo(),
mTargetTerminalId(targetTerminalId) {}
// Entry with historical information.
BigramEntry(const bool hasNext, const int probability,
const HistoricalInfo *const historicalInfo, const int targetTerminalId)
: mHasNext(hasNext), mProbability(probability), mHistoricalInfo(*historicalInfo),
mTargetTerminalId(targetTerminalId) {}
const BigramEntry getInvalidatedEntry() const {
return updateTargetTerminalIdAndGetEntry(Ver4DictConstants::NOT_A_TERMINAL_ID);
}
const BigramEntry updateHasNextAndGetEntry(const bool hasNext) const {
return BigramEntry(hasNext, mProbability, &mHistoricalInfo, mTargetTerminalId);
}
const BigramEntry updateTargetTerminalIdAndGetEntry(const int newTargetTerminalId) const {
return BigramEntry(mHasNext, mProbability, &mHistoricalInfo, newTargetTerminalId);
}
const BigramEntry updateProbabilityAndGetEntry(const int probability) const {
return BigramEntry(mHasNext, probability, &mHistoricalInfo, mTargetTerminalId);
}
const BigramEntry updateHistoricalInfoAndGetEntry(
const HistoricalInfo *const historicalInfo) const {
return BigramEntry(mHasNext, mProbability, historicalInfo, mTargetTerminalId);
}
bool isValid() const {
return mTargetTerminalId != Ver4DictConstants::NOT_A_TERMINAL_ID;
}
bool hasNext() const {
return mHasNext;
}
int getProbability() const {
return mProbability;
}
bool hasHistoricalInfo() const {
return mHistoricalInfo.isValid();
}
const HistoricalInfo *getHistoricalInfo() const {
return &mHistoricalInfo;
}
int getTargetTerminalId() const {
return mTargetTerminalId;
}
private:
// Copy constructor is public to use this class as a type of return value.
DISALLOW_DEFAULT_CONSTRUCTOR(BigramEntry);
DISALLOW_ASSIGNMENT_OPERATOR(BigramEntry);
const bool mHasNext;
const int mProbability;
const HistoricalInfo mHistoricalInfo;
const int mTargetTerminalId;
};
} // namespace v402
} // namespace backward
} // namespace latinime
#endif /* LATINIME_BACKWARD_V402_BIGRAM_ENTRY_H */
|
timgates42/Ender
|
lib/commands/info.js
|
/*!
* ENDER - The open module JavaScript framework
*
* Copyright (c) 2011-2012 @ded, @fat, @rvagg and other contributors
*
* 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.
*/
/******************************************************************************
* 'Info' executable module, prints pretty details about the build, can be
* used for the `ender info [--use <file>]` or by calling generateAndPrint()
* directly (this is done in main-build). Most of the pretty printing is done
* by main-info-output, we just provide the data/model here.
*/
var async = require('async')
, fs = require('fs')
, zlib = require('zlib')
, argsParser = require('../args-parser')
, LocalPackage = require('../local-package')
, util = require('../util')
, CompressionError = require('../errors').CompressionError
, FilesystemError = require('../errors').FilesystemError
, exec = function (options, log, callback, buildName, ids, files) {
var sizes = {}
, finish = function (callback) {
log.info('Your current build command is: {yellow}ender ' + argsParser.toContextString(options) + '{/yellow}')
log.info(
'Your current build size is: {yellow}' + util.toKb(sizes.build) + '{/yellow} raw' +
(sizes.minifiedBuild ?
', {yellow}' + util.toKb(sizes.minifiedBuild) + '{/yellow} minified' +
' and {yellow}' + util.toKb(sizes.gzippedMinifiedBuild) + '{/yellow} gzipped'
: '')
+ '\n')
LocalPackage.buildTree(ids, true, function (err, tree) {
if (err) return callback(err)
log.info(tree)
callback()
})
}
, calculateSizes = function (callback) {
sizes.build = files.build.length
if (!files.minifiedBuild) return callback()
sizes.minifiedBuild = files.minifiedBuild.length
zlib.gzip(files.minifiedBuild, function (err, data) {
if (err) return callback(new CompressionError(err))
sizes.gzippedMinifiedBuild = data.length
callback()
})
}
, loadFiles = function (callback) {
if (files) return callback()
var tasks = {}
tasks.build = fs.readFile.bind(null, buildName, 'utf-8')
if (options.minifier != 'none') {
tasks.minifiedBuild = fs.readFile.bind(null, buildName.replace(/\.js$/, '.min.js'), 'utf-8')
}
async.parallel(tasks, function (err, _files) {
if (err) return callback(new FilesystemError(err))
files = _files
callback()
})
}
, loadOptions = function (callback) {
// If we're the main command, we need to load things from the build
if (!buildName) {
buildName = util.getInputFilenameFromOptions(options)
options = null
}
if (options && ids) return callback()
// read 'Build: ...' and 'Packages: ...' from the head of the build file
util.parseContext(buildName, function (err, context) {
if (err) return callback(err)
options = context.options
if (!ids) ids = util.packageList(options)
callback()
})
}
if (arguments.length < 3) {
callback = log
log = undefined
}
if (!log) return callback()
async.series(
[
loadOptions
, loadFiles
, calculateSizes
, finish
]
, callback
)
}
module.exports.exec = exec
|
vcellmike/Biosimulators_VCell
|
vcell-server/src/main/java/cbit/vcell/modeldb/UserStatTable.java
|
<filename>vcell-server/src/main/java/cbit/vcell/modeldb/UserStatTable.java
/*
* Copyright (C) 1999-2011 University of Connecticut Health Center
*
* Licensed under the MIT License (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.opensource.org/licenses/mit-license.php
*/
package cbit.vcell.modeldb;
import org.vcell.db.KeyFactory;
import org.vcell.util.document.KeyValue;
import cbit.sql.Field;
import cbit.sql.Field.SQLDataType;
import cbit.sql.Table;
/**
* This type was created in VisualAge.
*/
public class UserStatTable extends cbit.sql.Table {
private static final String TABLE_NAME = "vc_userstat";
public static final String REF_TYPE = "REFERENCES " + TABLE_NAME + "(" + Table.id_ColumnName + ")";
public final Field userRef = new Field("userRef", SQLDataType.integer, "UNIQUE NOT NULL "+UserTable.REF_TYPE+" ON DELETE CASCADE");
public final Field loginCount = new Field("loginCount", SQLDataType.number_as_integer, "");
public final Field lastLogin = new Field("lastLogin", SQLDataType.date, "");
public final Field emailLostPasswordOK = new Field("emailLostPasswordOK", SQLDataType.varchar2_5, "");
public final Field wantsOnlineCallback = new Field("wantsOnlineCallback", SQLDataType.varchar2_5, "");
public final Field userAgent = new Field("userAgent", SQLDataType.varchar2_255,"");
public final Field useMac = new Field("useMac", SQLDataType.number_as_integer, "");
public final Field useWin = new Field("useWin", SQLDataType.number_as_integer, "");
public final Field useLin = new Field("useLin", SQLDataType.number_as_integer, "");
private final Field fields[] = {userRef,loginCount,
lastLogin,
emailLostPasswordOK,wantsOnlineCallback,userAgent,
useMac,useWin,useLin};
public static final UserStatTable table = new UserStatTable();
/**
* ModelTable constructor comment.
*/
private UserStatTable() {
super(TABLE_NAME);
addFields(fields);
}
public String getSQLValueList(KeyValue key,KeyFactory keyFactory) {
StringBuffer buffer = new StringBuffer();
buffer.append("(");
buffer.append(keyFactory.nextSEQ()+",");
buffer.append(key.toString()+",");
buffer.append("0,");
buffer.append("NULL,");
buffer.append("'true',");
buffer.append("'false',");
buffer.append("NULL,");
buffer.append("0,");
buffer.append("0,");
buffer.append("0");
buffer.append(")");
return buffer.toString();
}
}
|
skdebray/ASE-2020
|
shared/LynxReg.h
|
#ifndef _LYNX_REG_H_
#define _LYNX_REG_H_
#include <stdint.h>
/* This enum represents all of the registers in x86 for all of the different
architectures. Note that different architectures use different subsets of
these registers and as a result, each of the register groups are named.
There should never be an architecture that uses a subset of one of the
groups in this file. Also, it should be noted that LynxReg is ordered so
that full registers appear first, making it possibly to easily loop over
the full registers*/
typedef enum {
LYNX_FIRST=0,
LYNX_ZMM_FIRST=LYNX_FIRST,
LYNX_ZMM0=LYNX_ZMM_FIRST,
LYNX_ZMM1,
LYNX_ZMM2,
LYNX_ZMM3,
LYNX_ZMM4,
LYNX_ZMM5,
LYNX_ZMM6,
LYNX_ZMM7,
LYNX_ZMM8,
LYNX_ZMM9,
LYNX_ZMM10,
LYNX_ZMM11,
LYNX_ZMM12,
LYNX_ZMM13,
LYNX_ZMM14,
LYNX_ZMM15,
LYNX_ZMM16,
LYNX_ZMM17,
LYNX_ZMM18,
LYNX_ZMM19,
LYNX_ZMM20,
LYNX_ZMM21,
LYNX_ZMM22,
LYNX_ZMM23,
LYNX_ZMM24,
LYNX_ZMM25,
LYNX_ZMM26,
LYNX_ZMM27,
LYNX_ZMM28,
LYNX_ZMM29,
LYNX_ZMM30,
LYNX_ZMM31,
LYNX_ZMM_LAST=LYNX_ZMM31,
LYNX_K_MASK_FIRST,
LYNX_K0=LYNX_K_MASK_FIRST,
LYNX_K1,
LYNX_K2,
LYNX_K3,
LYNX_K4,
LYNX_K5,
LYNX_K6,
LYNX_K7,
LYNX_K_MASK_LAST=LYNX_K7,
LYNX_GR64_FIRST,
LYNX_RIP=LYNX_GR64_FIRST,
LYNX_RAX,
LYNX_RBX,
LYNX_RCX,
LYNX_RDX,
LYNX_RBP,
LYNX_RSI,
LYNX_RDI,
LYNX_RSP,
LYNX_R8,
LYNX_R9,
LYNX_R10,
LYNX_R11,
LYNX_R12,
LYNX_R13,
LYNX_R14,
LYNX_R15,
LYNX_GR64_LAST=LYNX_R15,
LYNX_SEG_FIRST,
LYNX_SEG_CS=LYNX_SEG_FIRST,
LYNX_SEG_DS,
LYNX_SEG_ES,
LYNX_SEG_FS,
LYNX_SEG_GS,
LYNX_SEG_SS,
LYNX_SEG_LAST=LYNX_SEG_SS,
LYNX_SSE_FLG_FIRST,
LYNX_MXCSR=LYNX_SSE_FLG_FIRST,
LYNX_SSE_FLG_LAST=LYNX_MXCSR,
LYNX_FPU_FIRST,
LYNX_ST0=LYNX_FPU_FIRST,
LYNX_ST1,
LYNX_ST2,
LYNX_ST3,
LYNX_ST4,
LYNX_ST5,
LYNX_ST6,
LYNX_ST7,
LYNX_FPU_LAST=LYNX_ST7,
LYNX_FPU_STAT_FIRST,
LYNX_FPSW=LYNX_FPU_STAT_FIRST,
LYNX_FPCW,
LYNX_FPTAG_FULL,
LYNX_FPIP_OFF,
LYNX_FPIP_SEL,
LYNX_FPDP_OFF,
LYNX_FPDP_SEL,
LYNX_FPOPCODE,
LYNX_FPU_STAT_LAST=LYNX_FPOPCODE,
LYNX_DBG_FIRST,
LYNX_DR0=LYNX_DBG_FIRST,
LYNX_DR1,
LYNX_DR2,
LYNX_DR3,
LYNX_DR4,
LYNX_DR5,
LYNX_DR6,
LYNX_DR7,
LYNX_DBG_LAST=LYNX_DR7,
LYNX_CTRL_FIRST,
LYNX_CR0=LYNX_CTRL_FIRST,
LYNX_CR1,
LYNX_CR2,
LYNX_CR3,
LYNX_CR4,
LYNX_CTRL_LAST=LYNX_CR4,
LYNX_FLAGS_FIRST,
LYNX_GFLAGS=LYNX_FLAGS_FIRST,
LYNX_FLAGS_LAST=LYNX_GFLAGS,
LYNX_LAST_FULL=LYNX_GFLAGS,
LYNX_YMM_X86_FIRST,
LYNX_YMM0=LYNX_YMM_X86_FIRST,
LYNX_YMM1,
LYNX_YMM2,
LYNX_YMM3,
LYNX_YMM4,
LYNX_YMM5,
LYNX_YMM6,
LYNX_YMM7,
LYNX_YMM_X86_LAST=LYNX_YMM7,
LYNX_X86_GR32_FIRST,
LYNX_EIP=LYNX_X86_GR32_FIRST,
LYNX_EAX,
LYNX_EBX,
LYNX_ECX,
LYNX_EDX,
LYNX_EBP,
LYNX_ESI,
LYNX_EDI,
LYNX_ESP,
LYNX_X86_GR32_LAST=LYNX_ESP,
LYNX_X64_GR32_FIRST,
LYNX_R8D=LYNX_X64_GR32_FIRST,
LYNX_R9D,
LYNX_R10D,
LYNX_R11D,
LYNX_R12D,
LYNX_R13D,
LYNX_R14D,
LYNX_R15D,
LYNX_X64_GR32_LAST=LYNX_R15D,
LYNX_X86_GR16_FIRST,
LYNX_IP=LYNX_X86_GR16_FIRST,
LYNX_AX,
LYNX_BX,
LYNX_CX,
LYNX_DX,
LYNX_BP,
LYNX_SI,
LYNX_DI,
LYNX_SP,
LYNX_X86_GR16_LAST=LYNX_SP,
LYNX_X64_GR16_FIRST,
LYNX_R8W=LYNX_X64_GR16_FIRST,
LYNX_R9W,
LYNX_R10W,
LYNX_R11W,
LYNX_R12W,
LYNX_R13W,
LYNX_R14W,
LYNX_R15W,
LYNX_X64_GR16_LAST=LYNX_R15W,
LYNX_X86_GR8H_FIRST,
LYNX_AH=LYNX_X86_GR8H_FIRST,
LYNX_BH,
LYNX_CH,
LYNX_DH,
LYNX_X86_GR8H_LAST=LYNX_DH,
LYNX_X86_GR8_FIRST,
LYNX_AL=LYNX_X86_GR8_FIRST,
LYNX_BL,
LYNX_CL,
LYNX_DL,
LYNX_X86_GR8_LAST=LYNX_DL,
LYNX_X64_GR8_FIRST,
LYNX_BPL=LYNX_X64_GR8_FIRST,
LYNX_SIL,
LYNX_DIL,
LYNX_SPL,
LYNX_R8B,
LYNX_R9B,
LYNX_R10B,
LYNX_R11B,
LYNX_R12B,
LYNX_R13B,
LYNX_R14B,
LYNX_R15B,
LYNX_X64_GR8_LAST=LYNX_R15B,
LYNX_YMM_X64_FIRST,
LYNX_YMM8=LYNX_YMM_X64_FIRST,
LYNX_YMM9,
LYNX_YMM10,
LYNX_YMM11,
LYNX_YMM12,
LYNX_YMM13,
LYNX_YMM14,
LYNX_YMM15,
LYNX_YMM_X64_LAST=LYNX_YMM15,
LYNX_YMM_FIRST,
LYNX_YMM16=LYNX_YMM_FIRST,
LYNX_YMM17,
LYNX_YMM18,
LYNX_YMM19,
LYNX_YMM20,
LYNX_YMM21,
LYNX_YMM22,
LYNX_YMM23,
LYNX_YMM24,
LYNX_YMM25,
LYNX_YMM26,
LYNX_YMM27,
LYNX_YMM28,
LYNX_YMM29,
LYNX_YMM30,
LYNX_YMM31,
LYNX_YMM_LAST=LYNX_YMM31,
LYNX_XMM_X86_FIRST,
LYNX_XMM0=LYNX_XMM_X86_FIRST,
LYNX_XMM1,
LYNX_XMM2,
LYNX_XMM3,
LYNX_XMM4,
LYNX_XMM5,
LYNX_XMM6,
LYNX_XMM7,
LYNX_XMM_X86_LAST=LYNX_XMM7,
LYNX_XMM_X64_FIRST,
LYNX_XMM8=LYNX_XMM_X64_FIRST,
LYNX_XMM9,
LYNX_XMM10,
LYNX_XMM11,
LYNX_XMM12,
LYNX_XMM13,
LYNX_XMM14,
LYNX_XMM15,
LYNX_XMM_X64_LAST=LYNX_XMM15,
LYNX_XMM_FIRST,
LYNX_XMM16=LYNX_XMM_FIRST,
LYNX_XMM17,
LYNX_XMM18,
LYNX_XMM19,
LYNX_XMM20,
LYNX_XMM21,
LYNX_XMM22,
LYNX_XMM23,
LYNX_XMM24,
LYNX_XMM25,
LYNX_XMM26,
LYNX_XMM27,
LYNX_XMM28,
LYNX_XMM29,
LYNX_XMM30,
LYNX_XMM31,
LYNX_XMM_LAST=LYNX_XMM31,
LYNX_MMX_FIRST,
LYNX_MM0=LYNX_MMX_FIRST,
LYNX_MM1,
LYNX_MM2,
LYNX_MM3,
LYNX_MM4,
LYNX_MM5,
LYNX_MM6,
LYNX_MM7,
LYNX_MMX_LAST=LYNX_MM7,
LYNX_FPU_STACK_FIRST,
LYNX_FPU_STACK=LYNX_FPU_STACK_FIRST,
LYNX_FPU_STACK_LAST=LYNX_FPU_STACK,
LYNX_LAST_REG=LYNX_FPU_STACK,
LYNX_INVALID,
LYNX_LAST=LYNX_INVALID
} LynxReg;
//Gets a string representation of the given LynxReg
const char *LynxReg2Str(LynxReg lReg);
//Gets the size of the lReg in a 64 bit architecture
uint8_t LynxRegSize(LynxReg lReg);
//Gets the size of the lReg in a 32 bit architecture
uint8_t LynxRegSize32(LynxReg lReg);
//Gets the number of bytes this register is offset from the least significant bit of the fullReg
uint8_t LynxRegOffset(LynxReg lReg);
//Gets the full register for the input register if all registers are considered
LynxReg LynxReg2FullLynxReg(LynxReg lReg);
//Gets the full register for the input register if 32bit registers are considered
LynxReg LynxReg2FullLynxIA32EReg(LynxReg lReg);
//Gets the full register for the input register if 64bit registers are considered (Excluding MIC, which is the ZMM registers)
LynxReg LynxReg2FullLynxIA32Reg(LynxReg lReg);
#endif
|
mullinger/dicexpression
|
src/main/java/ch/ullinger/dicexpression/base/Expression.java
|
<gh_stars>0
package ch.ullinger.dicexpression.base;
import java.util.List;
public interface Expression {
public int evaluate();
public List<Expression> getSubExpressions();
}
|
Kevin-Lee/effectie
|
cats-effect3/src/test/scala-3/effectie/cats/compat/CatsEffectIoCompatForFuture.scala
|
package effectie.cats.compat
import cats.effect.*
import cats.effect.unsafe.IORuntime
import extras.concurrent.testing.ConcurrentSupport
import extras.concurrent.testing.types.ErrorLogger
import java.util.concurrent.ExecutorService
import scala.concurrent.ExecutionContext
/** @author <NAME>
* @since 2021-04-18
*/
final class CatsEffectIoCompatForFuture {
// TODO: Use it for Cats Effect 3
val es: ExecutorService = ConcurrentSupport.newExecutorService(2)
given ec: ExecutionContext = ConcurrentSupport.newExecutionContextWithLogger(es, ErrorLogger.printlnExecutionContextErrorLogger)
// val es: ExecutorService = ConcurrentSupport.newExecutorService(2)
// given ec: ExecutionContext = ConcurrentSupport.newExecutionContextWithLogger(es, println(_))
// given ioRuntime: IORuntime = cats.effect.unsafe.implicits.global
}
|
mladra/packing-assistant
|
app/src/main/java/pl/lodz/p/edu/database/PackAssistantDatabase.java
|
<gh_stars>0
package pl.lodz.p.edu.database;
import android.content.Context;
import java.util.concurrent.Executors;
import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.TypeConverters;
import androidx.sqlite.db.SupportSQLiteDatabase;
import pl.lodz.p.edu.database.converters.ActivityEnumTypeConverter;
import pl.lodz.p.edu.database.converters.DateTypeConverter;
import pl.lodz.p.edu.database.converters.StatusEnumTypeConverter;
import pl.lodz.p.edu.database.converters.WeatherEnumTypeConverter;
import pl.lodz.p.edu.database.dao.definitions.ItemDefinitionsDao;
import pl.lodz.p.edu.database.dao.instances.ItemInstancesDao;
import pl.lodz.p.edu.database.dao.definitions.PackingListDefinitionsDao;
import pl.lodz.p.edu.database.dao.instances.PackingListInstancesDao;
import pl.lodz.p.edu.database.dao.definitions.PackingListSectionDefinitionsDao;
import pl.lodz.p.edu.database.dao.definitions.SectionDefinitionsDao;
import pl.lodz.p.edu.database.dao.instances.PackingListSectionInstancesDao;
import pl.lodz.p.edu.database.dao.instances.SectionInstancesDao;
import pl.lodz.p.edu.database.dao.definitions.SectionItemDefinitionsDao;
import pl.lodz.p.edu.database.dao.instances.SectionItemInstancesDao;
import pl.lodz.p.edu.database.entity.definitions.PackingListDefinition;
import pl.lodz.p.edu.database.entity.definitions.SectionDefinition;
import pl.lodz.p.edu.database.entity.definitions.ItemDefinition;
import pl.lodz.p.edu.database.entity.instances.ItemInstance;
import pl.lodz.p.edu.database.entity.instances.PackingListInstance;
import pl.lodz.p.edu.database.entity.definitions.PackingListSectionDefinition;
import pl.lodz.p.edu.database.entity.definitions.SectionItemDefinition;
import pl.lodz.p.edu.database.entity.instances.PackingListSectionInstance;
import pl.lodz.p.edu.database.entity.instances.SectionInstance;
import pl.lodz.p.edu.database.entity.instances.SectionItemInstance;
@Database(entities = {
ItemDefinition.class,
SectionDefinition.class,
PackingListDefinition.class,
SectionItemDefinition.class,
PackingListSectionDefinition.class,
ItemInstance.class,
SectionInstance.class,
PackingListInstance.class,
SectionItemInstance.class,
PackingListSectionInstance.class}, version = 11, exportSchema = false)
@TypeConverters({DateTypeConverter.class, ActivityEnumTypeConverter.class, StatusEnumTypeConverter.class, WeatherEnumTypeConverter.class})
public abstract class PackAssistantDatabase extends RoomDatabase {
private static final String DB_NAME = "pack-assistant-db";
private static PackAssistantDatabase INSTANCE;
public abstract ItemDefinitionsDao itemDefinitionsDao();
public abstract SectionDefinitionsDao sectionDefinitionsDao();
public abstract PackingListDefinitionsDao packingListDefinitionsDao();
public abstract SectionItemDefinitionsDao sectionItemDefinitionsDao();
public abstract PackingListSectionDefinitionsDao packingListSectionDefinitionsDao();
public abstract PackingListInstancesDao packingListInstancesDao();
public abstract SectionInstancesDao sectionInstancesDao();
public abstract ItemInstancesDao itemInstancesDao();
public abstract PackingListSectionInstancesDao packingListSectionInstancesDao();
public abstract SectionItemInstancesDao sectionItemInstancesDao();
public synchronized static PackAssistantDatabase getInstance(Context context) {
if (INSTANCE == null) {
INSTANCE = buildDatabase(context);
}
return INSTANCE;
}
private static PackAssistantDatabase buildDatabase(final Context context) {
return Room.databaseBuilder(context, PackAssistantDatabase.class, DB_NAME)
.addCallback(new Callback() {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
Executors.newSingleThreadScheduledExecutor().execute(new Runnable() {
@Override
public void run() {
getInstance(context).itemDefinitionsDao().insertAll(ItemDefinition.populateData());
getInstance(context).sectionDefinitionsDao().insertAll(SectionDefinition.populateData());
getInstance(context).packingListDefinitionsDao().insertAll(PackingListDefinition.populateData());
getInstance(context).sectionItemDefinitionsDao().insertAll(SectionItemDefinition.populateData());
}
});
}
})
.fallbackToDestructiveMigration()
.build();
}
}
|
jczaja/Paddle
|
paddle/capi/examples/model_inference/common/common.h
|
<gh_stars>1-10
// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
//
// 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.
#ifndef __CAPI_EXAMPLE_COMMON_H__
#define __CAPI_EXAMPLE_COMMON_H__
#include <stdio.h>
#include <stdlib.h>
#define CHECK(stmt) \
do { \
paddle_error __err__ = stmt; \
if (__err__ != kPD_NO_ERROR) { \
fprintf(stderr, "Invoke paddle error %d in " #stmt "\n", __err__); \
exit(__err__); \
} \
} while (0)
void* read_config(const char* filename, long* size) {
FILE* file = fopen(filename, "r");
if (file == NULL) {
fprintf(stderr, "Open %s error\n", filename);
return NULL;
}
fseek(file, 0L, SEEK_END);
*size = ftell(file);
fseek(file, 0L, SEEK_SET);
void* buf = malloc(*size);
fread(buf, 1, *size, file);
fclose(file);
return buf;
}
#endif
|
saydulk/parliamentary-questions
|
redeploy/pq_fixer.rb
|
<reponame>saydulk/parliamentary-questions<gh_stars>0
module Redeploy
class PqFixer
def initialize(pqid)
@pq = Pq.find(pqid)
@log_messages = []
end
def fix!
begin
log("fixing PQID")
if %w{ unassigned no_response rejected }.include?(@pq.state)
# for unassigned and no response
# create an "Unknown" action officer, with deleted false and assign to question
# create ActionOfficersPq object with the question id and action officer id
# set ActionOfficersPq response to 'accepted'
fix_uncommissioned
end
if %w{ pod_query with_pod}.include?(@pq.state)
# for pod_query, pod_clearance,
# set pod_clearance to answer submitted date
fix_pod_clearance
end
if @pq.state == 'pod_cleared'
# for pod_cleared
# set sent_to_answering_minister to answer_submitted
# set sent_to_policy_miniser to answer_submitted if policy_minister not nil
fix_minister_submitted
end
if @pq.state == 'with_minister'
# for with minister
# when there is a policy minister
# set cleared_by_policy_minister to answer_submitted
fix_cleared_by_minister
end
@pq.update_state!
rescue => err
puts "ERROR: #{err.class} #{err.message}"
ensure
print_log_messages
end
end
private
def log(message)
@log_messages << "#{@pq.id} UIN: #{@pq.uin} #{message}"
end
def print_log_messages
@log_messages.each { |m| puts m }
end
def fix_pod_clearance
@pq.update!(pod_clearance: @pq.answer_submitted)
log("pod_clearance set to #{@pq.pod_clearance}")
@pq.update_state!
end
def fix_minister_submitted
@pq.update!(sent_to_answering_minister: @pq.answer_submitted)
log("sent_to_answering_minister set to #{@pq.answer_submitted}")
if @pq.policy_minister
@pq.update!(sent_to_policy_minister: @pq.answer_submitted)
log("sent_to_policy_minister set to #{@pq.answer_submitted}")
end
@pq.update_state!
end
def fix_cleared_by_minister
@pq.update!(cleared_by_answering_minister: @pq.answer_submitted)
log("cleared_by_answering_minister set to #{@pq.answer_submitted}")
if @pq.policy_minister
@pq.update!(cleared_by_policy_minister: @pq.answer_submitted)
log("cleared_by_policy_minister set to #{@pq.answer_submitted}")
end
@pq.update_state!
end
def fix_uncommissioned
ao_pq = ActionOfficersPq.create(
pq_id: @pq.id,
action_officer_id: ao_placeholder.id,
)
ao_pq.accept
log(
"assigned to and accepted by ActionOfficer with id: " +
"#{ao_placeholder.id}, through ActionOfficersPq with id: #{ao_pq.id} "
)
@pq.update_state!
end
def ao_placeholder
@ao_placeholder ||=
ActionOfficer.find_or_create_by(
deputy_director: dd_placeholder,
name: 'AO not known placeholder',
email: '<EMAIL>',
press_desk: pd_placeholder,
deleted: true
)
end
def dd_placeholder
@dd_placeholder ||=
DeputyDirector.find_or_create_by(
division: div_placeholder,
email: '<EMAIL>',
name: 'DD for AO not known placeholder',
deleted: true
)
end
def pd_placeholder
@pd_placeholder ||=
PressDesk.find_or_create_by(
name: 'Unknown'
)
end
def dir_placeholder
@dir_placeholder ||=
Directorate.find_or_create_by(
name: 'Unknown'
)
end
def div_placeholder
@div_placholder ||=
Division.find_or_create_by(
name: 'Unknown',
directorate: dir_placeholder
)
end
end
end
|
coreboot/chrome-ec
|
chip/stm32/config-stm32g473xc.h
|
/* Copyright 2021 The Chromium OS Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/*
* Memory mapping for STM32G473xc. The STM32G473xc is a category 1 device within
* the STM32G4 chip family. Category 1 devices have either 128, 256, or 512 kB
* of internal flash. 'xc' indicates 256 kB of internal flash.
*
* STM32G473xc can be configured via option bytes as either a single bank or
* dual bank device. Dual bank is the default selection.
* CONFIG_FLASH_BANK_SIZE is consistent with page size as defined in RM0440 TRM
* for the STM32G4 chip family. In dual bank mode, the flash is organized in 2
* kB pages, with 64 pages per bank for this variant.
*
* The minimum write size for STM32G4 is 8 bytes. Cros-EC does not support
* PSTATE in single bank memories with a write size > 4 bytes.
*
* TODO(b/181874494): Verify that dual bank mode should be used, or add support
* for enabling single bank mode on STM32G473xc.
*/
#define CONFIG_FLASH_SIZE_BYTES (256 * 1024)
#define CONFIG_FLASH_WRITE_SIZE 0x0004
#define CONFIG_FLASH_BANK_SIZE (2 * 1024)
#define CONFIG_FLASH_ERASE_SIZE CONFIG_FLASH_BANK_SIZE
/* Dual-bank (DBANK) mode is enabled by default for this chip */
#define STM32_FLASH_DBANK_MODE
/* Erasing 128K can take up to 2s, need to defer erase. */
#define CONFIG_FLASH_DEFERRED_ERASE
/* No page mode on STM32G4, so no benefit to larger write sizes */
#define CONFIG_FLASH_WRITE_IDEAL_SIZE CONFIG_FLASH_WRITE_SIZE
/*
* STM32G473xc is a category 3 SRAM device featuring 128 Kbytes of embedded
* SRAM. This SRAM is split into three blocks:
* • 80 Kbytes mapped at address 0x2000 0000 (SRAM1).
* • 16 Kbytes mapped at address 0x2001 4000 (SRAM2).
* • 32 Kbytes mapped at address 0x1000 0000 (CCM SRAM). It is also aliased
* at 0x2001 8000 address to be accessed by all bus controllers.
*/
#define CONFIG_RAM_BASE 0x20000000
#define CONFIG_RAM_SIZE 0x00020000
#undef I2C_PORT_COUNT
#define I2C_PORT_COUNT 4
/* Number of DMA channels supported (6 channels each for DMA1 and DMA2) */
#define DMAC_COUNT 12
/* Use PSTATE embedded in the RO image, not in its own erase block */
#define CONFIG_FLASH_PSTATE
#undef CONFIG_FLASH_PSTATE_BANK
/* Number of IRQ vectors on the NVIC */
#define CONFIG_IRQ_COUNT 101
/* USB packet ram config */
#define CONFIG_USB_RAM_BASE 0x40006000
#define CONFIG_USB_RAM_SIZE 1024
#define CONFIG_USB_RAM_ACCESS_TYPE uint16_t
#define CONFIG_USB_RAM_ACCESS_SIZE 2
|
asgeir/old-school-projects
|
computer_graphics/tests/cubemap/cubemapapp.cpp
|
<gh_stars>0
#include "cubemapapp.h"
namespace {
const std::string kReflectiveVertexShader = R"(
#version 150
in vec4 ge_position;
in vec3 ge_normal;
uniform mat4 ge_modelViewProjection;
uniform mat3 ge_normalMatrix;
out vec3 normal;
void main()
{
gl_Position = ge_modelViewProjection * ge_position;
normal = normalize(ge_normalMatrix * ge_normal);
}
)";
const std::string kReflectiveFragmentShader = R"(
#version 150
#ge_include "standard/lighting.fs"
//in vec3 normal;
uniform samplerCube envMap;
uniform mat3 ge_viewMatrixLinearInverse;
out vec4 ge_fragmentColor;
void main()
{
vec3 reflected = normalize(reflect(vec3(0.0, 0.0, -1.0), normal));
reflected = ge_viewMatrixLinearInverse * reflected;
ge_fragmentColor = texture(envMap, reflected) + lighting(vec4(0.2));
}
)";
const std::string kRefractiveFragmentShader = R"(
#version 150
in vec3 normal;
uniform float outsideRefractiveIndex = 1.0;
uniform float objectRefractiveIndex = 1.5;
uniform samplerCube envMap;
uniform mat3 ge_viewMatrixLinearInverse;
out vec4 ge_fragmentColor;
void main()
{
vec3 reflected = normalize(refract(vec3(0.0, 0.0, -1.0), normal, outsideRefractiveIndex / objectRefractiveIndex));
reflected = ge_viewMatrixLinearInverse * reflected;
ge_fragmentColor = texture(envMap, reflected);
}
)";
}
using namespace ge2;
CubemapApplication::CubemapApplication(int argc, char *argv[])
{
geRenderer->setTitle("GL Engine 2 - Cubemap Test");
geResourceMgr->setAssetDirectory("../assets");
if (argc >= 2) {
geResourceMgr->setAssetDirectory(argv[1]);
}
Shader *shader = geResourceMgr->loadShaderFromFiles(
"default_shader",
"standard/default.vs",
"ge2test/colored_fragment_light_shadow.fs",
{ });
if (shader->hasError()) {
std::cerr << "Shader compilation error" << std::endl;
std::cerr << shader->errorString() << std::endl;
}
Material *greyMaterial = geResourceMgr->createMaterial("grey_material", shader);
greyMaterial->setDiffuseColor(glm::vec3{0.8f});
Material *redMaterial = geResourceMgr->createMaterial("red_material", shader);
redMaterial->setDiffuseColor(glm::vec3{1.0f, 0.0f, 0.0f});
redMaterial->setSpecularColor(glm::vec3{0.5f, 0.0f, 0.0f});
redMaterial->setShininess(50.0f);
Material *greenMaterial = geResourceMgr->createMaterial("green_material", shader);
greenMaterial->setDiffuseColor(glm::vec3{0.0f, 1.0f, 0.0f});
greenMaterial->setSpecularColor(glm::vec3{0.0f, 0.5f, 0.0f});
greenMaterial->setShininess(50.0f);
Material *blueMaterial = geResourceMgr->createMaterial("blue_material", shader);
blueMaterial->setDiffuseColor(glm::vec3{0.0f, 0.0f, 1.0f});
blueMaterial->setSpecularColor(glm::vec3{0.0f, 0.0f, 0.5f});
blueMaterial->setShininess(50.0f);
shader = geResourceMgr->loadShaderFromStrings(
"reflective_shader",
kReflectiveVertexShader,
kReflectiveFragmentShader,
{ "envMap" });
if (shader->hasError()) {
std::cerr << "Shader compilation error" << std::endl;
std::cerr << shader->errorString() << std::endl;
}
m_reflectiveMaterial = geResourceMgr->createMaterial("reflective_material", shader);
m_reflectiveMaterial->setSpecularColor(glm::vec3{1.0f});
m_reflectiveMaterial->setShininess(25.0f);
shader = geResourceMgr->loadShaderFromStrings(
"refractive_shader",
kReflectiveVertexShader,
kRefractiveFragmentShader,
{ "envMap", "objectRefractiveIndex", "outsideRefractiveIndex" });
if (shader->hasError()) {
std::cerr << "Shader compilation error" << std::endl;
std::cerr << shader->errorString() << std::endl;
}
m_refractiveMaterial = geResourceMgr->createMaterial("refractive_material", shader);
m_environmentMap = new CubeFramebuffer;
m_environmentMap->construct(512, true, { FragmentBuffer::Color });
m_reflectiveMaterial->setUniform("envMap", m_environmentMap->colorBuffer(FragmentBuffer::Color));
m_refractiveMaterial->setUniform("envMap", m_environmentMap->colorBuffer(FragmentBuffer::Color));
m_camera = new DebugCamera;
m_scene = new Node;
// grey sphere
Mesh *sphereMesh = geResourceMgr->createSphere("sphere", 0.5f, 3);
sphereMesh->setMaterial(greyMaterial);
sphereMesh->construct();
Node *sphereNode = new Node;
sphereNode->setMeshList({ sphereMesh });
m_scene->addChild(sphereNode);
// red sphere
sphereMesh = geResourceMgr->createSphere("red_sphere", 0.5f, 3);
sphereMesh->setMaterial(redMaterial);
sphereMesh->construct();
sphereNode = new Node;
sphereNode->setMeshList({ sphereMesh });
sphereNode->setPosition(glm::vec3{0.0f, 0.0f, -4.0f});
m_scene->addChild(sphereNode);
// green sphere
sphereMesh = geResourceMgr->createSphere("green_sphere", 0.5f, 3);
sphereMesh->setMaterial(greenMaterial);
sphereMesh->construct();
sphereNode = new Node;
sphereNode->setMeshList({ sphereMesh });
sphereNode->setPosition(glm::rotate(glm::quat{}, degToRad(132), kUnitVectorY) * glm::vec3{0.0f, 0.0f, -4.0f});
m_scene->addChild(sphereNode);
// blue sphere
sphereMesh = geResourceMgr->createSphere("blue_sphere", 0.5f, 3);
sphereMesh->setMaterial(blueMaterial);
sphereMesh->construct();
sphereNode = new Node;
sphereNode->setMeshList({ sphereMesh });
sphereNode->setPosition(glm::rotate(glm::quat{}, degToRad(-132), kUnitVectorY) * glm::vec3{0.0f, 0.0f, -4.0f});
m_scene->addChild(sphereNode);
// ground
Mesh *planeMesh = geResourceMgr->createQuad("ground", 50, 50);
planeMesh->setMaterial(greyMaterial);
planeMesh->construct();
Node *groundNode = new Node;
groundNode->setMeshList({ planeMesh });
groundNode->setPosition(glm::vec3{0.0f, -1.0f, 0.0f});
groundNode->setRotation(glm::rotate(glm::quat{}, degToRad(-90), kUnitVectorX));
m_scene->addChild(groundNode);
// reflective/refractive sphere
m_reflectiveRefractiveSphere = geResourceMgr->createSphere("reflective/refractive_sphere", 0.5f, 3);
m_reflectiveRefractiveSphere->setMaterial(m_reflectiveMaterial);
m_reflectiveRefractiveSphere->construct();
m_rotationNode = new Node;
m_scene->addChild(m_rotationNode);
m_reflectiveNode = new Node;
m_reflectiveNode->setPosition(glm::vec3{2.0f, 0.0f, 0.0f});
m_reflectiveNode->setMeshList({ m_reflectiveRefractiveSphere });
m_rotationNode->addChild(m_reflectiveNode);
// light
Node *lightNode = new Node;
DirectionalLight *light = new DirectionalLight;
light->setAmbientColor(glm::vec3{0.15f});
light->setColor(glm::vec3{1.0f});
light->setDirection(glm::vec3{-1.0f});
light->setCastsShadows(true);
light->setDepth(glm::vec2{-30.0f, 30.0f});
light->setHorizontal(glm::vec2{-35.0f, 35.0f});
light->setVertical(glm::vec2{-35.0f, 35.0f});
lightNode->setLight(light);
lightNode->setPosition(glm::vec3{4.0f});
m_scene->addChild(lightNode);
// compositor
m_antiAliasingEffect = new AntiAliasingEffect;
m_bloomEffect = new BloomEffect;
m_tonemapEffect = new TonemapEffect{1.0f, 1.0f, glm::vec3{1.0f}};
m_compositorEffects.push_back(m_antiAliasingEffect);
m_compositorEffects.push_back(m_bloomEffect);
m_compositorEffects.push_back(m_tonemapEffect);
m_compositor = new Compositor;
m_compositor->construct(geRenderer->width(), geRenderer->height());
}
CubemapApplication::~CubemapApplication()
{
delete m_compositor;
delete m_antiAliasingEffect;
delete m_bloomEffect;
delete m_tonemapEffect;
delete m_scene;
delete m_camera;
}
void CubemapApplication::handleEvent(const SDL_Event &event)
{
m_camera->handleEvent(event);
if (event.type == SDL_KEYUP) {
const SDL_KeyboardEvent *evt = (const SDL_KeyboardEvent *)(&event);
if (evt->keysym.scancode == SDL_SCANCODE_ESCAPE) {
SDL_Event quitEvent = { SDL_QUIT };
SDL_PushEvent(&quitEvent);
} else if (evt->keysym.scancode == SDL_SCANCODE_1) {
m_reflectiveRefractiveSphere->setMaterial(m_refractiveMaterial);
} else if (evt->keysym.scancode == SDL_SCANCODE_2) {
m_reflectiveRefractiveSphere->setMaterial(m_reflectiveMaterial);
}
}
}
void CubemapApplication::update()
{
m_camera->update();
m_rotationNode->setRotation(glm::rotate(m_rotationNode->rotation(), Time::deltaTime() * GE_PI / 8.0f, kUnitVectorY));
LightInfoList lights;
RenderableList renderables;
NodeTreeVisitor treeVisitor;
treeVisitor.visitNodeTree(m_scene, {
[this, &renderables, &lights] (Node *node, const glm::mat4 &modelMatrix) {
if (node->meshCount()) {
renderables.push_back({ modelMatrix, node, node != this->m_reflectiveNode });
}
if (node->light()) {
lights.push_back({ modelMatrix, node->light() });
}
}
});
m_environmentMap->setPosition(m_reflectiveNode->worldPosition());
m_environmentMap->update(
[&renderables, &lights] (PerspectiveCamera *faceCamera) {
geRenderer->setActiveCameraAndLights(faceCamera, lights);
geRenderer->clear();
geRenderer->render(renderables);
}
);
geRenderer->setActiveCameraAndLights(m_camera->camera(), lights);
geRenderer->updateShadowMaps(renderables);
m_compositor->bindInputFramebuffer();
geRenderer->clear();
geRenderer->render(renderables);
m_compositor->unbindInputFramebuffer();
m_compositor->compose(m_compositorEffects);
}
|
TheEggi/esphomeyaml
|
esphome/components/a4988/a4988.h
|
<reponame>TheEggi/esphomeyaml
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/esphal.h"
#include "esphome/components/stepper/stepper.h"
namespace esphome {
namespace a4988 {
class A4988 : public stepper::Stepper, public Component {
public:
void set_step_pin(GPIOPin *step_pin) { step_pin_ = step_pin; }
void set_dir_pin(GPIOPin *dir_pin) { dir_pin_ = dir_pin; }
void set_sleep_pin(GPIOPin *sleep_pin) { this->sleep_pin_ = sleep_pin; }
void setup() override;
void dump_config() override;
void loop() override;
float get_setup_priority() const override { return setup_priority::HARDWARE; }
protected:
GPIOPin *step_pin_;
GPIOPin *dir_pin_;
GPIOPin *sleep_pin_{nullptr};
HighFrequencyLoopRequester high_freq_;
};
} // namespace a4988
} // namespace esphome
|
maurizioabba/rose
|
tests/roseTests/roseHPCToolkitTests/data/02/struct_ls/CPP-smg_residual.c
|
/*BHEADER**********************************************************************
* (c) 1997 The Regents of the University of California
*
* See the file COPYRIGHT_and_DISCLAIMER for a complete copyright
* notice, contact person, and disclaimer.
*
* $Revision: 1.1 $
*********************************************************************EHEADER*/
/******************************************************************************
*
* Routine for computing residuals in the SMG code
*
*****************************************************************************/
#include "headers.h"
/*--------------------------------------------------------------------------
* hypre_SMGResidualData data structure
*--------------------------------------------------------------------------*/
typedef struct
{
hypre_Index base_index;
hypre_Index base_stride;
hypre_StructMatrix *A;
hypre_StructVector *x;
hypre_StructVector *b;
hypre_StructVector *r;
hypre_BoxArray *base_points;
hypre_ComputePkg *compute_pkg;
int time_index;
int flops;
} hypre_SMGResidualData;
/*--------------------------------------------------------------------------
* hypre_SMGResidualCreate
*--------------------------------------------------------------------------*/
void *
hypre_SMGResidualCreate( )
{
hypre_SMGResidualData *residual_data;
residual_data = hypre_CTAlloc(hypre_SMGResidualData, 1);
(residual_data -> time_index) = hypre_InitializeTiming("SMGResidual");
/* set defaults */
hypre_SetIndex((residual_data -> base_index), 0, 0, 0);
hypre_SetIndex((residual_data -> base_stride), 1, 1, 1);
return (void *) residual_data;
}
/*--------------------------------------------------------------------------
* hypre_SMGResidualSetup
*--------------------------------------------------------------------------*/
int
hypre_SMGResidualSetup( void *residual_vdata,
hypre_StructMatrix *A,
hypre_StructVector *x,
hypre_StructVector *b,
hypre_StructVector *r )
{
int ierr = 0;
hypre_SMGResidualData *residual_data = (hypre_SMGResidualData *)residual_vdata;
hypre_IndexRef base_index = (residual_data -> base_index);
hypre_IndexRef base_stride = (residual_data -> base_stride);
hypre_Index unit_stride;
hypre_StructGrid *grid;
hypre_StructStencil *stencil;
hypre_BoxArrayArray *send_boxes;
hypre_BoxArrayArray *recv_boxes;
int **send_processes;
int **recv_processes;
hypre_BoxArrayArray *indt_boxes;
hypre_BoxArrayArray *dept_boxes;
hypre_BoxArray *base_points;
hypre_ComputePkg *compute_pkg;
/*----------------------------------------------------------
* Set up base points and the compute package
*----------------------------------------------------------*/
grid = hypre_StructMatrixGrid(A);
stencil = hypre_StructMatrixStencil(A);
hypre_SetIndex(unit_stride, 1, 1, 1);
base_points = hypre_BoxArrayDuplicate(hypre_StructGridBoxes(grid));
hypre_ProjectBoxArray(base_points, base_index, base_stride);
hypre_CreateComputeInfo(grid, stencil,
&send_boxes, &recv_boxes,
&send_processes, &recv_processes,
&indt_boxes, &dept_boxes);
hypre_ProjectBoxArrayArray(indt_boxes, base_index, base_stride);
hypre_ProjectBoxArrayArray(dept_boxes, base_index, base_stride);
hypre_ComputePkgCreate(send_boxes, recv_boxes,
unit_stride, unit_stride,
send_processes, recv_processes,
indt_boxes, dept_boxes,
base_stride, grid,
hypre_StructVectorDataSpace(x), 1,
&compute_pkg);
/*----------------------------------------------------------
* Set up the residual data structure
*----------------------------------------------------------*/
(residual_data -> A) = hypre_StructMatrixRef(A);
(residual_data -> x) = hypre_StructVectorRef(x);
(residual_data -> b) = hypre_StructVectorRef(b);
(residual_data -> r) = hypre_StructVectorRef(r);
(residual_data -> base_points) = base_points;
(residual_data -> compute_pkg) = compute_pkg;
/*-----------------------------------------------------
* Compute flops
*-----------------------------------------------------*/
(residual_data -> flops) =
(hypre_StructMatrixGlobalSize(A) + hypre_StructVectorGlobalSize(x)) /
(hypre_IndexX(base_stride) *
hypre_IndexY(base_stride) *
hypre_IndexZ(base_stride) );
return ierr;
}
/*--------------------------------------------------------------------------
* hypre_SMGResidual
*--------------------------------------------------------------------------*/
int
hypre_SMGResidual (void *residual_vdata,
hypre_StructMatrix * A,
hypre_StructVector * x,
hypre_StructVector * b, hypre_StructVector * r)
{
int ierr = 0;
hypre_SMGResidualData *residual_data = (hypre_SMGResidualData *)residual_vdata;
hypre_IndexRef base_stride = (residual_data->base_stride);
hypre_BoxArray *base_points = (residual_data->base_points);
hypre_ComputePkg *compute_pkg = (residual_data->compute_pkg);
hypre_CommHandle *comm_handle;
hypre_BoxArrayArray *compute_box_aa;
hypre_BoxArray *compute_box_a;
hypre_Box *compute_box;
hypre_Box *A_data_box;
hypre_Box *x_data_box;
hypre_Box *b_data_box;
hypre_Box *r_data_box;
int Ai;
int xi;
int bi;
int ri;
double *Ap;
double *xp;
double *bp;
double *rp;
hypre_Index loop_size;
hypre_IndexRef start;
hypre_StructStencil *stencil;
hypre_Index *stencil_shape;
int stencil_size;
int compute_i, i, j, si;
int loopi, loopj, loopk;
hypre_BeginTiming (residual_data->time_index);
/*-----------------------------------------------------------------------
* Compute residual r = b - Ax
*-----------------------------------------------------------------------*/
stencil = ((A)->stencil);
stencil_shape = ((stencil)->shape);
stencil_size = ((stencil)->size);
for (compute_i = 0; compute_i < 2; compute_i++)
{
switch (compute_i)
{
case 0:
{
xp = ((x)->data);
hypre_InitializeIndtComputations (compute_pkg, xp, &comm_handle);
compute_box_aa = (compute_pkg->indt_boxes);
/*----------------------------------------
* Copy b into r
*----------------------------------------*/
compute_box_a = base_points;
for (i = 0; i < ((compute_box_a)->size); i++)
{
compute_box = &((compute_box_a)->boxes[(i)]);
start = ((compute_box)->imin);
b_data_box = &((((b)->data_space))->boxes[(i)]);
r_data_box = &((((r)->data_space))->boxes[(i)]);
bp = (((b)->data) + ((b)->data_indices)[i]);
rp = (((r)->data) + ((r)->data_indices)[i]);
hypre_BoxGetStrideSize (compute_box, base_stride, loop_size);
{
int hypre__i1start =
(((start[0]) - ((((b_data_box)->imin)[0]))) +
(((start[1]) - ((((b_data_box)->imin)[1]))) +
(((start[2]) -
((((b_data_box)->imin)[2]))) * (((0) <
((((((b_data_box)->
imax)[1])) -
((((b_data_box)->
imin)[1])) +
1)))
? ((((((b_data_box)->
imax)[1])) -
((((b_data_box)->
imin)[1])) +
1)) : (0)))) *
(((0) <
((((((b_data_box)->imax)[0])) -
((((b_data_box)->imin)[0])) +
1))) ? ((((((b_data_box)->imax)[0])) -
((((b_data_box)->imin)[0])) + 1)) : (0)));
int hypre__i2start =
(((start[0]) - ((((r_data_box)->imin)[0]))) +
(((start[1]) - ((((r_data_box)->imin)[1]))) +
(((start[2]) -
((((r_data_box)->imin)[2]))) * (((0) <
((((((r_data_box)->
imax)[1])) -
((((r_data_box)->
imin)[1])) +
1)))
? ((((((r_data_box)->
imax)[1])) -
((((r_data_box)->
imin)[1])) +
1)) : (0)))) *
(((0) <
((((((r_data_box)->imax)[0])) -
((((r_data_box)->imin)[0])) +
1))) ? ((((((r_data_box)->imax)[0])) -
((((r_data_box)->imin)[0])) + 1)) : (0)));
int hypre__sx1 = ((base_stride[0]));
int hypre__sy1 =
((base_stride[1]) *
(((0) <
((((((b_data_box)->imax)[0])) -
((((b_data_box)->imin)[0])) +
1))) ? ((((((b_data_box)->imax)[0])) -
((((b_data_box)->imin)[0])) + 1)) : (0)));
int hypre__sz1 =
((base_stride[2]) *
(((0) <
((((((b_data_box)->imax)[0])) -
((((b_data_box)->imin)[0])) +
1))) ? ((((((b_data_box)->imax)[0])) -
((((b_data_box)->imin)[0])) +
1)) : (0)) * (((0) <
((((((b_data_box)->
imax)[1])) -
((((b_data_box)->
imin)[1])) +
1)))
? ((((((b_data_box)->
imax)[1])) -
((((b_data_box)->
imin)[1])) +
1)) : (0)));
int hypre__sx2 = ((base_stride[0]));
int hypre__sy2 =
((base_stride[1]) *
(((0) <
((((((r_data_box)->imax)[0])) -
((((r_data_box)->imin)[0])) +
1))) ? ((((((r_data_box)->imax)[0])) -
((((r_data_box)->imin)[0])) + 1)) : (0)));
int hypre__sz2 =
((base_stride[2]) *
(((0) <
((((((r_data_box)->imax)[0])) -
((((r_data_box)->imin)[0])) +
1))) ? ((((((r_data_box)->imax)[0])) -
((((r_data_box)->imin)[0])) +
1)) : (0)) * (((0) <
((((((r_data_box)->
imax)[1])) -
((((r_data_box)->
imin)[1])) +
1)))
? ((((((r_data_box)->
imax)[1])) -
((((r_data_box)->
imin)[1])) +
1)) : (0)));
int hypre__nx = (loop_size[0]);
int hypre__ny = (loop_size[1]);
int hypre__nz = (loop_size[2]);
int hypre__mx = hypre__nx;
int hypre__my = hypre__ny;
int hypre__mz = hypre__nz;
int hypre__dir, hypre__max;
int hypre__div, hypre__mod;
int hypre__block, hypre__num_blocks;
hypre__dir = 0;
hypre__max = hypre__nx;
if (hypre__ny > hypre__max)
{
hypre__dir = 1;
hypre__max = hypre__ny;
}
if (hypre__nz > hypre__max)
{
hypre__dir = 2;
hypre__max = hypre__nz;
}
hypre__num_blocks = 1;
if (hypre__max < hypre__num_blocks)
{
hypre__num_blocks = hypre__max;
}
if (hypre__num_blocks > 0)
{
hypre__div = hypre__max / hypre__num_blocks;
hypre__mod = hypre__max % hypre__num_blocks;
};;
/* # 236 "smg_residual.c" */
for (hypre__block = 0; hypre__block < hypre__num_blocks;
hypre__block++)
{
loopi = 0;
loopj = 0;
loopk = 0;
hypre__nx = hypre__mx;
hypre__ny = hypre__my;
hypre__nz = hypre__mz;
if (hypre__num_blocks > 1)
{
if (hypre__dir == 0)
{
loopi =
hypre__block * hypre__div +
(((hypre__mod) <
(hypre__block)) ? (hypre__mod)
: (hypre__block));
hypre__nx =
hypre__div +
((hypre__mod > hypre__block) ? 1 : 0);
}
else if (hypre__dir == 1)
{
loopj =
hypre__block * hypre__div +
(((hypre__mod) <
(hypre__block)) ? (hypre__mod)
: (hypre__block));
hypre__ny =
hypre__div +
((hypre__mod > hypre__block) ? 1 : 0);
}
else if (hypre__dir == 2)
{
loopk =
hypre__block * hypre__div +
(((hypre__mod) <
(hypre__block)) ? (hypre__mod)
: (hypre__block));
hypre__nz =
hypre__div +
((hypre__mod > hypre__block) ? 1 : 0);
}
};
bi =
hypre__i1start + loopi * hypre__sx1 +
loopj * hypre__sy1 + loopk * hypre__sz1;
ri =
hypre__i2start + loopi * hypre__sx2 +
loopj * hypre__sy2 + loopk * hypre__sz2;
for (loopk = 0; loopk < hypre__nz; loopk++)
{
for (loopj = 0; loopj < hypre__ny; loopj++)
{
for (loopi = 0; loopi < hypre__nx; loopi++)
{
{
rp[ri] = bp[bi];
}
bi += hypre__sx1;
ri += hypre__sx2;
}
bi += hypre__sy1 - hypre__nx * hypre__sx1;
ri += hypre__sy2 - hypre__nx * hypre__sx2;
}
bi += hypre__sz1 - hypre__ny * hypre__sy1;
ri += hypre__sz2 - hypre__ny * hypre__sy2;
}
}
};
}
}
break;
case 1:
{
hypre_FinalizeIndtComputations (comm_handle);
compute_box_aa = (compute_pkg->dept_boxes);
}
break;
}
/*--------------------------------------------------------------------
* Compute r -= A*x
*--------------------------------------------------------------------*/
for (i = 0; i < ((compute_box_aa)->size); i++)
{
compute_box_a = ((compute_box_aa)->box_arrays[(i)]);
A_data_box = &((((A)->data_space))->boxes[(i)]);
x_data_box = &((((x)->data_space))->boxes[(i)]);
r_data_box = &((((r)->data_space))->boxes[(i)]);
rp = (((r)->data) + ((r)->data_indices)[i]);
for (j = 0; j < ((compute_box_a)->size); j++)
{
compute_box = &((compute_box_a)->boxes[(j)]);
start = ((compute_box)->imin);
for (si = 0; si < stencil_size; si++)
{
Ap = (((A)->data) + ((A)->data_indices)[i][si]);
xp = (((x)->data) + ((x)->data_indices)[i]) +
((stencil_shape[si][0]) +
((stencil_shape[si][1]) +
((stencil_shape[si][2]) *
(((0) <
((((((x_data_box)->imax)[1])) -
((((x_data_box)->imin)[1])) +
1))) ? ((((((x_data_box)->imax)[1])) -
((((x_data_box)->imin)[1])) +
1)) : (0)))) * (((0) <
((((((x_data_box)->
imax)[0])) -
((((x_data_box)->
imin)[0])) +
1)))
? ((((((x_data_box)->
imax)[0])) -
((((x_data_box)->
imin)[0])) +
1)) : (0)));
hypre_BoxGetStrideSize (compute_box, base_stride,
loop_size);
{
int hypre__i1start =
(((start[0]) - ((((A_data_box)->imin)[0]))) +
(((start[1]) - ((((A_data_box)->imin)[1]))) +
(((start[2]) -
((((A_data_box)->imin)[2]))) * (((0) <
((((((A_data_box)->
imax)[1])) -
((((A_data_box)->
imin)[1])) +
1)))
? ((((((A_data_box)->imax)[1])) - ((((A_data_box)->imin)[1])) + 1)) : (0)))) * (((0) < ((((((A_data_box)->imax)[0])) - ((((A_data_box)->imin)[0])) + 1))) ? ((((((A_data_box)->imax)[0])) - ((((A_data_box)->imin)[0])) + 1)) : (0)));
int hypre__i2start =
(((start[0]) - ((((x_data_box)->imin)[0]))) +
(((start[1]) - ((((x_data_box)->imin)[1]))) +
(((start[2]) -
((((x_data_box)->imin)[2]))) * (((0) <
((((((x_data_box)->
imax)[1])) -
((((x_data_box)->
imin)[1])) +
1)))
? ((((((x_data_box)->imax)[1])) - ((((x_data_box)->imin)[1])) + 1)) : (0)))) * (((0) < ((((((x_data_box)->imax)[0])) - ((((x_data_box)->imin)[0])) + 1))) ? ((((((x_data_box)->imax)[0])) - ((((x_data_box)->imin)[0])) + 1)) : (0)));
int hypre__i3start =
(((start[0]) - ((((r_data_box)->imin)[0]))) +
(((start[1]) - ((((r_data_box)->imin)[1]))) +
(((start[2]) -
((((r_data_box)->imin)[2]))) * (((0) <
((((((r_data_box)->
imax)[1])) -
((((r_data_box)->
imin)[1])) +
1)))
? ((((((r_data_box)->imax)[1])) - ((((r_data_box)->imin)[1])) + 1)) : (0)))) * (((0) < ((((((r_data_box)->imax)[0])) - ((((r_data_box)->imin)[0])) + 1))) ? ((((((r_data_box)->imax)[0])) - ((((r_data_box)->imin)[0])) + 1)) : (0)));
int hypre__sx1 = ((base_stride[0]));
int hypre__sy1 =
((base_stride[1]) *
(((0) <
((((((A_data_box)->imax)[0])) -
((((A_data_box)->imin)[0])) +
1))) ? ((((((A_data_box)->imax)[0])) -
((((A_data_box)->imin)[0])) + 1)) : (0)));
int hypre__sz1 =
((base_stride[2]) *
(((0) <
((((((A_data_box)->imax)[0])) -
((((A_data_box)->imin)[0])) +
1))) ? ((((((A_data_box)->imax)[0])) -
((((A_data_box)->imin)[0])) +
1)) : (0)) * (((0) <
((((((A_data_box)->
imax)[1])) -
((((A_data_box)->
imin)[1])) +
1)))
? ((((((A_data_box)->
imax)[1])) -
((((A_data_box)->
imin)[1])) +
1)) : (0)));
int hypre__sx2 = ((base_stride[0]));
int hypre__sy2 =
((base_stride[1]) *
(((0) <
((((((x_data_box)->imax)[0])) -
((((x_data_box)->imin)[0])) +
1))) ? ((((((x_data_box)->imax)[0])) -
((((x_data_box)->imin)[0])) + 1)) : (0)));
int hypre__sz2 =
((base_stride[2]) *
(((0) <
((((((x_data_box)->imax)[0])) -
((((x_data_box)->imin)[0])) +
1))) ? ((((((x_data_box)->imax)[0])) -
((((x_data_box)->imin)[0])) +
1)) : (0)) * (((0) <
((((((x_data_box)->
imax)[1])) -
((((x_data_box)->
imin)[1])) +
1)))
? ((((((x_data_box)->
imax)[1])) -
((((x_data_box)->
imin)[1])) +
1)) : (0)));
int hypre__sx3 = ((base_stride[0]));
int hypre__sy3 =
((base_stride[1]) *
(((0) <
((((((r_data_box)->imax)[0])) -
((((r_data_box)->imin)[0])) +
1))) ? ((((((r_data_box)->imax)[0])) -
((((r_data_box)->imin)[0])) + 1)) : (0)));
int hypre__sz3 =
((base_stride[2]) *
(((0) <
((((((r_data_box)->imax)[0])) -
((((r_data_box)->imin)[0])) +
1))) ? ((((((r_data_box)->imax)[0])) -
((((r_data_box)->imin)[0])) +
1)) : (0)) * (((0) <
((((((r_data_box)->
imax)[1])) -
((((r_data_box)->
imin)[1])) +
1)))
? ((((((r_data_box)->
imax)[1])) -
((((r_data_box)->
imin)[1])) +
1)) : (0)));
int hypre__nx = (loop_size[0]);
int hypre__ny = (loop_size[1]);
int hypre__nz = (loop_size[2]);
int hypre__mx = hypre__nx;
int hypre__my = hypre__ny;
int hypre__mz = hypre__nz;
int hypre__dir, hypre__max;
int hypre__div, hypre__mod;
int hypre__block, hypre__num_blocks;
hypre__dir = 0;
hypre__max = hypre__nx;
if (hypre__ny > hypre__max)
{
hypre__dir = 1;
hypre__max = hypre__ny;
}
if (hypre__nz > hypre__max)
{
hypre__dir = 2;
hypre__max = hypre__nz;
}
hypre__num_blocks = 1;
if (hypre__max < hypre__num_blocks)
{
hypre__num_blocks = hypre__max;
}
if (hypre__num_blocks > 0)
{
hypre__div = hypre__max / hypre__num_blocks;
hypre__mod = hypre__max % hypre__num_blocks;
};;
/* # 287 "smg_residual.c" */
for (hypre__block = 0; hypre__block < hypre__num_blocks;
hypre__block++)
{
loopi = 0;
loopj = 0;
loopk = 0;
hypre__nx = hypre__mx;
hypre__ny = hypre__my;
hypre__nz = hypre__mz;
if (hypre__num_blocks > 1)
{
if (hypre__dir == 0)
{
loopi =
hypre__block * hypre__div +
(((hypre__mod) <
(hypre__block)) ? (hypre__mod)
: (hypre__block));
hypre__nx =
hypre__div +
((hypre__mod > hypre__block) ? 1 : 0);
}
else if (hypre__dir == 1)
{
loopj =
hypre__block * hypre__div +
(((hypre__mod) <
(hypre__block)) ? (hypre__mod)
: (hypre__block));
hypre__ny =
hypre__div +
((hypre__mod > hypre__block) ? 1 : 0);
}
else if (hypre__dir == 2)
{
loopk =
hypre__block * hypre__div +
(((hypre__mod) <
(hypre__block)) ? (hypre__mod)
: (hypre__block));
hypre__nz =
hypre__div +
((hypre__mod > hypre__block) ? 1 : 0);
}
};
Ai =
hypre__i1start + loopi * hypre__sx1 +
loopj * hypre__sy1 + loopk * hypre__sz1;
xi =
hypre__i2start + loopi * hypre__sx2 +
loopj * hypre__sy2 + loopk * hypre__sz2;
ri =
hypre__i3start + loopi * hypre__sx3 +
loopj * hypre__sy3 + loopk * hypre__sz3;
for (loopk = 0; loopk < hypre__nz; loopk++)
{
for (loopj = 0; loopj < hypre__ny; loopj++)
{
for (loopi = 0; loopi < hypre__nx; loopi++)
{
{
rp[ri] -= Ap[Ai] * xp[xi];
}
Ai += hypre__sx1;
xi += hypre__sx2;
ri += hypre__sx3;
}
Ai += hypre__sy1 - hypre__nx * hypre__sx1;
xi += hypre__sy2 - hypre__nx * hypre__sx2;
ri += hypre__sy3 - hypre__nx * hypre__sx3;
}
Ai += hypre__sz1 - hypre__ny * hypre__sy1;
xi += hypre__sz2 - hypre__ny * hypre__sy2;
ri += hypre__sz3 - hypre__ny * hypre__sy3;
}
}
};
}
}
}
}
/*-----------------------------------------------------------------------
* Return
*-----------------------------------------------------------------------*/
hypre_IncFLOPCount (residual_data->flops);
hypre_EndTiming (residual_data->time_index);
return ierr;
}
/*--------------------------------------------------------------------------
* hypre_SMGResidualSetBase
*--------------------------------------------------------------------------*/
int
hypre_SMGResidualSetBase( void *residual_vdata,
hypre_Index base_index,
hypre_Index base_stride )
{
hypre_SMGResidualData *residual_data = (hypre_SMGResidualData *)residual_vdata;
int d;
int ierr = 0;
for (d = 0; d < 3; d++)
{
hypre_IndexD((residual_data -> base_index), d)
= hypre_IndexD(base_index, d);
hypre_IndexD((residual_data -> base_stride), d)
= hypre_IndexD(base_stride, d);
}
return ierr;
}
/*--------------------------------------------------------------------------
* hypre_SMGResidualDestroy
*--------------------------------------------------------------------------*/
int
hypre_SMGResidualDestroy( void *residual_vdata )
{
int ierr = 0;
hypre_SMGResidualData *residual_data = (hypre_SMGResidualData *)residual_vdata;
if (residual_data)
{
hypre_StructMatrixDestroy(residual_data -> A);
hypre_StructVectorDestroy(residual_data -> x);
hypre_StructVectorDestroy(residual_data -> b);
hypre_StructVectorDestroy(residual_data -> r);
hypre_BoxArrayDestroy(residual_data -> base_points);
hypre_ComputePkgDestroy(residual_data -> compute_pkg );
hypre_FinalizeTiming(residual_data -> time_index);
hypre_TFree(residual_data);
}
return ierr;
}
|
lizhanhui/tddl
|
tddl-executor/src/main/java/com/taobao/tddl/executor/cursor/impl/IndexNestedLoopMgetImpCursor.java
|
<filename>tddl-executor/src/main/java/com/taobao/tddl/executor/cursor/impl/IndexNestedLoopMgetImpCursor.java
package com.taobao.tddl.executor.cursor.impl;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.taobao.tddl.common.exception.TddlException;
import com.taobao.tddl.common.utils.GeneralUtil;
import com.taobao.tddl.executor.common.DuplicateKVPair;
import com.taobao.tddl.executor.common.KVPair;
import com.taobao.tddl.executor.cursor.ICursorMeta;
import com.taobao.tddl.executor.cursor.IIndexNestLoopCursor;
import com.taobao.tddl.executor.cursor.ISchematicCursor;
import com.taobao.tddl.executor.record.CloneableRecord;
import com.taobao.tddl.executor.record.NamedRecord;
import com.taobao.tddl.executor.rowset.ArrayRowSet;
import com.taobao.tddl.executor.rowset.IRowSet;
import com.taobao.tddl.optimizer.config.table.ColumnMeta;
import com.taobao.tddl.optimizer.core.plan.query.IJoin;
/**
* 批量到右边去取数据的index nested loop实现
*
* @author mengshi.sunmengshi 2013-12-3 上午10:55:29
* @since 5.0.0
*/
public class IndexNestedLoopMgetImpCursor extends IndexNestLoopCursor implements IIndexNestLoopCursor {
/**
* 一次匹配中,batch传递的数据个数
*/
int sizeKeyLimination = 20;
/**
* 假定每个key都有25个不同的value
*/
int sizeRetLimination = 5000;
/**
* left cursor ,会先取一批数据(sizeKeyLimination个),这是那一批数据的遍历器
*/
Iterator<IRowSet> leftIterator = null;
/**
* 当前取出的kvPair
*/
Map<CloneableRecord, DuplicateKVPair> rightPairs;
/**
* 如果有重复,那么会放在这里
*/
DuplicateKVPair rightDuplicateCache;
/**
* 左cursor join on columns 的value的遍历器,这个值是从leftIterator里面,根据left join on
* column ,取出来放到队列里的。
*/
Iterator<CloneableRecord> leftJoinOnColumnCacheIterator = null;
KVPair rightPair = null;
boolean isLeftJoin = false;
boolean useProxyResult = true;
protected ICursorMeta rightCursorMeta = null;
public IndexNestedLoopMgetImpCursor(ISchematicCursor leftCursor, ISchematicCursor rightCursor, List leftColumns,
List rightColumns, List columns, List leftRetColumns, List rightRetColumns,
IJoin join) throws TddlException{
super(leftCursor, rightCursor, leftColumns, rightColumns, columns, leftRetColumns, rightRetColumns);
setLeftRightJoin(join);
}
public IndexNestedLoopMgetImpCursor(ISchematicCursor leftCursor, ISchematicCursor rightCursor, List leftColumns,
List rightColumns, List columns, boolean prefix, List leftRetColumns,
List rightRetColumns, IJoin join) throws TddlException{
super(leftCursor, rightCursor, leftColumns, rightColumns, columns, prefix, leftRetColumns, rightRetColumns);
setLeftRightJoin(join);
}
@Override
protected IRowSet proecessJoinOneWithNoneProfix(boolean forward) throws TddlException {
//
isLeftJoin = isLeftOutJoin() & !isRightOutJoin();
while (true) {
if (leftIterator == null) {// 以左值iterator,作为判断整个结果集合能不能next下去的关键判断。
boolean hasMore = getMoreRecord(forward);
if (!hasMore) {// 没有新结果集合,直接返回null
return null;
}
}
IRowSet pair = match(leftIterator, leftJoinOnColumnCacheIterator, rightPairs);
// pair.toString();
if (pair != null) {
return pair;
} else {
// 取尽,让这俩为空,这样下一次循环就可以从新去建心的iterator,或者没有iterator返回空了
leftIterator = null;
rightPairs = null;
leftJoinOnColumnCacheIterator = null;
}
}
}
/**
* <pre>
* 这个方法的核心作用,就是把已经取出的左面一组数,和右面的一组数,按照join on
* column的条件,从两边各找到一个对应的Row.然后把这两个row join到一起。 右列与左列排序相同,但右列可能出现几种情况:
* 1. 右列可能缺少左列中的某个值
* 2. 右列也可能拥有多个与左列某个值相同的值(重复)
* 若左列当前值为空,从左面拿一个值出来,再从右面拿一个值出来,做比较。否则使用左列当前值
* 因为可能出现左列某值在右列为空的情况,为了简化场景(主要简化:左要知道右是否有左,需要遍历全结果集),所以以右作为驱动表。
* 右的值,一定会在左中有对应的值。 找到他,组合成joinRecord.放到current里面。然后返回true即可。
* </pre>
*
* @param leftIterator 左值的一个遍历队列便利器
* @param leftJoinOnColumnCacheIterator2 左值中,用来做join on column的数据的队列便利器
* @param rightPairs2
* 根据左面的数据id,从右面的结果集中取出的一组数据,这组数据内是可能有重复数据的。这个Map的key,是join on column中要求的数据
* value,是拥有这行数据的KVPair的集合(也就是拥有相同join on column的数据的集合,是个链表)
* @return 返回一个Join后的结果。
*/
protected IRowSet match(Iterator<IRowSet> leftIterator, Iterator<CloneableRecord> leftJoinOnColumnCacheIterator2,
Map<CloneableRecord/* 相同的key */, DuplicateKVPair/* 见DuplicateKVPair注释 */> rightPairs2) {
IRowSet right = null;
if (rightDuplicateCache == null) {
while (leftIterator.hasNext()) {
left = leftIterator.next();
if (!leftJoinOnColumnCacheIterator2.hasNext()) {
throw new IllegalStateException("should not be here . leftJoinOnColumns is end, but left kvPair is not");
}
left_key = leftKeyNext(leftJoinOnColumnCacheIterator2);
rightDuplicateCache = rightPairs2.get(left_key);
if (rightDuplicateCache != null) {
// 匹配,找到了
right = rightDuplicateCache.currentKey;
current = joinRecord(left, right);
// 如果有重复,那么指针下移,让下次可以直接去选择。
rightDuplicateCache = rightDuplicateCache.next;
return current;
} else if (isLeftJoin) {
// 如果是left join
try {
List<ColumnMeta> rightColumns = this.right_cursor.getReturnColumns();
List<ColumnMeta> leftColumns = this.left_cursor.getReturnColumns();
if (this.rightCursorMeta == null) {
// 都是按照返回列构建的,一致
this.buildSchemaFromReturnColumns(leftColumns, rightColumns);
this.rightCursorMeta = CursorMetaImp.buildNew(rightColumns);
} else {
buildSchemaInJoin(left.getParentCursorMeta(), rightCursorMeta);
}
// 建一个都为null的rouset
IRowSet rightRowSet = new ArrayRowSet(rightCursorMeta, new Object[rightCursorMeta.getColumns()
.size()]);
current = joinRecord(left, rightRowSet);
// Object[] row = new Object[leftColumns.size() +
// rightColumns.size()];
//
// for (int i = 0; i < leftColumns.size(); i++) {
// ColumnMeta cm = leftColumns.get(i);
// Integer index =
// left.getParentCursorMeta().getIndex(cm.getTableName(),
// cm.getName());
// if (index == null) index =
// left.getParentCursorMeta().getIndex(cm.getTableName(),
// cm.getAlias());
// row[i] = left.getObject(index);
// }
// for (int i = leftColumns.size(); i < row.length; i++)
// {
// row[i] = null;
// }
// current = new ArrayRowSet(this.joinCursorMeta, row);
} catch (Exception e) {
throw new RuntimeException(e);
}
return current;
}
}
// 左值取尽
return null;
} else {
/*
* 如果 right节点的cache不为空,则证明某个右值还有数据相同的重复的Row. 所以左值不下移,右值取链表下一个。
*/
right = rightDuplicateCache.currentKey;
current = joinRecord(left, right);
// 如果有重复,那么指针下移,让下次可以直接去选择。
rightDuplicateCache = rightDuplicateCache.next;
return current;
}
}
private CloneableRecord leftKeyNext(Iterator<CloneableRecord> leftJoinOnColumnCacheIterator2) {
CloneableRecord cr = leftJoinOnColumnCacheIterator2.next();
return new NamedRecord(cr.getMap().keySet().iterator().next(), cr);
}
private boolean getMoreRecord(boolean forward) throws TddlException {
List<CloneableRecord> leftJoinOnColumnCache = new ArrayList<CloneableRecord>(sizeKeyLimination);
List<IRowSet> liftKVPair = new ArrayList<IRowSet>(sizeKeyLimination);
boolean hasMore = fillCache(leftJoinOnColumnCache, liftKVPair, forward);
if (!hasMore) {
return false;
}
// 如果使用index nest loop .那么右表一定是按主key进行查询的。
rightPairs = getRecordFromRight(leftJoinOnColumnCache);
leftIterator = liftKVPair.iterator();
leftJoinOnColumnCacheIterator = leftJoinOnColumnCache.iterator();
return true;
}
protected Map<CloneableRecord, DuplicateKVPair> getRecordFromRight(List<CloneableRecord> leftJoinOnColumnCache)
throws TddlException {
return right_cursor.mgetWithDuplicate(leftJoinOnColumnCache, false, true);
}
/**
* 将left cursor 取出 sizeKeyLimination个。 放到缓存里
*
* @param leftJoinOnColumnCache
* @param leftKVPair
* @return
* @throws TddlException
* @throws InterruptedException
*/
private boolean fillCache(List<CloneableRecord> leftJoinOnColumnCache, List<IRowSet> leftKVPair, boolean forward)
throws TddlException {
int currentSize = 0;
boolean hasMore = false;
while (getOneLeftCursor(forward) != null) {
// 有一个,就算has
hasMore = true;
GeneralUtil.checkInterrupted();
putLeftCursorValueIntoReturnVal();
// 上面的方法用来找到left Join on columns ,然后放入key里面,这里就直接利用这个key,去右边查询
leftJoinOnColumnCache.add(right_key);
leftKVPair.add(left);
currentSize++;
if (sizeKeyLimination <= currentSize) {
return true;
}
}
// 用后,清空,其他地方还可能会用到这两个类变量
left = null;
left_key = null;
// 耗尽
return hasMore;
}
}
|
Happy-sc/Doris-api
|
dataserver/dataserver.mysql/src/main/java/com/alibaba/doris/dataserver/store/mysql/MysqlDatabase.java
|
package com.alibaba.doris.dataserver.store.mysql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import javax.sql.DataSource;
import com.alibaba.doris.common.data.CompareStatus;
import com.alibaba.doris.common.data.Key;
import com.alibaba.doris.common.data.Pair;
import com.alibaba.doris.common.data.Value;
import com.alibaba.doris.dataserver.store.BaseStorage;
import com.alibaba.doris.dataserver.store.StorageType;
import com.alibaba.doris.dataserver.store.mysql.util.MysqlUtils;
import com.alibaba.doris.dataserver.store.serialize.KeyValueSerializerFactory;
/**
* @author ajun Email:<EMAIL>
*/
public class MysqlDatabase extends BaseStorage {
public MysqlDatabase(String databaseName, DataSource datasource) {
this.datasource = datasource;
this.databaseName = databaseName;
}
public void close() {
}
public void destroy() {
// execute("drop table if exists " + getDatabaseName());
}
private void createTable() {
// execute("create table " + getDatabaseName() + " (key_ varbinary(200) not null, "
// + " value_ blob, primary key(key_)) engine = InnoDB");
}
private void createTable(Key key) {
execute("create table " + getDatabaseName(key) + " (key_ varbinary(200) not null, "
+ " value_ blob, primary key(key_)) engine = InnoDB");
}
private void execute(String query) {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = datasource.getConnection();
stmt = conn.prepareStatement(query);
stmt.executeUpdate();
} catch (SQLException e) {
throw new MysqlStorageException("SQLException while performing operation.", e);
} finally {
MysqlUtils.close(stmt);
MysqlUtils.close(conn);
}
}
// private String getDatabaseName() {
// return databaseName;
// }
private String getDatabaseName(Key key) {
return databaseName + "_" + key.getVNode();
}
private boolean checkTableExists() {
// Connection conn = null;
// PreparedStatement stmt = null;
// ResultSet rs = null;
// String select = "show tables like '" + getDatabaseName() + "'";
// try {
// conn = this.datasource.getConnection();
// stmt = conn.prepareStatement(select);
// rs = stmt.executeQuery();
// return rs.next();
// } catch (SQLException e) {
// throw new MysqlStorageException("SQLException while checking for table existence!", e);
// } finally {
// MysqlUtils.close(rs);
// MysqlUtils.close(stmt);
// MysqlUtils.close(conn);
// }
return true;
}
public void open() {
if (!checkTableExists()) {
createTable();
}
}
public boolean delete(Key key) {
String delete = "delete from " + getDatabaseName(key) + " where key_ = ?";
Connection conn = null;
PreparedStatement deleteStmt = null;
try {
conn = datasource.getConnection();
deleteStmt = conn.prepareStatement(delete);
deleteStmt.setBytes(1, serializerFactory.encode(key).copyBytes());
return deleteStmt.executeUpdate() > 0;
} catch (SQLException e) {
throw new MysqlStorageException("Sql exception on delete!" + key.getKey(), e);
} finally {
MysqlUtils.close(deleteStmt);
MysqlUtils.close(conn);
}
}
public boolean delete(Key key, Value value) {
// TODO Auto-generated method stub
return false;
}
public boolean delete(List<Integer> vnodeList) {
return false;
}
public Value get(Key key) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String select = "select value_ from " + getDatabaseName(key) + " where key_ = ?";
try {
conn = datasource.getConnection();
stmt = conn.prepareStatement(select);
stmt.setBytes(1, serializerFactory.encode(key).copyBytes());
rs = stmt.executeQuery();
while (rs.next()) {
byte[] valueBytes = rs.getBytes("value_");
return serializerFactory.decodeValue(valueBytes);
}
} catch (SQLException e) {
throw new MysqlStorageException("Sql exception!", e);
} finally {
MysqlUtils.close(rs);
MysqlUtils.close(stmt);
MysqlUtils.close(conn);
}
return null;
}
public void set(Key key, Value value) {
boolean doCommit = false;
Connection conn = null;
PreparedStatement insert = null;
PreparedStatement select = null;
ResultSet results = null;
String insertSql = "insert into " + getDatabaseName(key)
+ " (key_, value_) values (?, ?) ON DUPLICATE KEY UPDATE value_= ? ";
try {
conn = datasource.getConnection();
conn.setAutoCommit(false);
byte[] keyBytes = serializerFactory.encode(key).copyBytes();
byte[] valueBytes = serializerFactory.encode(value).copyBytes();
insert = conn.prepareStatement(insertSql);
insert.setBytes(1, keyBytes);
insert.setBytes(2, valueBytes);
insert.setBytes(3, valueBytes);
insert.executeUpdate();
doCommit = true;
} catch (SQLException e) {
throw new MysqlStorageException("Fix me!" + key, e);
} finally {
if (conn != null) {
if (doCommit) {
MysqlUtils.commit(conn);
} else {
MysqlUtils.rollback(conn);
}
}
MysqlUtils.close(results);
MysqlUtils.close(insert);
MysqlUtils.close(select);
MysqlUtils.close(conn);
}
}
public void set(Key key, Value value, boolean isSetWithCompareVersion) {
boolean doCommit = false;
Connection conn = null;
PreparedStatement insert = null;
PreparedStatement select = null;
ResultSet results = null;
String insertSql = "insert into " + getDatabaseName(key) + " (key_, value_) values (?, ?)";
String selectSql = "select value_ from " + getDatabaseName(key) + " where key_ = ?";
try {
conn = datasource.getConnection();
conn.setAutoCommit(false);
byte[] keyBytes = serializerFactory.encode(key).copyBytes();
byte[] valueBytes = serializerFactory.encode(value).copyBytes();
// check for superior versions
select = conn.prepareStatement(selectSql);
select.setBytes(1, keyBytes);
results = select.executeQuery();
Value oldValue = null;
while (results.next()) {
serializerFactory.decodeValue(results.getBytes("value_"));
if (!CompareStatus.AFTER.equals(value.compareVersion(oldValue))) {
return;
} else {
delete(key);
}
}
// Okay, cool, now put the value
insert = conn.prepareStatement(insertSql);
insert.setBytes(1, keyBytes);
insert.setBytes(2, valueBytes);
insert.executeUpdate();
doCommit = true;
} catch (SQLException e) {
if (e.getErrorCode() == MYSQL_ERR_DUP_KEY || e.getErrorCode() == MYSQL_ERR_DUP_ENTRY) {
throw new MysqlStorageException("Key or value already used.");
} else {
throw new MysqlStorageException("Fix me!", e);
}
} finally {
if (conn != null) {
if (doCommit) {
MysqlUtils.commit(conn);
} else {
MysqlUtils.rollback(conn);
}
}
MysqlUtils.close(results);
MysqlUtils.close(insert);
MysqlUtils.close(select);
MysqlUtils.close(conn);
}
}
public StorageType getType() {
return MysqlStorageType.MYSQL;
}
public Iterator<Pair> iterator() {
return null;
}
public Iterator<Pair> iterator(List<Integer> vnodeList) {
return null;
}
private DataSource datasource;
private MysqlStorageConfigure config;
private String databaseName;
private static int MYSQL_ERR_DUP_KEY = 1022;
private static int MYSQL_ERR_DUP_ENTRY = 1062;
private static final KeyValueSerializerFactory serializerFactory = KeyValueSerializerFactory.getInstance();
}
|
viennamini/viennamini-dev
|
src/pde_set.cpp
|
/* =======================================================================
Copyright (c) 2011-2013, Institute for Microelectronics, TU Wien
http://www.iue.tuwien.ac.at
-----------------
ViennaMini - The Vienna Device Simulator
-----------------
authors: <NAME> <EMAIL>
<NAME> <EMAIL>
(add your name here)
license: see file LICENSE in the ViennaFVM base directory
======================================================================= */
#include "viennamini/pde_set.hpp"
namespace viennamini
{
pde_set::pde_set()
{
}
pde_set::~pde_set()
{
for(InitialGuessLookupType::iterator iter = initial_guess_lookup_.begin();
iter != initial_guess_lookup_.end(); iter++)
{
if(iter->second) delete iter->second;
}
}
viennamath::equation& pde_set::equation()
{
return equation_;
}
pde_set::ids_type& pde_set::dependencies()
{
return dependencies_;
}
pde_set::ids_type& pde_set::unknowns()
{
return unknowns_;
}
bool pde_set::is_role_supported(std::string const& key, viennamini::role::segment_role_ids segment_role)
{
if(role_lookup_.find(key) == role_lookup_.end())
throw viennamini::pde_set_exception("Quantity key \""+key+"\" is missing information regarding its support for specific segment-roles!");
return role_lookup_[key].find(segment_role) != role_lookup_[key].end();
}
void pde_set::register_quantity(std::string const& quantity_name, std::size_t quantity_id)
{
quantity_name_id_[quantity_name] = quantity_id;
}
void pde_set::set_initial_guess(std::string const& quantity_name, viennamini::quantity_generator* init_guess)
{
initial_guess_lookup_[quantity_name] = init_guess;
}
viennamini::quantity_generator* pde_set::get_initial_guess(std::string const& quantity_name, viennamini::device_handle& device_handle, std::size_t segment_index)
{
if(initial_guess_lookup_.find(quantity_name) == initial_guess_lookup_.end())
throw viennamini::pde_set_exception("Initial guess \""+quantity_name+"\" is missing!");
if(!initial_guess_lookup_[quantity_name])
throw viennamini::pde_set_exception("Initial guess \""+quantity_name+"\" is not initialized!");
initial_guess_lookup_[quantity_name]->set_device(device_handle.get());
initial_guess_lookup_[quantity_name]->set_segment_index(segment_index);
return initial_guess_lookup_[quantity_name];
}
void pde_set::set_contact_model(std::string const& quantity_name, viennamini::contact_model* model)
{
contact_model_lookup_[quantity_name] = model;
}
viennamini::contact_model* pde_set::get_contact_model(std::string const& quantity_name)
{
if(!this->has_contact_model(quantity_name))
throw viennamini::pde_set_exception("Contact model not available for quantity \""+quantity_name+"\"!");
contact_model_lookup_[quantity_name]->set_quantity_name(quantity_name);
return contact_model_lookup_[quantity_name];
}
bool pde_set::has_contact_model(std::string const& quantity_name)
{
if( contact_model_lookup_.find(quantity_name) != contact_model_lookup_.end() )
{
if(contact_model_lookup_[quantity_name]) return true;
else return false;
}
else return false;
}
void pde_set::add_dependency (std::string dependency)
{
dependencies_.push_back(dependency);
}
void pde_set::add_unknown (std::string unknown)
{
unknowns_.push_back(unknown);
}
void pde_set::add_role_support(std::string key, viennamini::role::segment_role_ids segment_role)
{
role_lookup_[key].insert(segment_role);
}
std::size_t pde_set::get_quantity_id(std::string const& quantity_name)
{
if(quantity_name_id_.find(quantity_name) == quantity_name_id_.end())
throw viennamini::pde_set_exception("Quantity \""+quantity_name+"\" has not been registered!");
return quantity_name_id_[quantity_name];
}
} // viennamini
|
alexeyche/vespa
|
controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/resource/ResourceAllocation.java
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.api.integration.resource;
import com.yahoo.config.provision.NodeResources;
import java.util.Objects;
/**
* An allocation of node resources.
*
* @author ldalves
*/
public class ResourceAllocation {
public static final ResourceAllocation ZERO = new ResourceAllocation(0, 0, 0, NodeResources.Architecture.getDefault());
private final double cpuCores;
private final double memoryGb;
private final double diskGb;
private final NodeResources.Architecture architecture;
public ResourceAllocation(double cpuCores, double memoryGb, double diskGb, NodeResources.Architecture architecture) {
this.cpuCores = cpuCores;
this.memoryGb = memoryGb;
this.diskGb = diskGb;
this.architecture = architecture;
}
public double usageFraction(ResourceAllocation total) {
return (cpuCores / total.cpuCores + memoryGb / total.memoryGb + diskGb / total.diskGb) / 3;
}
public double getCpuCores() {
return cpuCores;
}
public double getMemoryGb() {
return memoryGb;
}
public double getDiskGb() {
return diskGb;
}
public NodeResources.Architecture getArchitecture() {
return architecture;
}
/** Returns a copy of this with the given allocation added */
public ResourceAllocation plus(ResourceAllocation allocation) {
return new ResourceAllocation(cpuCores + allocation.cpuCores, memoryGb + allocation.memoryGb, diskGb + allocation.diskGb, architecture);
}
/** Returns a copy of this with each resource multiplied by given factor */
public ResourceAllocation multiply(double multiplicand) {
return new ResourceAllocation(cpuCores * multiplicand, memoryGb * multiplicand, diskGb * multiplicand, architecture);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ResourceAllocation)) return false;
ResourceAllocation other = (ResourceAllocation) o;
return Double.compare(this.cpuCores, other.cpuCores) == 0 &&
Double.compare(this.memoryGb, other.memoryGb) == 0 &&
Double.compare(this.diskGb, other.diskGb) == 0;
}
@Override
public int hashCode() {
return Objects.hash(cpuCores, memoryGb, diskGb);
}
}
|
Pleets/Talker-Town
|
public/libs/jquery-ui-1.10.4/tests/unit/tooltip/tooltip_methods.js
|
(function( $ ) {
module( "tooltip: methods" );
test( "destroy", function() {
expect( 3 );
var element = $( "#tooltipped1" );
domEqual( "#tooltipped1", function() {
element.tooltip().tooltip( "destroy" );
});
// make sure that open tooltips are removed on destroy
domEqual( "#tooltipped1", function() {
element
.tooltip()
.tooltip( "open", $.Event( "mouseover", { target: element[0] }) )
.tooltip( "destroy" );
});
equal( $( ".ui-tooltip" ).length, 0 );
});
test( "open/close", function() {
expect( 3 );
$.fx.off = true;
var tooltip,
element = $( "#tooltipped1" ).tooltip();
equal( $( ".ui-tooltip" ).length, 0, "no tooltip on init" );
element.tooltip( "open" );
tooltip = $( "#" + element.data( "ui-tooltip-id" ) );
ok( tooltip.is( ":visible" ) );
element.tooltip( "close" );
ok( tooltip.is( ":hidden" ) );
$.fx.off = false;
});
// #8626 - Calling open() without an event
test( "open/close with tracking", function() {
expect( 3 );
$.fx.off = true;
var tooltip,
element = $( "#tooltipped1" ).tooltip({ track: true });
equal( $( ".ui-tooltip" ).length, 0, "no tooltip on init" );
element.tooltip( "open" );
tooltip = $( "#" + element.data( "ui-tooltip-id" ) );
ok( tooltip.is( ":visible" ) );
element.tooltip( "close" );
ok( tooltip.is( ":hidden" ) );
$.fx.off = false;
});
test( "enable/disable", function() {
expect( 7 );
$.fx.off = true;
var tooltip,
element = $( "#tooltipped1" ).tooltip();
equal( $( ".ui-tooltip" ).length, 0, "no tooltip on init" );
element.tooltip( "open" );
tooltip = $( "#" + element.data( "ui-tooltip-id" ) );
ok( tooltip.is( ":visible" ) );
element.tooltip( "disable" );
equal( $( ".ui-tooltip" ).length, 0, "no tooltip when disabled" );
// support: jQuery <1.6.2
// support: IE <8
// We should use strictEqual( ..., undefined ) when dropping jQuery 1.6.1 support (or IE6/7)
ok( !tooltip.attr( "title" ), "title removed on disable" );
element.tooltip( "open" );
equal( $( ".ui-tooltip" ).length, 0, "open does nothing when disabled" );
element.tooltip( "enable" );
equal( element.attr( "title" ), "anchortitle", "title restored on enable" );
element.tooltip( "open" );
tooltip = $( "#" + element.data( "ui-tooltip-id" ) );
ok( tooltip.is( ":visible" ) );
$.fx.off = false;
});
test( "widget", function() {
expect( 2 );
var element = $( "#tooltipped1" ).tooltip(),
widgetElement = element.tooltip( "widget" );
equal( widgetElement.length, 1, "one element" );
strictEqual( widgetElement[ 0 ], element[ 0 ], "same element" );
});
}( jQuery ) );
|
leiferikb/bitpop-private
|
chrome/browser/extensions/api/notification/notification_apitest.cc
|
<reponame>leiferikb/bitpop-private<gh_stars>1-10
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/api/notification/notification_api.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/common/chrome_switches.h"
using extensions::Extension;
namespace utils = extension_function_test_utils;
namespace {
class NotificationApiTest : public ExtensionApiTest {
public:
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
ExtensionApiTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
}
};
} // namespace
IN_PROC_BROWSER_TEST_F(NotificationApiTest, TestSimpleNotification) {
scoped_refptr<extensions::NotificationShowFunction>
notification_show_function(new extensions::NotificationShowFunction());
scoped_refptr<Extension> empty_extension(utils::CreateEmptyExtension());
notification_show_function->set_extension(empty_extension.get());
notification_show_function->set_has_callback(true);
scoped_ptr<base::Value> result(utils::RunFunctionAndReturnSingleResult(
notification_show_function,
"[{"
"\"type\": \"simple\","
"\"iconUrl\": \"http://www.google.com/intl/en/chrome/assets/"
"common/images/chrome_logo_2x.png\","
"\"title\": \"Attention!\","
"\"message\": \"Check out Cirque du Soleil\","
"\"replaceId\": \"12345678\""
"}]",
browser(), utils::NONE));
ASSERT_EQ(base::Value::TYPE_DICTIONARY, result->GetType());
// TODO(miket): confirm that the show succeeded.
}
IN_PROC_BROWSER_TEST_F(NotificationApiTest, TestBaseFormatNotification) {
scoped_refptr<extensions::NotificationShowFunction>
notification_show_function(new extensions::NotificationShowFunction());
scoped_refptr<Extension> empty_extension(utils::CreateEmptyExtension());
notification_show_function->set_extension(empty_extension.get());
notification_show_function->set_has_callback(true);
scoped_ptr<base::Value> result(utils::RunFunctionAndReturnSingleResult(
notification_show_function,
"[{"
"\"type\": \"base\","
"\"iconUrl\": \"http://www.google.com/intl/en/chrome/assets/"
"common/images/chrome_logo_2x.png\","
"\"title\": \"Attention!\","
"\"message\": \"Check out Cirque du Soleil\","
"\"messageIntent\": \"[pending]\","
"\"priority\": 1,"
"\"timestamp\": \"Tue, 15 Nov 1994 12:45:26 GMT\","
"\"secondIconUrl\": \"http://www.google.com/logos/2012/"
"Day-Of-The-Dead-12-hp.jpg\","
"\"unreadCount\": 42,"
"\"buttonOneTitle\": \"Up\","
"\"buttonOneIntent\": \"[pending]\","
"\"buttonTwoTitle\": \"Down\","
"\"buttonTwoIntent\": \"[pending]\","
"\"expandedMessage\": \"This is a longer expanded message.\","
"\"imageUrl\": \"http://www.google.com/logos/2012/election12-hp.jpg\","
"\"replaceId\": \"12345678\""
"}]",
browser(), utils::NONE));
ASSERT_EQ(base::Value::TYPE_DICTIONARY, result->GetType());
// TODO(miket): confirm that the show succeeded.
}
IN_PROC_BROWSER_TEST_F(NotificationApiTest, TestMultipleItemNotification) {
scoped_refptr<extensions::NotificationShowFunction>
notification_show_function(new extensions::NotificationShowFunction());
scoped_refptr<Extension> empty_extension(utils::CreateEmptyExtension());
notification_show_function->set_extension(empty_extension.get());
notification_show_function->set_has_callback(true);
scoped_ptr<base::Value> result(utils::RunFunctionAndReturnSingleResult(
notification_show_function,
"[{"
"\"type\": \"multiple\","
"\"iconUrl\": \"https://code.google.com/p/chromium/logo\","
"\"title\": \"Multiple Item Notification Title\","
"\"message\": \"Multiple item notification message.\","
"\"items\": ["
" {\"title\": \"<NAME>\","
" \"message\": \"This is an important message!\"},"
" {\"title\": \"<NAME>\","
" \"message\": \"Just took a look at the proposal\"},"
" {\"title\": \"<NAME>\","
" \"message\": \"I see that you went to the conference\"},"
" {\"title\": \"<NAME>\","
" \"message\": \"I ate Harry's sandwich!\"},"
" {\"title\": \"<NAME>\","
" \"message\": \"I saw Frank steal a sandwich :-)\"}"
"],"
"\"priority\": 1,"
"\"timestamp\": \"Fri, 16 Nov 2012 01:17:15 GMT\","
"\"replaceId\": \"12345678\""
"}]",
browser(), utils::NONE));
// TODO(dharcourt): [...], items = [{title: foo, message: bar}, ...], [...]
ASSERT_EQ(base::Value::TYPE_DICTIONARY, result->GetType());
// TODO(dharcourt): confirm that the show succeeded.
}
|
ScottWinkler/github-api-app
|
react-ui/src/containers/compare.js
|
<reponame>ScottWinkler/github-api-app
//import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import Compare from '../components/compare/compare.js'
import {setUser} from '../actions/compare.js';
import {bindActionCreators} from 'redux';
const mapStateToProps=(state)=>{
return{
users: state.rootReducer.users,
first: state.rootReducer.compare.first,
second: state.rootReducer.compare.second,
first_data:state.rootReducer.compare.first_data,
second_data:state.rootReducer.compare.second_data,
loading:state.rootReducer.compare.loading
};
};
const mapDispatchToProps = (dispatch) =>{
return{
setUser: bindActionCreators(setUser,dispatch),
}
};
export default connect(mapStateToProps,mapDispatchToProps)(Compare);
|
vntodorova/Notes
|
Notes/Notes/LeftPanelViewController.h
|
<filename>Notes/Notes/LeftPanelViewController.h
//
// LeftPanelViewController.h
// Notes
//
// Created by <NAME> on 4/3/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "Protocols.h"
@class Notebook;
@class Reminder;
@class NoteManager;
@interface LeftPanelViewController : UIViewController <UITableViewDataSource,UITableViewDelegate, UIGestureRecognizerDelegate, EditableCellDelegate>
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil manager:(NoteManager *)noteManager;
- (IBAction)settingsButtonClicked:(UIButton *)sender;
- (void)loadTheme;
- (void)reloadTableViewData;
- (void)exitEditingMode;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) UIViewController<LeftPanelDelegate>* presentingViewControllerDelegate;
@property NSMutableDictionary *tableViewDataSource;
@property BOOL isHidden;
@end
|
udidoron/monday-ui-react-core
|
src/components/Menu/MenuTitle/__tests__/menuTitle.jest.js
|
import React from "react";
import renderer from "react-test-renderer";
import MenuTitle from "../MenuTitle";
it("renders correctly with empty props", () => {
const tree = renderer.create(<MenuTitle />).toJSON();
expect(tree).toMatchSnapshot();
});
it("renders correctly with custom class name", () => {
const tree = renderer.create(<MenuTitle classname="dummy-class-name" />).toJSON();
expect(tree).toMatchSnapshot();
});
it("renders correctly with caption", () => {
const tree = renderer.create(<MenuTitle caption="my title" />).toJSON();
expect(tree).toMatchSnapshot();
});
|
jultabary/4dk
|
java/project/core-java/src/main/java/org/tby/fourdk/core/query/bus/QueryDispatcher.java
|
package org.tby.fourdk.core.query.bus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tby.fourdk.core.query.Query;
import org.tby.fourdk.core.query.Response;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class QueryDispatcher implements QueryBus{
private static final Logger LOGGER = LoggerFactory.getLogger(QueryDispatcher.class);
protected Map<Class, QueryHandler> queryHandlers;
public QueryDispatcher(List<QueryHandler> queryHandlers) {
this.queryHandlers = new HashMap<>();
registerQueryHandlers(queryHandlers);
}
@Override
public Response dispatch(Query query) {
if (!isQueryHandled(query.getClass())) {
var type = query.getClass().getSimpleName();
throw new UnhandledQueryException("Query type [" + type + "] is not handled.");
}
return this.queryHandlers.get(query.getClass()).ask(query);
}
private boolean isQueryHandled(Class queryClass) {
return this.queryHandlers.containsKey(queryClass);
}
private void registerQueryHandlers(List<QueryHandler> queryHandlers) {
for (QueryHandler queryHandler : queryHandlers) {
var type = queryHandler.getQueryType().getSimpleName();
if (isQueryHandled(queryHandler.getQueryType())) {
throw new QueryAlreadyHandledException("Query type [" + type + "] is already handled." );
} else {
LOGGER.info("Register queryHandler [{}] for query [{}]", queryHandler.getClass().getSimpleName(), type);
this.queryHandlers.put(queryHandler.getQueryType(), queryHandler);
}
}
}
}
|
mauguignard/cbmc
|
regression/cbmc-library/fprintf-01/main.c
|
#include <assert.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
fprintf(stdout, "some string %s: %d\n", argv[0], 42);
fprintf(stderr, "some other string\n");
return 0;
}
|
israelba/ifbaeventos
|
src/main/java/br/edu/ifba/bru/sistemas/ifbaeventos/CriarTabelas.java
|
<reponame>israelba/ifbaeventos<filename>src/main/java/br/edu/ifba/bru/sistemas/ifbaeventos/CriarTabelas.java
package br.edu.ifba.bru.sistemas.ifbaeventos;
import javax.persistence.Persistence;
public class CriarTabelas {
public static void main(String[] args) {
Persistence.createEntityManagerFactory("ifbaeventos");
}
}
|
vkurnosov/effe
|
generator/flow_gen_res.go
|
package generator
import (
"go/ast"
"go/types"
"strings"
"github.com/GettEngineering/effe/fields"
"github.com/pkg/errors"
)
type implFieldInfo struct {
serviceFuncName *ast.Ident
originalFuncName *ast.Ident
input *ast.FieldList
output *ast.FieldList
deps *ast.FieldList
}
type flowGenRes struct {
implFuncDecls []*ast.FuncDecl
typeSpecs []*ast.TypeSpec
flowFuncDecl *ast.FuncDecl
depInitializerFuncDecl *ast.FuncDecl
imports []string
}
func (g Generator) genFlowFunc(funcName, interfaceName *ast.Ident, flowFunc *ast.FuncLit) (*ast.TypeSpec, *ast.FuncDecl) {
typeFunc := &ast.TypeSpec{
Name: ast.NewIdent(funcName.Name + g.settings.FlowFuncPostfix()),
Type: flowFunc.Type,
}
return typeFunc, newFlowFunc(g.settings.LocalInterfaceVarname(), interfaceName, funcName, typeFunc.Name, flowFunc)
}
func (g Generator) genImplField(impleName *ast.Ident, field implFieldInfo, deps []*ast.Field) (*ast.Field, *ast.FuncDecl, *ast.KeyValueExpr) {
structFieldIdent := ast.NewIdent(field.originalFuncName.Name + g.settings.ImplFieldPostfix())
structField := &ast.Field{
Names: []*ast.Ident{structFieldIdent},
Type: &ast.FuncType{
Params: field.input,
Results: field.output,
},
}
depArgs := []ast.Expr{}
for _, dep := range field.deps.List {
flowDep := fields.FindFieldWithType(deps, dep.Type)
depArgs = append(depArgs, flowDep.Names[0])
}
assignExpr := &ast.KeyValueExpr{
Key: structFieldIdent,
Value: &ast.CallExpr{
Fun: field.originalFuncName,
Args: depArgs,
},
}
callArgs := []ast.Expr{}
for _, input := range field.input.List {
callArgs = append(callArgs, input.Names[0])
}
impleNameIdent := ast.NewIdent(strings.ToLower(string([]rune(impleName.Name)[0])))
implFunc := &ast.FuncDecl{
Name: field.serviceFuncName,
Recv: &ast.FieldList{
List: []*ast.Field{
{
Names: []*ast.Ident{impleNameIdent},
Type: &ast.StarExpr{
X: impleName,
},
},
},
},
Type: &ast.FuncType{
Params: field.input,
Results: field.output,
},
Body: &ast.BlockStmt{
List: []ast.Stmt{},
},
}
if field.output != nil && len(field.output.List) > 0 {
implFunc.Body.List = append(implFunc.Body.List, &ast.ReturnStmt{
Results: []ast.Expr{
&ast.CallExpr{
Fun: &ast.SelectorExpr{
X: impleNameIdent,
Sel: structFieldIdent,
},
Args: callArgs,
},
},
})
} else {
implFunc.Body.List = append(implFunc.Body.List, &ast.ExprStmt{
X: &ast.CallExpr{
Fun: &ast.SelectorExpr{
X: impleNameIdent,
Sel: structFieldIdent,
},
Args: callArgs,
},
})
}
return structField, implFunc, assignExpr
}
func (g Generator) genImplementation(impleName, newImpleFuncName *ast.Ident, f *flowGen) (*ast.TypeSpec, *ast.FuncDecl, []*ast.FuncDecl) {
funcDecls := make([]*ast.FuncDecl, 0)
structType := &ast.StructType{
Fields: &ast.FieldList{},
}
allDeps := f.getSortedFlowDependecies()
assignExprs := []ast.Expr{}
for _, field := range f.sortedImplFields() {
strField, implFunc, assignExp := g.genImplField(impleName, field, allDeps)
assignExprs = append(assignExprs, assignExp)
structType.Fields.List = append(structType.Fields.List, strField)
funcDecls = append(funcDecls, implFunc)
}
interfaceServiceFunc := genInitializeImplementFunc(newImpleFuncName, impleName, allDeps, assignExprs)
typeSpec := &ast.TypeSpec{
Name: impleName,
Type: structType,
}
return typeSpec, interfaceServiceFunc, funcDecls
}
func genInterface(interfaceName *ast.Ident, f *flowGen) *ast.TypeSpec {
inter := &ast.InterfaceType{
Methods: &ast.FieldList{},
}
for _, fieldInfo := range f.sortedImplFields() {
fn := &ast.FuncType{
Params: fieldInfo.input,
Results: fieldInfo.output,
}
inter.Methods.List = append(inter.Methods.List, &ast.Field{
Names: []*ast.Ident{fieldInfo.serviceFuncName},
Type: fn,
})
}
return &ast.TypeSpec{
Name: interfaceName,
Type: inter,
}
}
func (g Generator) genFlow(flowFunc *ast.FuncDecl, buildFlowFuncCall *ast.CallExpr, f *flowGen, typesInfo *types.Info) (*flowGenRes, error) {
flowComponents, failureComponent, err := g.loader.LoadFlow(buildFlowFuncCall.Args, f.pkgFuncDecls)
if err != nil {
return nil, err
}
fn, imports, err := g.strategy.BuildFlow(flowComponents, failureComponent, typesInfo)
if err != nil {
return nil, err
}
resFunc, ok := fn.(*ast.FuncLit)
if !ok {
return nil, errors.New("something goes wrong")
}
for _, flowComponent := range flowComponents {
f.genImplFields(flowComponent)
}
if failureComponent != nil {
f.genImplFields(failureComponent)
}
interfaceName := ast.NewIdent(flowFunc.Name.Name + g.settings.InterfaceNamePostfix())
implName := ast.NewIdent(flowFunc.Name.Name + g.settings.ImplPostfix())
newImplFuncName := ast.NewIdent(g.settings.NewImplFuncPrefix() + implName.Name)
flowDeclTypeSpec, flowDecl := g.genFlowFunc(flowFunc.Name, interfaceName, resFunc)
implTypeSpec, implInitializationFunc, implMethods := g.genImplementation(implName, newImplFuncName, f)
serviceInterfaceSpec := genInterface(interfaceName, f)
res := &flowGenRes{
imports: imports,
flowFuncDecl: flowDecl,
implFuncDecls: implMethods,
depInitializerFuncDecl: implInitializationFunc,
}
res.typeSpecs = append(res.typeSpecs, serviceInterfaceSpec)
res.typeSpecs = append(res.typeSpecs, implTypeSpec)
res.typeSpecs = append(res.typeSpecs, flowDeclTypeSpec)
return res, nil
}
|
xSnowChen/vertx-zero
|
vertx-gaia/vertx-co/src/main/java/io/vertx/up/atom/query/tree/QValue.java
|
package io.vertx.up.atom.query.tree;
import io.vertx.up.util.Ut;
public class QValue implements QLeaf {
private transient final QOp op;
private transient final String field;
private transient final Object value;
private transient Integer level = 0;
private QValue(final String field, final QOp op, final Object value) {
this.field = field;
this.op = null == op ? QOp.EQ : op;
this.value = value;
}
static QValue create(final String field,
final QOp op,
final Object value) {
return new QValue(field, op, value);
}
@Override
public boolean isLeaf() {
return true;
}
@Override
public String field() {
return this.field;
}
@Override
public QOp op() {
return this.op;
}
@Override
public QNode level(final Integer level) {
this.level = level;
return this;
}
@Override
public Object value() {
return this.value;
}
@Override
public String toString() {
final StringBuilder source = new StringBuilder();
Ut.itRepeat(this.level, () -> source.append("\t"));
source.append("Leaf").append(",");
source.append("( ").append(this.field).append(" , ")
.append(this.op).append(" , ")
.append(this.value).append(" ) ");
return source.toString();
}
}
|
yaghouti/e-health
|
views/js/patient.js
|
<reponame>yaghouti/e-health
window.onload = function () {
var app = new Vue({
el: "#app",
data: {
activeForm: 'greeting',
menuList: [
{name: 'getTicket', text: 'دریافت نوبت'},
{name: 'myTickets', text: 'نوبتهای من'},
{name: 'myRecords', text: 'پروندهی پزشکی من'}
],
profile: {},
newTicket: null,
getTicketBy: 'specialty',
selectedItem: null,
myTickets: [],
myRecords: []
},
computed: {
orderedMyTickets: function () {
return this.myTickets.sort(function (t1, t2) {
return t1.date < t2.date ? 1 : -1;
});
},
orderedMyRecords: function () {
return this.myRecords.sort(function (r1, r2) {
return (r1.date + r1.time) < (r2.date + r2.time) ? 1 : -1;
});
}
},
methods: {
loadProfile: async function () {
try {
this.profile = await request('GET', '/profile');
}
catch (error) {
alert(error.error.message);
}
},
loadDoctors: async function () {
try {
let data = await request('GET', '/doctors');
this.doctors = data.doctors;
}
catch (error) {
alert(error.error.message);
}
},
activateForm: async function (menu) {
try {
this.activeForm = menu.name;
this.newTicket = null;
if (this.activeForm === 'myTickets') {
this.myTickets = (await request('GET', '/tickets')).tickets;
}
else if (this.activeForm === 'myRecords') {
this.myRecords = (await request('GET', '/medicalRecords')).medicalRecords;
}
}
catch (error) {
alert(error.error.message);
}
},
loadSpecialties: async function () {
try {
let data = await request('GET', '/specialties');
this.specialties = data.specialties;
}
catch (error) {
alert(error.error.message);
}
},
getTicket: async function () {
try {
let submitData = {
[this.getTicketBy]: this.selectedItem
};
this.newTicket = await request('POST', '/tickets', submitData);
}
catch (error) {
alert(error.error.message);
}
},
logout: async function () {
try {
let data = await request('GET', '/auth/logout');
window.location.href = data.location;
}
catch (error) {
alert(error.error.message);
}
}
}
});
app.loadProfile();
app.loadDoctors();
app.loadSpecialties();
};
async function request(method, url = '', data = {}) {
// Default options are marked with *
let options = {
method, // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer' // no-referrer, *client
};
if (method !== 'GET') {
options.body = JSON.stringify(data); // body data type must match "Content-Type" header
}
const response = await fetch(url, options);
if (response.status >= 200 && response.status < 300) {
return await response.json(); // parses JSON response into native JavaScript objects
}
throw await response.json();
}
|
hidura/sugelico
|
resources/site/js/orders_rep.js
|
$(function () {
$("#filters").submit(function(event){
event.preventDefault();
var data = {
"classname": "Bills.getProdsHistPreorder",
"preorder": $("#order").val()
}
console.log(data);
sugelico.postServerCall(data, function(data, status) {
console.log(data);
});
});
});
|
dekuan/thingTrust-byteballcore
|
test/test_array.js
|
<filename>test/test_array.js
var m_arrCache = [];
var m_arrCacheLeft = [];
var m_arrCacheRight = [];
m_arrCache = m_arrCacheLeft;
m_arrCache.push( 1 );
m_arrCache.push( 2 );
m_arrCache.push( 3 );
m_arrCache = m_arrCacheRight;
m_arrCache.push( 4 );
m_arrCache.push( 5 );
m_arrCache.push( 6 );
m_arrCache = null;
m_arrCacheLeft.shift();
console.log( m_arrCache, m_arrCacheLeft, m_arrCacheRight );
|
stutiredboy/obproxy
|
unittest/obproxy/test_ob_blowfish.cpp
|
<gh_stars>10-100
/**
* Copyright (c) 2021 OceanBase
* OceanBase Database Proxy(ODP) is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#define USING_LOG_PREFIX PROXY
#define private public
#define protected public
#include <gtest/gtest.h>
#include <map>
#include "lib/oblog/ob_log.h"
#include "lib/string/ob_string.h"
#include "obproxy/utils/ob_proxy_blowfish.h"
using namespace oceanbase::common;
namespace oceanbase
{
namespace obproxy
{
namespace proxy
{
const static int64_t DBKEY_COUNT = 1;
class TestBlowFish : public ::testing::Test
{
public:
static void SetUpTestCase() {}
static void TearDownTestCase() {}
};
static const char enc_pwd[DBKEY_COUNT][128] = {
"<PASSWORD>"
};
static const char plain_pwd[DBKEY_COUNT][128] = {
"<PASSWORD>"
};
TEST_F(TestBlowFish, decode)
{
int ret = OB_SUCCESS;
char dec_pwd[128];
for (int64_t i = 0; OB_SUCC(ret) && i < DBKEY_COUNT; ++i) {
memset(dec_pwd, 0, 128);
if (OB_FAIL(ObBlowFish::decode(enc_pwd[i], strlen(enc_pwd[i]), dec_pwd, 128))) {
LOG_WARN("fail to decode password", "pwd", enc_pwd[i], K(ret));
ASSERT_EQ(1, 0);
} else {
LOG_INFO("succ to decode pwd", "pwd", enc_pwd[i], "dec_pwd", dec_pwd);
ASSERT_EQ(0, memcmp(plain_pwd[i], dec_pwd, strlen(plain_pwd[i])));
}
}
}
}//end of namespace proxy
}//end of namespace obproxy
}//end of namespace oceanbase
int main(int argc, char **argv)
{
OB_LOGGER.set_log_level("WARN");
oceanbase::common::ObLogger::get_logger().set_log_level("DEBUG");
::testing::InitGoogleTest(&argc,argv);
return RUN_ALL_TESTS();
}
|
mobilesec/cormorant
|
cormorant-libsignal-service-fork/src/main/java/org/whispersystems/signalservice/api/messages/SignalServiceAttachmentStream.java
|
<filename>cormorant-libsignal-service-fork/src/main/java/org/whispersystems/signalservice/api/messages/SignalServiceAttachmentStream.java
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.whispersystems.signalservice.api.messages;
import org.whispersystems.libsignal.util.guava.Optional;
import java.io.InputStream;
/**
* Represents a local SignalServiceAttachment to be sent.
*/
public class SignalServiceAttachmentStream extends SignalServiceAttachment {
private final InputStream inputStream;
private final long length;
private final Optional<String> fileName;
private final ProgressListener listener;
private final Optional<byte[]> preview;
private final boolean voiceNote;
public SignalServiceAttachmentStream(InputStream inputStream, String contentType, long length, Optional<String> fileName, boolean voiceNote, ProgressListener listener) {
this(inputStream, contentType, length, fileName, voiceNote, Optional.<byte[]>absent(), listener);
}
public SignalServiceAttachmentStream(InputStream inputStream, String contentType, long length, Optional<String> fileName, boolean voiceNote, Optional<byte[]> preview, ProgressListener listener) {
super(contentType);
this.inputStream = inputStream;
this.length = length;
this.fileName = fileName;
this.listener = listener;
this.voiceNote = voiceNote;
this.preview = preview;
}
@Override
public boolean isStream() {
return true;
}
@Override
public boolean isPointer() {
return false;
}
public InputStream getInputStream() {
return inputStream;
}
public long getLength() {
return length;
}
public Optional<String> getFileName() {
return fileName;
}
public ProgressListener getListener() {
return listener;
}
public Optional<byte[]> getPreview() {
return preview;
}
public boolean getVoiceNote() {
return voiceNote;
}
}
|
manuelpalenga/ContinuITy
|
continuity.idpa/src/main/java/org/continuity/idpa/test/IdpaTestInstance.java
|
<filename>continuity.idpa/src/main/java/org/continuity/idpa/test/IdpaTestInstance.java
package org.continuity.idpa.test;
import java.io.IOException;
import org.continuity.idpa.WeakReference;
import org.continuity.idpa.annotation.ApplicationAnnotation;
import org.continuity.idpa.annotation.CsvInput;
import org.continuity.idpa.annotation.DirectListInput;
import org.continuity.idpa.annotation.EndpointAnnotation;
import org.continuity.idpa.annotation.ExtractedInput;
import org.continuity.idpa.annotation.ParameterAnnotation;
import org.continuity.idpa.annotation.PropertyOverride;
import org.continuity.idpa.annotation.PropertyOverrideKey;
import org.continuity.idpa.annotation.RegExExtraction;
import org.continuity.idpa.application.Application;
import org.continuity.idpa.application.HttpEndpoint;
import org.continuity.idpa.application.HttpParameter;
import org.continuity.idpa.application.HttpParameterType;
import org.continuity.idpa.serialization.yaml.IdpaYamlSerializer;
/**
* @author <NAME>
*
*/
public enum IdpaTestInstance {
SIMPLE {
@Override
protected Application setupApplication() {
Application system = new Application();
HttpEndpoint interf = new HttpEndpoint();
interf.setDomain("mydomain");
interf.setId("login");
HttpParameter param = new HttpParameter();
param.setId("user");
param.setParameterType(HttpParameterType.REQ_PARAM);
interf.getParameters().add(param);
system.addEndpoint(interf);
return system;
}
@Override
protected ApplicationAnnotation setupAnnotation(Application system) {
ApplicationAnnotation annotation = new ApplicationAnnotation();
HttpEndpoint interf = (HttpEndpoint) system.getEndpoints().get(0);
// Input
DirectListInput input = new DirectListInput();
input.setId("DAT1");
input.getData().add("foo");
input.getData().add("bar");
CsvInput csvInput = new CsvInput();
csvInput.setFilename("myfile.csv");
csvInput.setColumn(3);
csvInput.getAssociated().add(input);
ExtractedInput extrInput = new ExtractedInput();
RegExExtraction extr = new RegExExtraction();
extr.setFrom(WeakReference.create(interf));
extr.setPattern("(.*)");
extrInput.getExtractions().add(extr);
DirectListInput unknownInput = new DirectListInput();
unknownInput.setId("UNK1");
unknownInput.getData().add("something");
// Annotation
annotation = new ApplicationAnnotation();
annotation.getInputs().add(input);
annotation.getInputs().add(csvInput);
annotation.getInputs().add(extrInput);
annotation.getInputs().add(unknownInput);
annotation.setId("ANN");
EndpointAnnotation interfaceAnn = new EndpointAnnotation();
interfaceAnn.setAnnotatedEndpoint(WeakReference.create(interf));
PropertyOverride<PropertyOverrideKey.EndpointLevel> ov = new PropertyOverride<>();
ov.setKey(PropertyOverrideKey.HttpEndpoint.DOMAIN);
ov.setValue("localhost");
interfaceAnn.addOverride(ov);
ParameterAnnotation paramAnn = new ParameterAnnotation();
paramAnn.setAnnotatedParameter(WeakReference.create(interf.getParameters().get(0)));
paramAnn.setInput(input);
interfaceAnn.getParameterAnnotations().add(paramAnn);
annotation.getEndpointAnnotations().add(interfaceAnn);
return annotation;
}
},
DVDSTORE_PARSED {
@Override
protected Application setupApplication() {
IdpaYamlSerializer<Application> serializer = new IdpaYamlSerializer<>(Application.class);
try {
return serializer.readFromYamlInputStream(getClass().getResourceAsStream("/dvdstore-application.yml"));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
@Override
protected ApplicationAnnotation setupAnnotation(Application system) {
IdpaYamlSerializer<ApplicationAnnotation> serializer = new IdpaYamlSerializer<>(ApplicationAnnotation.class);
try {
return serializer.readFromYamlInputStream(getClass().getResourceAsStream("/dvdstore-annotation.yml"));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
};
private final Application application;
private final ApplicationAnnotation annotation;
/**
*
*/
private IdpaTestInstance() {
this.application = setupApplication();
this.annotation = setupAnnotation(application);
}
protected abstract Application setupApplication();
protected abstract ApplicationAnnotation setupAnnotation(Application system);
/**
* Gets {@link #application}.
*
* @return {@link #application}
*/
public Application getApplication() {
return this.application;
}
/**
* Gets {@link #annotation}.
*
* @return {@link #annotation}
*/
public ApplicationAnnotation getAnnotation() {
return this.annotation;
}
}
|
svrc-pivotal/safekeeping
|
vmbk/src/com/vmware/vmbk/soap/VimConnection.java
|
/*******************************************************************************
* Copyright (C) 2019, VMware 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package com.vmware.vmbk.soap;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.rmi.ConnectException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.handler.HandlerResolver;
import javax.xml.ws.handler.MessageContext;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.w3c.dom.Element;
import com.vmware.jvix.jDiskLib;
import com.vmware.jvix.jDiskLib.ConnectParams;
import com.vmware.pbm.PbmServiceInstanceContent;
import com.vmware.vapi.bindings.StubConfiguration;
import com.vmware.vapi.protocol.HttpConfiguration;
import com.vmware.vapi.saml.SamlToken;
import com.vmware.vim25.AboutInfo;
import com.vmware.vim25.AlreadyExistsFaultMsg;
import com.vmware.vim25.ArrayOfDatastoreHostMount;
import com.vmware.vim25.ArrayOfManagedObjectReference;
import com.vmware.vim25.DatastoreHostMount;
import com.vmware.vim25.DatastoreSummary;
import com.vmware.vim25.DiskChangeInfo;
import com.vmware.vim25.DuplicateNameFaultMsg;
import com.vmware.vim25.DynamicProperty;
import com.vmware.vim25.FileFaultFaultMsg;
import com.vmware.vim25.FileNotFoundFaultMsg;
import com.vmware.vim25.ID;
import com.vmware.vim25.InsufficientResourcesFaultFaultMsg;
import com.vmware.vim25.InvalidCollectorVersionFaultMsg;
import com.vmware.vim25.InvalidDatastoreFaultMsg;
import com.vmware.vim25.InvalidDatastorePathFaultMsg;
import com.vmware.vim25.InvalidLocaleFaultMsg;
import com.vmware.vim25.InvalidLoginFaultMsg;
import com.vmware.vim25.InvalidNameFaultMsg;
import com.vmware.vim25.InvalidPropertyFaultMsg;
import com.vmware.vim25.InvalidStateFaultMsg;
import com.vmware.vim25.LocalizedMethodFault;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.NotFoundFaultMsg;
import com.vmware.vim25.ObjectContent;
import com.vmware.vim25.ObjectSpec;
import com.vmware.vim25.OutOfBoundsFaultMsg;
import com.vmware.vim25.PropertyFilterSpec;
import com.vmware.vim25.PropertySpec;
import com.vmware.vim25.ResourceConfigSpec;
import com.vmware.vim25.RetrieveOptions;
import com.vmware.vim25.RuntimeFaultFaultMsg;
import com.vmware.vim25.SelectionSpec;
import com.vmware.vim25.TaskInfoState;
import com.vmware.vim25.TraversalSpec;
import com.vmware.vim25.UserSession;
import com.vmware.vim25.VAppConfigInfo;
import com.vmware.vim25.VAppConfigSpec;
import com.vmware.vim25.VimService;
import com.vmware.vim25.VirtualMachineConfigInfo;
import com.vmware.vim25.VmConfigFaultFaultMsg;
import com.vmware.vmbk.control.IoFunction;
import com.vmware.vmbk.control.Jvddk;
import com.vmware.vmbk.control.Jvddk.CleanUp;
import com.vmware.vmbk.control.info.RestoreManagedInfo;
import com.vmware.vmbk.logger.LoggerUtils;
import com.vmware.vmbk.profile.GlobalConfiguration;
import com.vmware.vmbk.soap.helpers.MorefUtil;
import com.vmware.vmbk.soap.helpers.VapiAuthenticationHelper;
import com.vmware.vmbk.soap.helpers.WaitForValues;
import com.vmware.vmbk.soap.helpers.builders.ObjectSpecBuilder;
import com.vmware.vmbk.soap.helpers.builders.PropertySpecBuilder;
import com.vmware.vmbk.soap.helpers.builders.SelectionSpecBuilder;
import com.vmware.vmbk.soap.helpers.builders.TraversalSpecBuilder;
import com.vmware.vmbk.soap.sso.HeaderCookieExtractionHandler;
import com.vmware.vmbk.soap.sso.HeaderHandlerResolver;
import com.vmware.vmbk.soap.sso.SamlTokenHandler;
import com.vmware.vmbk.soap.sso.SsoUtils;
import com.vmware.vmbk.soap.sso.TimeStampHandler;
import com.vmware.vmbk.soap.sso.WsSecuritySignatureAssertionHandler;
import com.vmware.vmbk.type.EntityType;
import com.vmware.vmbk.type.ImprovedVirtuaDisk;
import com.vmware.vmbk.type.ManagedEntityInfo;
import com.vmware.vmbk.type.VirtualAppManager;
import com.vmware.vmbk.type.VirtualMachineManager;
import com.vmware.vmbk.util.Utility;
import com.vmware.vslm.VslmServiceInstanceContent;
public class VimConnection extends AConnection implements IConnection {
static {
logger = Logger.getLogger(VimConnection.class.getName());
}
private HeaderCookieExtractionHandler cookieExtractor;
private String cookieVal;
private HandlerResolver defaultHandler;
private String instanceUuid;
private final Jvddk jvddk;
private Thread keepAlive;
private final String lookupServiceUuidReference;
public com.vmware.vmbk.soap.helpers.MorefUtil morefHelper;
private String privateKeyFileName;
private final Sso pscConnection;
private final VapiAuthenticationHelper vapiService;
private AboutInfo aboutInfo;
final com.vmware.vmbk.soap.helpers.WaitForValues waitForValues;
private String x509CertFileName;
private final VslmConnection vslmConnection;
private final PbmConnection pbmConnection;
VimConnection(final Sso pscConnection, final String lookupServiceUuidReference, final String url)
throws MalformedURLException {
this.waitForValues = new WaitForValues(this);
this.morefHelper = new MorefUtil(this);
setUrl(url);
this.lookupServiceUuidReference = lookupServiceUuidReference;
this.pscConnection = pscConnection;
final HttpConfiguration httpConfig = buildHttpConfiguration();
this.vapiService = new VapiAuthenticationHelper(getHost(), httpConfig, this.pscConnection.getUserCert());
this.jvddk = new Jvddk(this);
this.vslmConnection = new VslmConnection(this);
this.pbmConnection = new PbmConnection(this);
}
@SuppressWarnings("rawtypes")
private void _connect(final Element token) throws RuntimeFaultFaultMsg, InvalidLocaleFaultMsg, InvalidLoginFaultMsg,
com.vmware.pbm.RuntimeFaultFaultMsg, MalformedURLException, InvalidPropertyFaultMsg,
com.vmware.vsphereautomation.lookup.RuntimeFaultFaultMsg {
this.cookieVal = loginUsingSAMLToken(token, getURL().toString());
this.vimService = new VimService();
this.vimPort = this.vimService.getVimPort();
this.defaultHandler = this.vimService.getHandlerResolver();
final Map<String, Object> ctxt = ((BindingProvider) this.vimPort).getRequestContext();
ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, getUrl().toString());
ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);
@SuppressWarnings("unchecked")
Map<String, List<String>> headers = (Map<String, List<String>>) ctxt.get(MessageContext.HTTP_REQUEST_HEADERS);
if (headers == null) {
headers = new HashMap<>();
}
headers.put("Cookie", Arrays.asList(this.cookieVal));
ctxt.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
this.serviceContent = this.vimPort.retrieveServiceContent(getServiceInstanceReference());
this.aboutInfo = this.serviceContent.getAbout();
this.instanceUuid = this.aboutInfo.getInstanceUuid();
this.userSession = getCurrentSession();
this.headers = (Map) ((BindingProvider) this.vimPort).getResponseContext()
.get(MessageContext.HTTP_RESPONSE_HEADERS);
// this.vsoManager = this.serviceContent.getVStorageObjectManager();
}
private List<SelectionSpec> buildTraversalSpecForDatastoreToDatacenter() {
final SelectionSpec sspecvfolders = new SelectionSpecBuilder().name("VisitFolders");
final TraversalSpec visitFolders = new TraversalSpecBuilder().name("VisitFolders").path("parent").type("Folder")
.skip(false).selectSet(sspecvfolders);
final TraversalSpec datastoreToFolder = new TraversalSpecBuilder().name("DatastoreToFolder").path("parent")
.type(EntityType.Datastore.toString()).skip(false).selectSet(sspecvfolders);
final List<SelectionSpec> speclist = new ArrayList<>();
speclist.add(datastoreToFolder);
speclist.add(visitFolders);
return speclist;
}
/**
* @return
*/
private List<SelectionSpec> buildTraversalSpecForHostToDatacenter() {
final SelectionSpec sspecvfolders = new SelectionSpecBuilder().name("VisitFolders");
final TraversalSpec visitFolders = new TraversalSpecBuilder().name("VisitFolders").path("parent")
.type("hostFolder").skip(false).selectSet(sspecvfolders);
final TraversalSpec HostSystemToFolder = new TraversalSpecBuilder().name("HostSystemToFolder").path("parent")
.type(EntityType.HostSystem.toString()).skip(true).selectSet(sspecvfolders);
final TraversalSpec FolderTraversalSpec = new TraversalSpecBuilder().name("FolderTraversalSpec")
.path("childEntity").type(EntityType.Folder.toString()).skip(true).selectSet(sspecvfolders);
final List<SelectionSpec> speclist = new ArrayList<>();
speclist.add(HostSystemToFolder);
speclist.add(visitFolders);
speclist.add(FolderTraversalSpec);
return speclist;
}
private List<SelectionSpec> buildTraversalSpecForVappToDatacenter() {
final SelectionSpec sspecvfolders = new SelectionSpecBuilder().name("VisitFolders");
final TraversalSpec visitFolders = new TraversalSpecBuilder().name("VisitFolders").path("parent").type("Folder")
.skip(false).selectSet(sspecvfolders);
final SelectionSpec sspecvApp = new SelectionSpecBuilder().name("vAppToVApp");
final SelectionSpec sspecvAppToFolder = new SelectionSpecBuilder().name("vAppToFolder");
final TraversalSpec vAppToFolder = new TraversalSpecBuilder().type("VirtualApp").path("parentFolder")
.skip(false).name("vAppToFolder").selectSet(sspecvfolders);
final TraversalSpec vAppToVApp = new TraversalSpecBuilder().type("VirtualApp").path("parentVApp").skip(false)
.name("vAppToVApp").selectSet(sspecvApp, sspecvAppToFolder);
final List<SelectionSpec> speclist = new ArrayList<>();
speclist.add(vAppToFolder);
speclist.add(vAppToVApp);
speclist.add(visitFolders);
return speclist;
}
private List<SelectionSpec> buildTraversalSpecForVmToDatacenter() {
final SelectionSpec sspecvfolders = new SelectionSpecBuilder().name("VisitFolders");
final TraversalSpec visitFolders = new TraversalSpecBuilder().name("VisitFolders").path("parent").type("Folder")
.skip(false).selectSet(sspecvfolders);
final SelectionSpec sspecvApp = new SelectionSpecBuilder().name("vAppToVApp");
final SelectionSpec sspecvAppToFolder = new SelectionSpecBuilder().name("vAppToFolder");
final TraversalSpec vAppToFolder = new TraversalSpecBuilder().type("VirtualApp").path("parentFolder")
.skip(false).name("vAppToFolder").selectSet(sspecvfolders);
final TraversalSpec vAppToVApp = new TraversalSpecBuilder().type("VirtualApp").path("parentVApp").skip(false)
.name("vAppToVApp").selectSet(sspecvApp, sspecvAppToFolder);
final TraversalSpec vmTovApp = new TraversalSpecBuilder().type("VirtualMachine").path("parentVApp").skip(false)
.name("vmTovApp").selectSet(vAppToVApp, vAppToFolder);
final TraversalSpec vmToFolder = new TraversalSpecBuilder().type("VirtualMachine").path("parent").skip(false)
.name("vmToFolder").selectSet(sspecvfolders);
final List<SelectionSpec> speclist = new ArrayList<>();
speclist.add(vmToFolder);
speclist.add(vmTovApp);
speclist.add(visitFolders);
return speclist;
}
private boolean Cleanup() {
boolean success = false;
for (int i = 0; i < 3; i++) {
final CleanUp cleanupResult = this.jvddk.Cleanup();
if (cleanupResult.result == com.vmware.jvix.jDiskLib.VIX_OK) {
if (cleanupResult.numRemaining == 0) {
success = true;
break;
}
} else {
break;
}
}
return success;
}
private void clearHandlerResolver(final String vcServerUrl, final String cookie) {
this.vimService.setHandlerResolver(this.defaultHandler);
this.vimPort = this.vimService.getVimPort();
{
final Map<String, Object> ctxt = ((BindingProvider) this.vimPort).getRequestContext();
ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, vcServerUrl);
ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);
@SuppressWarnings("unchecked")
Map<String, List<String>> headers = (Map<String, List<String>>) ctxt
.get(MessageContext.HTTP_REQUEST_HEADERS);
if (headers == null) {
headers = new HashMap<>();
}
headers.put("Cookie", Arrays.asList(cookie));
ctxt.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
}
}
public Jvddk configureVddkAccess(final ImprovedVirtuaDisk ivd) {
logger.entering(getClass().getName(), "configureVddkAccess", new Object[] { ivd });
configureVddkAccess(ivd, null);
logger.exiting(getClass().getName(), "configureVddkAccess", this.jvddk);
return this.jvddk;
}
public Jvddk configureVddkAccess(final ImprovedVirtuaDisk ivd, final ID id) {
logger.entering(getClass().getName(), "configureVddkAccess", new Object[] { ivd, id });
final ConnectParams connectParams = new jDiskLib.ConnectParams();
connectParams.specType = jDiskLib.ConnectParams.VIXDISKLIB_SPEC_VSTORAGE_OBJECT;
connectParams.id = ivd.getUuid();
connectParams.datastoreMoRef = ivd.getDatastoreInfo().getMorefValue();
if (id != null) {
connectParams.ssId = id.getId();
}
connectParams.credType = jDiskLib.ConnectParams.VIXDISKLIB_CRED_SESSIONID;
connectParams.serverName = getHost();
connectParams.port = getPort();
connectParams.nfcHostPort = GlobalConfiguration.getNfcHostPort();
connectParams.username = GlobalConfiguration.getUsername();
connectParams.password = "";
connectParams.key = GlobalConfiguration.getPassword();
connectParams.cookie = getCookieValue();
connectParams.thumbPrint = getThumbPrint();
this.jvddk.setConnectParams(connectParams);
logger.exiting(getClass().getName(), "configureVddkAccess", this.jvddk);
return this.jvddk;
}
public Jvddk configureVddkAccess(final ManagedObjectReference vmMor) {
logger.entering(getClass().getName(), "configureVddkAccess", new Object[] { vmMor });
final ConnectParams connectParams = new jDiskLib.ConnectParams();
connectParams.vmxSpec = String.format("moref=%s", vmMor.getValue());
connectParams.specType = jDiskLib.ConnectParams.VIXDISKLIB_SPEC_VMX;
connectParams.credType = jDiskLib.ConnectParams.VIXDISKLIB_CRED_SESSIONID;
connectParams.serverName = getHost();
connectParams.port = getPort();
connectParams.nfcHostPort = GlobalConfiguration.getNfcHostPort();
connectParams.username = GlobalConfiguration.getUsername();
connectParams.password = "";
connectParams.key = GlobalConfiguration.getPassword();
connectParams.cookie = getCookieValue();
connectParams.thumbPrint = getThumbPrint();
this.jvddk.setConnectParams(connectParams);
logger.exiting(getClass().getName(), "configureVddkAccess", this.jvddk);
return this.jvddk;
}
@Override
public IConnection connect(final Element token) throws ConnectException {
if (!isConnected()) {
try {
socket();
_connect(token);
} catch (final Exception e) {
throw new ConnectException(String.format("failed to connect to %s not valid", getURL().toString()), e);
}
}
return this;
}
/**
* @return
* @throws MalformedURLException
* @throws ConnectException
*
*/
public PbmServiceInstanceContent connectPbm() throws ConnectException, MalformedURLException {
return getPbmConnection().connectPbm();
}
StubConfiguration connectVapi(final SamlToken samlToken) throws MalformedURLException {
logger.entering(getClass().getName(), "connectVapi", samlToken);
final StubConfiguration result = this.vapiService.loginBySamlBearerToken(samlToken);
logger.exiting(getClass().getName(), "connectVapi", result);
return result;
}
/**
* @return
* @throws MalformedURLException
* @throws ConnectException
*
*/
public VslmServiceInstanceContent connectVslm() throws ConnectException, MalformedURLException {
return getVslmConnection().connectVslm();
}
/**
* @param vim
* @param name
* @param resSpec
* @param configSpec
* @return
*/
public ManagedObjectReference createVApp(final String name, final ManagedEntityInfo rpInfo,
final ManagedEntityInfo folderInfo, final ResourceConfigSpec resSpec, final VAppConfigSpec configSpec) {
ManagedObjectReference result = null;
try {
result = getVimPort().createVApp(rpInfo.getMoref(), name, resSpec, configSpec, folderInfo.getMoref());
} catch (final Exception e) {
logger.warning(Utility.toString(e));
result = null;
}
return result;
}
public boolean deleteDirectory(final ManagedEntityInfo dcInfo, final ManagedEntityInfo dsInfo,
final String directory) {
boolean result = true;
try {
final DatastoreSummary dsSummary = (DatastoreSummary) this.morefHelper.entityProps(dsInfo.getMoref(),
"summary");
final String namespaceUrl = dsSummary.getUrl() + directory;
String datastorePath = getVimPort().convertNamespacePathToUuidPath(
getServiceContent().getDatastoreNamespaceManager(), dcInfo.getMoref(), namespaceUrl);
System.out.println("datastorePath=" + datastorePath);
datastorePath = datastorePath.substring(5);
getVimPort().deleteDirectory(getServiceContent().getDatastoreNamespaceManager(), dcInfo.getMoref(),
datastorePath);
} catch (InvalidDatastoreFaultMsg | RuntimeFaultFaultMsg | FileFaultFaultMsg | FileNotFoundFaultMsg
| InvalidDatastorePathFaultMsg e) {
logger.warning(Utility.toString(e));
result = false;
} catch (final Exception e) {
logger.warning(Utility.toString(e));
result = false;
}
return result;
}
@Override
public IConnection disconnect() {
if (isConnected()) {
try {
if (this.keepAlive != null) {
this.keepAlive.interrupt();
}
Cleanup();
logger.info("disconnecting...");
this.vimPort.logout(this.serviceContent.getSessionManager());
this.getVslmConnection().disconnect();
this.vapiService.logout();
logger.info("disconnected.");
} catch (final Exception e) {
logger.warning(Utility.toString(e));
} finally {
this.userSession = null;
this.serviceContent = null;
this.vimPort = null;
this.vimService = null;
}
}
return this;
}
/**
* @param vmFolder
* @return
*/
public ManagedObjectReference findByInventoryPath(final String path) {
logger.entering(getClass().getName(), "findByInventoryPath", path);
ManagedObjectReference result = null;
try {
result = getVimPort().findByInventoryPath(getSearchIndex(), path);
} catch (final RuntimeFaultFaultMsg e) {
logger.warning(Utility.toString(e));
}
logger.exiting(getClass().getName(), "findByInventoryPath", result);
return result;
}
/**
* @param moref
* @return
*/
public VirtualAppManager findVAppByMoref(final ManagedObjectReference moref) {
logger.entering(getClass().getName(), "findVAppByMoref", moref);
VirtualAppManager result = null;
try {
result = new VirtualAppManager(this, moref);
} catch (final RuntimeFaultFaultMsg | InvalidPropertyFaultMsg e) {
logger.warning(Utility.toString(e));
}
logger.exiting(getClass().getName(), "findVAppByMoref", result);
return result;
}
public VirtualAppManager findVAppByName(final String name) throws Exception {
logger.entering(getClass().getName(), "findVmByName", name);
VirtualAppManager result = null;
final ManagedObjectReference mor = getVAppByName(name);
if (mor != null) {
result = new VirtualAppManager(this, mor);
}
logger.exiting(getClass().getName(), "findVAppByName", result);
return result;
}
/**
* @param uuid
* @return
*/
public VirtualAppManager findVAppByUuid(final String uuid) {
// TODO Auto-generated method stub
return null;
}
// TODO Remove unused code found by UCDetector
// public ManagedObjectReference getFolder(final ManagedObjectReference dcMor, final String folder) throws Exception {
//
// final ManagedObjectReference folderMor = getvmFolderByDatacenter(dcMor, folder);
// if (folderMor == null) {
// throw new Exception("folder is not found.");
// }
// return folderMor;
// }
/**
* Finds a virtual machine or host by IP address, where the IP address is in
* dot-decimal notation. For example, 10.17.12.12. The IP address for a virtual
* machine is the one returned from VMware tools, ipAddress.
*
* @param ip The IP to find.
* @return The virtual machine entity that is found. If no managed entities are
* found, null is returned.
*/
public VirtualMachineManager findVmByIp(final String ip) {
logger.entering(getClass().getName(), "findVmByIp", ip);
VirtualMachineManager result = null;
try {
final ManagedObjectReference mor = getVimPort().findByIp(getSearchIndex(), null, ip, true);
result = new VirtualMachineManager(this, mor);
} catch (final RuntimeFaultFaultMsg e) {
logger.warning(Utility.toString(e));
}
logger.exiting(getClass().getName(), "findVmByIp", result);
return result;
}
/**
* Finds a virtual machine by the moref.
*
* @param moref The moref to find.
* @return The virtual machine entity that is found. If no managed entities are
* found, null is returned.
*/
public VirtualMachineManager findVmByMoref(final ManagedObjectReference moref) {
logger.entering(getClass().getName(), "findVmByMoref", moref);
final VirtualMachineManager result = new VirtualMachineManager(this, moref);
logger.exiting(getClass().getName(), "findVmByMoref", result);
return result;
}
public VirtualMachineManager findVmByName(final String vmName) throws Exception {
logger.entering(getClass().getName(), "findVmByName", vmName);
VirtualMachineManager result = null;
final ManagedObjectReference mor = getVmByName(vmName);
if (mor != null) {
result = new VirtualMachineManager(this, vmName, mor);
}
logger.exiting(getClass().getName(), "findVmByName", result);
return result;
}
/**
* Finds a virtual machine by BIOS or instance UUID.
*
* @param uuid The UUID to find.
* @param instanceUuid If true, search for virtual machines whose instance UUID
* matches the given uuid. Otherwise, search for virtual
* machines whose BIOS UUID matches the given uuid.
* @return The virtual machine entity that is found. If no managed entities are
* found, null is returned.
*/
public VirtualMachineManager findVmByUuid(final String uuid, final boolean instanceUuid) {
logger.entering(getClass().getName(), "findVmByUuid", uuid);
VirtualMachineManager result = null;
try {
final ManagedObjectReference mor = getVimPort().findByUuid(getSearchIndex(), null, uuid, true,
instanceUuid);
result = new VirtualMachineManager(this, mor);
} catch (final RuntimeFaultFaultMsg e) {
logger.warning(Utility.toString(e));
}
logger.exiting(getClass().getName(), "findVmByUuid", result);
return result;
}
public AboutInfo getAboutInfo() {
return this.aboutInfo;
}
LinkedList<VirtualAppManager> getAllVAppList(final String filter)
throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
ManagedObjectReference folder = null;
if ((filter != null) & !filter.isEmpty()) {
folder = this.vimPort.findByInventoryPath(getSearchIndex(), filter);
}
final Map<String, Vector<Object>> tmpList = this.morefHelper.getAllVAppList(folder);
final LinkedList<VirtualAppManager> result = new LinkedList<>();
int i = 0;
for (final String me : tmpList.keySet()) {
try {
final ManagedObjectReference mor = (ManagedObjectReference) tmpList.get(me).get(0);
final VAppConfigInfo config = (VAppConfigInfo) tmpList.get(me).get(1);
final VirtualAppManager vmm = new VirtualAppManager(this, me, mor, config);
LoggerUtils.logInfo(logger, "%d: %s %s %s", i, vmm.getUuid(), vmm.getMorefValue(), vmm.getName());
result.add(vmm);
i++;
} catch (final Exception e) {
LoggerUtils.logWarning(logger, "Virtual Machine information missing: %s skipped", me);
}
}
return result;
}
LinkedList<VirtualMachineManager> getAllVmList(final String filter)
throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
ManagedObjectReference folder = null;
if ((filter != null) & !filter.isEmpty()) {
folder = this.vimPort.findByInventoryPath(getSearchIndex(), filter);
}
final Map<String, Vector<Object>> tmpList = this.morefHelper.getAllVmList(folder);
final LinkedList<VirtualMachineManager> ret = new LinkedList<>();
int i = 0;
for (final String me : tmpList.keySet()) {
try {
final ManagedObjectReference vmMor = (ManagedObjectReference) tmpList.get(me).get(0);
final VirtualMachineConfigInfo config = (VirtualMachineConfigInfo) tmpList.get(me).get(1);
final VirtualMachineManager vmm = new VirtualMachineManager(this, me, vmMor, config);
LoggerUtils.logInfo(logger, "%d: %s %s %s", i, vmm.getUuid(), vmm.getMorefValue(), vmm.getName());
ret.add(vmm);
i++;
} catch (final Exception e) {
LoggerUtils.logWarning(logger, "Virtual Machine information missing: %s skipped", me);
}
}
return ret;
}
@Override
public String getCookie() {
return this.cookieVal;
}
@Override
public String getCookieValue() {
String[] tokens = this.cookieVal.split(";");
tokens = tokens[0].split("=");
final String extractedCookie = StringUtils.strip(tokens[1], "\"");
return extractedCookie;
}
private UserSession getCurrentSession() throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
logger.entering(getClass().getName(), "getCurrentSession");
final ManagedObjectReference entityMor = this.serviceContent.getSessionManager();
final HashMap<String, Object> retVal = new HashMap<>();
final PropertySpec propertySpec = new PropertySpec();
propertySpec.setAll(Boolean.FALSE);
propertySpec.setType(entityMor.getType());
propertySpec.getPathSet().add("currentSession");
final ObjectSpec objectSpec = new ObjectSpec();
objectSpec.setObj(entityMor);
final PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec();
propertyFilterSpec.getPropSet().add(propertySpec);
propertyFilterSpec.getObjectSet().add(objectSpec);
final List<ObjectContent> oCont = this.vimPort.retrievePropertiesEx(this.serviceContent.getPropertyCollector(),
Arrays.asList(propertyFilterSpec), new RetrieveOptions()).getObjects();
if (oCont != null) {
for (final ObjectContent oc : oCont) {
final List<DynamicProperty> dps = oc.getPropSet();
for (final DynamicProperty dp : dps) {
retVal.put(dp.getName(), dp.getVal());
}
}
}
final UserSession result = (UserSession) retVal.get("currentSession");
logger.exiting(getClass().getName(), "getCurrentSession", result);
return result;
}
public ManagedEntityInfo getDatacenterByHostsystem(final ManagedObjectReference hostMor) {
ManagedObjectReference dcMor = null;
String name = null;
final PropertySpec propertySpec = new PropertySpecBuilder().all(Boolean.FALSE)
.type(EntityType.Datacenter.toString());
propertySpec.getPathSet().add("name");
final ObjectSpec objectSpec = new ObjectSpecBuilder().obj(hostMor).skip(Boolean.TRUE);
objectSpec.getSelectSet().addAll(buildTraversalSpecForHostToDatacenter());
final PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec();
propertyFilterSpec.getPropSet().add(propertySpec);
propertyFilterSpec.getObjectSet().add(objectSpec);
final List<PropertyFilterSpec> propertyFilterSpecs = new ArrayList<>();
propertyFilterSpecs.add(propertyFilterSpec);
List<ObjectContent> oCont = null;
try {
oCont = this.vimPort.retrievePropertiesEx(this.serviceContent.getPropertyCollector(), propertyFilterSpecs,
new RetrieveOptions()).getObjects();
if (oCont != null) {
for (final ObjectContent oc : oCont) {
dcMor = oc.getObj();
name = oc.getPropSet().get(0).getVal().toString();
break;
}
}
} catch (InvalidPropertyFaultMsg | RuntimeFaultFaultMsg e) {
logger.warning(Utility.toString(e));
return null;
}
final ManagedEntityInfo datacenterInfo = new ManagedEntityInfo(name, dcMor, getServerIntanceUuid());
return datacenterInfo;
}
public ManagedEntityInfo getDatacenterByMoref(final ManagedObjectReference moref) {
ManagedObjectReference dcMor = null;
String name = null;
final PropertySpec propertySpec = new PropertySpecBuilder().all(Boolean.FALSE).type("Datacenter");
propertySpec.getPathSet().add("name");
final ObjectSpec objectSpec = new ObjectSpecBuilder().obj(moref).skip(Boolean.TRUE);
switch (EntityType.toEntityType(moref.getType())) {
case VirtualMachine:
objectSpec.getSelectSet().addAll(buildTraversalSpecForVmToDatacenter());
break;
case Datastore:
objectSpec.getSelectSet().addAll(buildTraversalSpecForDatastoreToDatacenter());
break;
case VirtualApp:
objectSpec.getSelectSet().addAll(buildTraversalSpecForVappToDatacenter());
break;
default:
return null;
}
final PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec();
propertyFilterSpec.getPropSet().add(propertySpec);
propertyFilterSpec.getObjectSet().add(objectSpec);
final List<PropertyFilterSpec> propertyFilterSpecs = new ArrayList<>();
propertyFilterSpecs.add(propertyFilterSpec);
List<ObjectContent> oCont = null;
try {
oCont = this.vimPort.retrievePropertiesEx(this.serviceContent.getPropertyCollector(), propertyFilterSpecs,
new RetrieveOptions()).getObjects();
if (oCont != null) {
for (final ObjectContent oc : oCont) {
dcMor = oc.getObj();
name = oc.getPropSet().get(0).getVal().toString();
break;
}
}
} catch (InvalidPropertyFaultMsg | RuntimeFaultFaultMsg e) {
logger.warning(Utility.toString(e));
return null;
}
final ManagedEntityInfo datacenterInfo = new ManagedEntityInfo(name, dcMor, getServerIntanceUuid());
return datacenterInfo;
}
public ManagedObjectReference getDatastoreByHost(final ManagedObjectReference hostMor) {
return getDatastoreByHost(hostMor, null);
}
public ManagedObjectReference getDatastoreByHost(final ManagedObjectReference hostMor, final String datastore) {
ManagedObjectReference dsMor = null;
List<ManagedObjectReference> dsList = null;
try {
dsList = ((ArrayOfManagedObjectReference) this.morefHelper.entityProps(hostMor, "datastore"))
.getManagedObjectReference();
} catch (InvalidPropertyFaultMsg | RuntimeFaultFaultMsg e1) {
logger.warning(Utility.toString(e1));
}
if (dsList.isEmpty()) {
throw new RuntimeException("No Datastores accesible from host " + hostMor.getValue());
}
if (datastore == null) {
dsMor = dsList.get(0);
} else {
for (final ManagedObjectReference ds : dsList) {
try {
if (datastore.equalsIgnoreCase(
(String) this.morefHelper.entityProps(ds, new String[] { "name" }).get("name"))) {
dsMor = ds;
break;
}
} catch (InvalidPropertyFaultMsg | RuntimeFaultFaultMsg e) {
logger.warning(Utility.toString(e));
}
}
}
if (dsMor == null) {
if (datastore != null) {
throw new RuntimeException(
"No Datastore by name " + datastore + " is accessible from host " + hostMor.getValue());
}
throw new RuntimeException("No Datastores accesible from host " + hostMor.getValue());
}
return dsMor;
}
// TODO Remove unused code found by UCDetector
// private ManagedObjectReference getDatastoreByHost(final String host, final String datastore) {
//
// return getDatastoreByHost(MorefUtil.create(EntityType.HostSystem, host), datastore);
// }
// TODO Remove unused code found by UCDetector
// public ManagedObjectReference getSnapshotReference(final ManagedObjectReference vmMor, final String snapName)
// throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
// final VirtualMachineSnapshotInfo snapInfo = (VirtualMachineSnapshotInfo) this.morefHelper
// .entityProps(vmMor, new String[] { "snapshot" }).get("snapshot");
// ManagedObjectReference snapmor = null;
// if (snapInfo != null) {
// final List<VirtualMachineSnapshotTree> listvmst = snapInfo.getRootSnapshotList();
// snapmor = traverseSnapshotInTree(listvmst, snapName, false);
// if (snapmor == null) {
// logger.warning("No Snapshot named : " + snapName);
// }
// } else {
//
// logger.warning("No Snapshots found ");
// }
// return snapmor;
// }
/**
* retrieve a datastore entity by name
*
* @param name
* @return
*/
public ManagedEntityInfo getDatastoreByName(final String name) {
logger.entering(getClass().getName(), "getDatastoreByName", name);
ManagedEntityInfo result = null;
if (StringUtils.isNotEmpty(name)) {
final Map<String, ManagedObjectReference> datastoreList = getDatastoreList();
if (datastoreList.containsKey(name)) {
result = new ManagedEntityInfo(name, datastoreList.get(name), this.instanceUuid);
}
}
logger.exiting(getClass().getName(), "getDatastoreByName", result);
return result;
}
public Map<String, ManagedObjectReference> getDatastoreList() {
Map<String, ManagedObjectReference> results = null;
try {
results = this.morefHelper.inFolderByType(getRootFolder(), EntityType.Datastore, new RetrieveOptions());
} catch (RuntimeFaultFaultMsg | InvalidPropertyFaultMsg e) {
logger.warning(Utility.toString(e));
}
return results;
}
public ManagedEntityInfo getDefaultResurcePool() {
ManagedObjectReference rpMoref = null;
final String defaultRP = GlobalConfiguration.getRpFilter();
if ((defaultRP != null) && !defaultRP.isEmpty()) {
try {
rpMoref = this.vimPort.findByInventoryPath(this.serviceContent.getSearchIndex(), defaultRP);
} catch (final RuntimeFaultFaultMsg e) {
logger.warning(Utility.toString(e));
return null;
}
return new ManagedEntityInfo(defaultRP.substring(defaultRP.lastIndexOf('/') + 1), rpMoref,
getServerIntanceUuid());
}
return null;
}
String getDiskPathForVc(final ManagedEntityInfo dcInfo, final String fileNameOfDisk) {
logger.entering(getClass().getName(), "getDiskPathForVc", new Object[] { dcInfo, fileNameOfDisk });
final String regex1 = "\\[(.*)\\]\\s(.*)/(.*\\.vmdk)";
String ds = null;
String vmFolder = null;
String vmdk = null;
if (Pattern.matches(regex1, fileNameOfDisk)) {
final Pattern pattern1 = Pattern.compile(regex1);
final Matcher m = pattern1.matcher(fileNameOfDisk);
if (m.find()) {
ds = m.group(1);
vmFolder = m.group(2);
vmdk = m.group(3);
}
}
/*
* diskPath format as recognized by VC:
* https://<VCIP>/folder/<PathToVmdkInsideDatastore
* >?dcPath=<DataCenterName>&dsName=<DatastoreName>
*
* Ex: diskpath = https://10.160.232.230/folder/TestVm_REKZ/TestVm_REKZ.vmdk
* ?dcPath=vcqaDC&dsName=sharedVmfs-0
*/
final String result = "https://" + getHost() + "/" + "folder/" + vmFolder + "/" + vmdk + "?dcPath="
+ dcInfo.getName() + "&dsName=" + ds;
logger.exiting(getClass().getName(), "getDiskPathForVc", result);
return result;
}
public Map<String, ManagedObjectReference> getHostList() {
Map<String, ManagedObjectReference> results = null;
try {
results = this.morefHelper.inFolderByType(getRootFolder(), EntityType.HostSystem, new RetrieveOptions());
} catch (RuntimeFaultFaultMsg | InvalidPropertyFaultMsg e) {
logger.warning(Utility.toString(e));
}
return results;
}
// TODO Remove unused code found by UCDetector
// ManagedObjectReference getvmFolderByDatastore(final ManagedObjectReference dsMor, final String folder)
// throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
//
// final ManagedEntityInfo datacenterInfo = getDatacenterByDatastore(dsMor);
// return getvmFolderByDatacenter(datacenterInfo.getMoref(), folder);
// }
public String getHostName(final ManagedObjectReference hostMor) {
String name = null;
try {
name = (String) this.morefHelper.entityProps(hostMor, "name");
} catch (InvalidPropertyFaultMsg | RuntimeFaultFaultMsg e) {
logger.warning(Utility.toString(e));
return null;
}
return name;
}
public List<DatastoreHostMount> getHostsByDatastore(final ManagedObjectReference datastore)
throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
final ArrayOfDatastoreHostMount datastoreHostsMount = (ArrayOfDatastoreHostMount) this.morefHelper
.entityProps(datastore, "host");
return datastoreHostsMount.getDatastoreHostMount();
}
public Jvddk getJvddk() {
return this.jvddk;
}
public String getLookupServiceUuidReference() {
return this.lookupServiceUuidReference;
}
public ManagedEntityInfo getManagedEntityInfo(final EntityType entity, final String name) {
return getManagedEntityInfo(getRootFolder(), entity, name);
}
public ManagedEntityInfo getManagedEntityInfo(final ManagedObjectReference root, final EntityType entity,
String name) {
ManagedObjectReference moref = null;
final Map<String, ManagedObjectReference> entityList = getManagedEntityInfoList(root, entity);
if (entityList == null) {
return null;
}
if (name == null) {
name = entityList.keySet().stream().findFirst().get();
moref = entityList.values().stream().findFirst().get();
} else {
moref = entityList.get(name);
}
if (moref == null) {
return null;
}
return new ManagedEntityInfo(name, moref, getServerIntanceUuid());
}
private Map<String, ManagedObjectReference> getManagedEntityInfoList(final ManagedObjectReference root,
final EntityType entity) {
Map<String, ManagedObjectReference> results = null;
try {
results = this.morefHelper.inFolderByType(root, entity.toString(), new RetrieveOptions());
} catch (RuntimeFaultFaultMsg | InvalidPropertyFaultMsg e) {
logger.warning(Utility.toString(e));
}
return results;
}
/**
* @return
*/
public PbmConnection getPbmConnection() {
return this.pbmConnection;
}
public String getPrivateKeyFileName() {
return this.privateKeyFileName;
}
public ManagedObjectReference getResourcePoolByHost(final ManagedObjectReference hostMor)
throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
ManagedObjectReference rpMor = null;
Map<String, Object> hostProp = null;
hostProp = this.morefHelper.entityProps(hostMor, new String[] { "parent" });
rpMor = (ManagedObjectReference) this.morefHelper.entityProps((ManagedObjectReference) hostProp.get("parent"),
"resourcePool");
return rpMor;
}
/**
* @return
*/
public ManagedObjectReference getRootFolder() {
return this.serviceContent.getRootFolder();
}
public ManagedObjectReference getSearchIndex() {
return this.serviceContent.getSearchIndex();
}
public String getServerIntanceUuid() {
return this.instanceUuid;
}
private String getSessionCookieUsingHokToken(final Element token, final String vcServerUrl)
throws InvalidLocaleFaultMsg, InvalidLoginFaultMsg, RuntimeFaultFaultMsg {
this.cookieExtractor = new HeaderCookieExtractionHandler();
updateHeaderHandlerResolver(token);
this.vimPort = this.vimService.getVimPort();
final Map<String, Object> ctxt = ((BindingProvider) this.vimPort).getRequestContext();
ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, vcServerUrl);
ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);
this.vimPort.loginByToken(this.serviceContent.getSessionManager(), null);
final String cookie = this.cookieExtractor.getCookie();
clearHandlerResolver(vcServerUrl, cookie);
return cookie;
}
public VapiAuthenticationHelper getVapiService() {
return this.vapiService;
}
public URL getVapiUrl() throws MalformedURLException {
return this.vapiService.getVapiURL();
}
private ManagedObjectReference getVAppByName(final String name) {
ManagedObjectReference vmRef;
try {
vmRef = this.morefHelper.vAppByName(name, this.serviceContent.getPropertyCollector());
} catch (InvalidPropertyFaultMsg | RuntimeFaultFaultMsg e) {
logger.warning(Utility.toString(e));
return null;
}
return vmRef;
}
public VirtualMachineConfigInfo getVirtualMachineConfigInfo(final ManagedObjectReference vmMor) {
VirtualMachineConfigInfo configInfo = null;
try {
configInfo = (VirtualMachineConfigInfo) this.morefHelper.entityProps(vmMor, "config");
} catch (InvalidPropertyFaultMsg | RuntimeFaultFaultMsg e) {
logger.warning(Utility.toString(e));
return null;
}
return configInfo;
}
private ManagedObjectReference getVmByName(final String name) {
ManagedObjectReference vmRef;
try {
vmRef = this.morefHelper.vmByName(name, this.serviceContent.getPropertyCollector());
} catch (InvalidPropertyFaultMsg | RuntimeFaultFaultMsg e) {
logger.warning(Utility.toString(e));
return null;
}
return vmRef;
}
/**
* @return
*/
public VslmConnection getVslmConnection() {
return this.vslmConnection;
}
public String getX509CertFileName() {
return this.x509CertFileName;
}
/**
* @param string
* @param string2
* @param ovfImport
* @param string3
*/
public void importVApp(final URL urlPath, final String vappName, final String host, final String datastore,
final String resourcePool, final String vmFolder) {
final OvfImport ovf = new OvfImport(this);
ovf.importVApp(urlPath, vappName, host, datastore, resourcePool, vmFolder);
}
/**
*
* @param name
* @return
*/
public boolean isIvdByNameExist(final String name) {
logger.entering(getClass().getName(), "isIvdByNameExist", name);
final ImprovedVirtuaDisk ivd = getVslmConnection().getIvdByName(name);
final boolean ret = (ivd == null) ? false : true;
logger.exiting(getClass().getName(), "isIvdByNameExist", ret);
return ret;
}
public boolean isVAppByNameExist(final String name) {
logger.entering(getClass().getName(), "isVAppByNameExist", name);
final ManagedObjectReference vmMoref = getVAppByName(name);
final boolean ret = (vmMoref == null) ? false : true;
logger.exiting(getClass().getName(), "isVAppByNameExist", ret);
return ret;
}
public boolean isVmByNameExist(final String name) {
logger.entering(getClass().getName(), "isVmByNameExist", name);
final ManagedObjectReference vmMoref = getVmByName(name);
final boolean ret = (vmMoref == null) ? false : true;
logger.exiting(getClass().getName(), "isVmByNameExist", ret);
return ret;
}
void keepAlive() throws RuntimeFaultFaultMsg {
logger.info(String.format("keep alive %s : Current Time %s", getServerIntanceUuid(),
getVimPort().currentTime(getServiceInstanceReference())));
}
private String loginUsingSAMLToken(final Element token, final String vcServerUrl)
throws RuntimeFaultFaultMsg, InvalidLocaleFaultMsg, InvalidLoginFaultMsg {
this.vimService = new VimService();
this.vimPort = this.vimService.getVimPort();
final Map<String, Object> ctxt = ((BindingProvider) this.vimPort).getRequestContext();
ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, vcServerUrl);
ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, false);
this.serviceContent = this.vimPort.retrieveServiceContent(getServiceInstanceReference());
if (SsoUtils.isHoKToken(token)) {
return getSessionCookieUsingHokToken(token, vcServerUrl);
} else {
LoggerUtils.logWarning(logger, "failed to connect to %s : token %s not valid", vcServerUrl,
token.toString());
return null;
}
}
/**
* @param virtualMachineManager
* @param key
* @param startPosition
* @param prevChanges
* @return
*/
public DiskChangeInfo queryChangedDiskAreas(final VirtualMachineManager vmm, final int key,
final long startPosition, final String prevChanges) {
logger.entering(getClass().getName(), "queryChangedDiskAreas",
new Object[] { vmm, key, startPosition, prevChanges });
DiskChangeInfo result = null;
try {
result = getVimPort().queryChangedDiskAreas(vmm.getMoref(), vmm.getSnapshotManager().getMoref(), key,
startPosition, prevChanges);
} catch (FileFaultFaultMsg | NotFoundFaultMsg | RuntimeFaultFaultMsg e) {
logger.warning(Utility.toString(e));
}
logger.exiting(getClass().getName(), "queryChangedDiskAreas");
return result;
}
public ManagedObjectReference registerVirtualMachine(final RestoreManagedInfo managedInfo) {
final String vmxPath = String.format("[%s] %s/%s.vmx", managedInfo.getDsInfo().getName(),
managedInfo.getDirectoryName(), managedInfo.getName());
return registerVirtualMachine(vmxPath, managedInfo.getName(), managedInfo.getHostInfo(),
managedInfo.getFolderInfo(), managedInfo.getRpInfo());
}
private ManagedObjectReference registerVirtualMachine(final String vmxPath, final String vmName,
final ManagedEntityInfo hostInfo, final ManagedEntityInfo folderInfo, final ManagedEntityInfo rpInfo) {
ManagedObjectReference registeredVMRef = null;
IoFunction.showInfo(logger, "Registering Virtual Machine %s Name:%s", vmxPath, vmName);
if (hostInfo == null) {
IoFunction.showWarning(logger, "Host is undefined");
}
if (folderInfo == null) {
IoFunction.showWarning(logger, "VmFolder is undefined");
}
if (rpInfo == null) {
IoFunction.showWarning(logger, "ResourcePool is undefined");
}
if ((hostInfo != null) && (folderInfo != null) && (rpInfo != null)) {
try {
final ManagedObjectReference taskmor = this.vimPort.registerVMTask(folderInfo.getMoref(), vmxPath,
vmName, false, rpInfo.getMoref(), hostInfo.getMoref());
if (waitForTask(taskmor)) {
// System.out.print("*");
registeredVMRef = (ManagedObjectReference) this.morefHelper
.entityProps(taskmor, new String[] { "info.result" }).get("info.result");
IoFunction.showInfo(logger, "VM %s registered Moref:%s", vmName, registeredVMRef.getValue());
} else {
IoFunction.showWarning(logger, "Failed to register Virtual Machine %s Name:%s", vmxPath, vmName);
}
} catch (InvalidPropertyFaultMsg | RuntimeFaultFaultMsg | InvalidCollectorVersionFaultMsg
| AlreadyExistsFaultMsg | DuplicateNameFaultMsg | FileFaultFaultMsg
| InsufficientResourcesFaultFaultMsg | InvalidDatastoreFaultMsg | InvalidNameFaultMsg
| InvalidStateFaultMsg | NotFoundFaultMsg | OutOfBoundsFaultMsg | VmConfigFaultFaultMsg e) {
logger.warning(Utility.toString(e));
return null;
}
}
return registeredVMRef;
}
public void setPrivateKeyFileName(final String privateKeyFileName) {
this.privateKeyFileName = privateKeyFileName;
}
public void setX509CertFileName(final String x509CertFileName) {
this.x509CertFileName = x509CertFileName;
}
void socket() throws NoSuchAlgorithmException, UnknownHostException, IOException, CertificateEncodingException {
final MessageDigest sha1 = MessageDigest.getInstance("SHA1");
final SSLSocketFactory factory = this.pscConnection.getSslContext().getSocketFactory();
final SSLSocket socket = (SSLSocket) factory.createSocket(getURL().getHost(), getURL().getPort());
socket.startHandshake();
final SSLSession session = socket.getSession();
final java.security.cert.Certificate[] servercerts = session.getPeerCertificates();
for (final Certificate servercert : servercerts) {
logger.fine("-----BEGIN CERTIFICATE-----\n");
logger.fine(Base64.encodeBase64String(servercert.getEncoded()));
logger.fine("\n-----END CERTIFICATE-----\n");
if (this.thumbPrint == null) {
sha1.update(servercert.getEncoded());
String sha1Digest = Utility.toHexString(sha1.digest()).replaceAll(" ", ":");
sha1Digest = sha1Digest.substring(0, sha1Digest.length() - 1);
this.thumbPrint = sha1Digest;
logger.info("Thumb: " + this.thumbPrint);
}
}
socket.close();
}
void startKeepAlive() {
this.keepAlive = KeepAlive.keepAlive(this);
this.keepAlive.start();
}
HeaderHandlerResolver updateHeaderHandlerResolver(final Element token) {
final HeaderHandlerResolver handlerResolver = new HeaderHandlerResolver();
handlerResolver.addHandler(new TimeStampHandler());
handlerResolver.addHandler(new SamlTokenHandler(token));
handlerResolver.addHandler(this.cookieExtractor);
handlerResolver.addHandler(new WsSecuritySignatureAssertionHandler(this.pscConnection.getUserCert(),
SsoUtils.getNodeProperty(token, "ID")));
this.vimService.setHandlerResolver(handlerResolver);
resetTokenUpdateSessionEventTime();
return handlerResolver;
}
/**
*
*/
public HeaderHandlerResolver updatePbmHeaderHandlerResolver() {
return this.pbmConnection.updatePbmHeaderHandlerResolver();
}
StubConfiguration updateVapi(final SamlToken samlToken) {
logger.entering(getClass().getName(), "updateVapi", samlToken);
final StubConfiguration result = this.vapiService.updateSamlBearerToken(samlToken);
logger.exiting(getClass().getName(), "updateVapi", result);
return result;
}
public HeaderHandlerResolver updateVslmHeaderHandlerResolver() {
return this.vslmConnection.updateVslmHeaderHandlerResolver();
}
public boolean waitForTask(final ManagedObjectReference task)
throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvalidCollectorVersionFaultMsg {
logger.entering(getClass().getName(), "waitForTask", task);
boolean result = false;
final Object[] waitResult = this.waitForValues.wait(task, new String[] { "info.state", "info.error" },
new String[] { "state" },
new Object[][] { new Object[] { TaskInfoState.SUCCESS, TaskInfoState.ERROR } });
if (waitResult[0].equals(TaskInfoState.SUCCESS)) {
result = true;
}
if (waitResult[1] instanceof LocalizedMethodFault) {
IoFunction.showWarning(logger, ((LocalizedMethodFault) waitResult[1]).getLocalizedMessage());
result = false;
}
logger.exiting(getClass().getName(), "waitForTask");
return result;
}
}
|
t0rr3sp3dr0/t0rr3sp3dr0.github.io
|
files/The Huxley/Problem804.java
|
import java.util.Scanner;
/**
* Created by phts on 08/06/16.
*/
public class Lista {
public static void main(String[] args) {
String nome;
double valor;
int quantidade;
Scanner in = new Scanner(System.in);
Lista lista = new Lista();
ListaProdutos lp = lista.new ListaProdutos();
for (int codigo = 1; codigo <= 3; codigo++) {
nome = in.nextLine();
valor = Double.parseDouble(in.nextLine());
quantidade = Integer.parseInt(in.nextLine());
lp.inserir(lista.new Produto(codigo, nome, valor, quantidade));
}
System.out.println(lp.procurarProduto(1));
System.out.println(lp.procurarProduto(3));
System.out.println(lp.procurarProduto(5));
}
public class Produto {
int codigo;
String nome;
double valor;
int quantidade;
public Produto(int codigo, String nome, double valor, int quantidade) {
this.codigo = codigo;
this.nome = nome;
this.valor = valor;
this.quantidade = quantidade;
}
public int getCodigo() {
return codigo;
}
public void setCodigo(int codigo) {
this.codigo = codigo;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public double getValor() {
return valor;
}
public void setValor(double valor) {
this.valor = valor;
}
public int getQuantidade() {
return quantidade;
}
public void setQuantidade(int quantidade) {
this.quantidade = quantidade;
}
@Override
public String toString() {
return "Produto [codigo=" + codigo + ", nome=" + nome + ", valor=" + valor + ", quantidade=" + quantidade + "]";
}
}
public class ListaProdutos {
Produto produto;
ListaProdutos proximo;
public ListaProdutos() {
this.produto = null;
this.proximo = null;
}
public String procurarProduto(int codigo) {
if (this.proximo != null) {
if (this.produto.getCodigo() == codigo)
return this.produto.toString();
else
return this.proximo.procurarProduto(codigo);
} else
return "Produto Inexistente!";
}
public void inserir(Produto produto) {
if (this.produto == null) {
this.produto = produto;
this.proximo = new ListaProdutos();
} else
this.proximo.inserir(produto);
}
}
}
|
fangfan/ff
|
dynamic-proxy/src/main/java/cglib/HelloMethodInterceptor.java
|
<gh_stars>0
package cglib;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
/**
* Created by F.Fang on 2015/12/2.
* Spring当中也存在MethodInterceptor.
* org.aopalliance.intercept.MethodInterceptor;
*/
public class HelloMethodInterceptor implements MethodInterceptor{
private Object target;
public HelloMethodInterceptor(Object target){
this.target = target;
}
public Object createProxy(){
Enhancer enhancer = new Enhancer();
// 生成子类.
enhancer.setSuperclass(target.getClass());
enhancer.setCallback(this);
return enhancer.create();
}
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("i am your agent");
return methodProxy.invokeSuper(o,objects);
}
}
|
chanwaikit/fulin-test
|
src/main/java/com/mazentop/entity/SysFriendsLinkType.java
|
package com.mazentop.entity;
import com.alibaba.fastjson.annotation.JSONField;
import com.mztframework.commons.Utils;
import com.mztframework.dao.jdbc.BaseBean;
import java.util.function.Supplier;
import java.util.Map;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
/**
* Author: zhaoqt
* Mail: <EMAIL>
* Date: 18:12 2020/04/01
* Company: 美赞拓
* Version: 1.0
* Description: SysFriendsLinkType实体
*/
@SuppressWarnings("all")
public class SysFriendsLinkType extends BaseBean<SysFriendsLinkType> {
/**
* 表名
*/
public static final String TABLE_NAME = "sys_friends_link_type";
/**
* 编号
*/
public static final String F_ID = "id";
/**
* 友情链接类型名称
*/
public static final String F_FRIENDS_LINK_TYPE_NAME = "friends_link_type_name";
/**
* 备注
*/
public static final String F_REMARK = "remark";
@Override
protected void initBeanValues(){
put(F_ID, null);
put(F_FRIENDS_LINK_TYPE_NAME, null);
put(F_REMARK, null);
}
public SysFriendsLinkType() {
super();
}
public SysFriendsLinkType(Map<String, Object> map) {
super(map);
}
public SysFriendsLinkType(String id) {
super();
setId(id);
}
/**
* @return id to id 编号<BR/>
*/
public String getId() {
return getTypedValue(F_ID, String.class);
}
/**
* @param id to id 编号 set
*/
public SysFriendsLinkType setId(String id) {
set(F_ID, id);
return this;
}
/**
* @return friends_link_type_name to friendsLinkTypeName 友情链接类型名称<BR/>
*/
public String getFriendsLinkTypeName() {
return getTypedValue(F_FRIENDS_LINK_TYPE_NAME, String.class);
}
/**
* @param friendsLinkTypeName to friends_link_type_name 友情链接类型名称 set
*/
public SysFriendsLinkType setFriendsLinkTypeName(String friendsLinkTypeName) {
set(F_FRIENDS_LINK_TYPE_NAME, friendsLinkTypeName);
return this;
}
/**
* @return remark to remark 备注<BR/>
*/
public String getRemark() {
return getTypedValue(F_REMARK, String.class);
}
/**
* @param remark to remark 备注 set
*/
public SysFriendsLinkType setRemark(String remark) {
set(F_REMARK, remark);
return this;
}
@JSONField(serialize = false)
@Override
public Object getPrimaryKey() {
return getId();
}
@Override
public SysFriendsLinkType setPrimaryKey(Object key) {
setId(Utils.toCast(key, String.class));
return this;
}
@JSONField(serialize = false)
@Override
public String getTableName() {
return TABLE_NAME;
}
public static SysFriendsLinkType me(){
return new SysFriendsLinkType();
}
private static class Mapper implements RowMapper<SysFriendsLinkType> {
private Supplier<SysFriendsLinkType> supplier;
public Mapper(Supplier supplier) {
this.supplier = supplier;
}
@Override
public SysFriendsLinkType mapRow(ResultSet rs, int rownum) throws SQLException {
SysFriendsLinkType bean = supplier.get();
bean.setId(Utils.toCast(rs.getObject(F_ID), String.class));
bean.setFriendsLinkTypeName(Utils.toCast(rs.getObject(F_FRIENDS_LINK_TYPE_NAME), String.class));
bean.setRemark(Utils.toCast(rs.getObject(F_REMARK), String.class));
bean.clearModifyKeys();
return bean;
}
}
@Override
public RowMapper<SysFriendsLinkType> newMapper(){
return newMapper(SysFriendsLinkType::new);
}
public RowMapper<SysFriendsLinkType> newMapper(Supplier<SysFriendsLinkType> supplier){
return new Mapper(supplier);
}
public static abstract class Sub extends SysFriendsLinkType {
@Override
public abstract RowMapper<SysFriendsLinkType> newMapper();
}
}
|
TheTripleV/GRIP
|
ui/src/main/java/edu/wpi/grip/ui/codegeneration/CppTMethods.java
|
package edu.wpi.grip.ui.codegeneration;
import edu.wpi.grip.ui.codegeneration.data.TInput;
import edu.wpi.grip.ui.codegeneration.data.TStep;
import com.google.common.base.CaseFormat;
import org.apache.commons.lang3.text.WordUtils;
public class CppTMethods extends TemplateMethods {
public CppTMethods() {
super();
}
@Override
public String name(String name) {
return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, name.replaceAll("\\s", ""));
}
@Override
public String getterName(String name) {
return "Get" + WordUtils.capitalize(name(name));
}
@Override
public String setterName(String name) {
return name(name);
}
@Override
public String callOp(TStep step) {
StringBuilder out = new StringBuilder();
if (step.name().equals("Switch") || step.name().equals("Valve")) {
out.append("pipeline");
}
out.append(name(step.name())).append('(');
for (TInput input : step.getInputs()) {
out.append(name(input.name()));
out.append(", ");
}
if (step.name().equals("Threshold_Moving")) {
out.append("this->lastImage");
out.append(step.num());
out.append(", ");
}
if (!step.getOutputs().isEmpty()) {
for (int i = 0; i < step.getOutputs().size() - 1; i++) {
out.append("this->");
out.append(name(step.getOutputs().get(i).name()));
out.append(", ");
}
out.append("this->");
out.append(name(step.getOutputs().get(step.getOutputs().size() - 1).name()));
}
out.append(')');
return out.toString();
}
}
|
duck8823/webhook-proxy
|
domain/model/job/target/git/mock_git/git.go
|
<gh_stars>10-100
// Code generated by MockGen. DO NOT EDIT.
// Source: domain/model/job/target/git/git.go
// Package mock_git is a generated GoMock package.
package mock_git
import (
context "context"
git "github.com/duck8823/duci/domain/model/job/target/git"
gomock "github.com/golang/mock/gomock"
plumbing "gopkg.in/src-d/go-git.v4/plumbing"
reflect "reflect"
)
// MockTargetSource is a mock of TargetSource interface
type MockTargetSource struct {
ctrl *gomock.Controller
recorder *MockTargetSourceMockRecorder
}
// MockTargetSourceMockRecorder is the mock recorder for MockTargetSource
type MockTargetSourceMockRecorder struct {
mock *MockTargetSource
}
// NewMockTargetSource creates a new mock instance
func NewMockTargetSource(ctrl *gomock.Controller) *MockTargetSource {
mock := &MockTargetSource{ctrl: ctrl}
mock.recorder = &MockTargetSourceMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockTargetSource) EXPECT() *MockTargetSourceMockRecorder {
return m.recorder
}
// GetSSHURL mocks base method
func (m *MockTargetSource) GetSSHURL() string {
ret := m.ctrl.Call(m, "GetSSHURL")
ret0, _ := ret[0].(string)
return ret0
}
// GetSSHURL indicates an expected call of GetSSHURL
func (mr *MockTargetSourceMockRecorder) GetSSHURL() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSSHURL", reflect.TypeOf((*MockTargetSource)(nil).GetSSHURL))
}
// GetCloneURL mocks base method
func (m *MockTargetSource) GetCloneURL() string {
ret := m.ctrl.Call(m, "GetCloneURL")
ret0, _ := ret[0].(string)
return ret0
}
// GetCloneURL indicates an expected call of GetCloneURL
func (mr *MockTargetSourceMockRecorder) GetCloneURL() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCloneURL", reflect.TypeOf((*MockTargetSource)(nil).GetCloneURL))
}
// GetRef mocks base method
func (m *MockTargetSource) GetRef() string {
ret := m.ctrl.Call(m, "GetRef")
ret0, _ := ret[0].(string)
return ret0
}
// GetRef indicates an expected call of GetRef
func (mr *MockTargetSourceMockRecorder) GetRef() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRef", reflect.TypeOf((*MockTargetSource)(nil).GetRef))
}
// GetSHA mocks base method
func (m *MockTargetSource) GetSHA() plumbing.Hash {
ret := m.ctrl.Call(m, "GetSHA")
ret0, _ := ret[0].(plumbing.Hash)
return ret0
}
// GetSHA indicates an expected call of GetSHA
func (mr *MockTargetSourceMockRecorder) GetSHA() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSHA", reflect.TypeOf((*MockTargetSource)(nil).GetSHA))
}
// MockGit is a mock of Git interface
type MockGit struct {
ctrl *gomock.Controller
recorder *MockGitMockRecorder
}
// MockGitMockRecorder is the mock recorder for MockGit
type MockGitMockRecorder struct {
mock *MockGit
}
// NewMockGit creates a new mock instance
func NewMockGit(ctrl *gomock.Controller) *MockGit {
mock := &MockGit{ctrl: ctrl}
mock.recorder = &MockGitMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockGit) EXPECT() *MockGitMockRecorder {
return m.recorder
}
// Clone mocks base method
func (m *MockGit) Clone(ctx context.Context, dir string, src git.TargetSource) error {
ret := m.ctrl.Call(m, "Clone", ctx, dir, src)
ret0, _ := ret[0].(error)
return ret0
}
// Clone indicates an expected call of Clone
func (mr *MockGitMockRecorder) Clone(ctx, dir, src interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Clone", reflect.TypeOf((*MockGit)(nil).Clone), ctx, dir, src)
}
|
langhua/OFBiz-Drools
|
webapp/business-central-7.17.0.Final/org.kie.bc.KIEWebapp/js/Plugins/patterncreator-min.js
|
if(!ORYX.Plugins){ORYX.Plugins={}
}if(!ORYX.Config){ORYX.Config={}
}ORYX.Plugins.PatternCreator=Clazz.extend({construct:function(a){this.facade=a;
this.facade.registerOnEvent(ORYX.CONFIG.CREATE_PATTERN,this.handleCreatePattern.bind(this));
this.patternShapes={};
this.patternPositions={};
this.selectedRoots=[];
this.selectedRootsCount;
this.createdElementCount;
this.patternContainer
},handleCreatePattern:function(c){if(c&&c.pid&&c.pdata&&c.pos){this.patternShapes={};
this.patternPositions={};
this.selectedRoots=[];
this.selectedRootsCount=0;
this.createdElementCount=0;
this.patternContainer=undefined;
for(var e=0;
e<c.pdata.length;
e++){var g=c.pdata[e];
if(g.id==c.pid){var f=g.elements;
var h=this.facade.getSelection();
h.each(function(i){if(i instanceof ORYX.Core.Node){this.selectedRoots[this.selectedRootsCount]=i;
this.selectedRootsCount++
}}.bind(this));
var b=this.getPatternRoots(f);
if(this.selectedRoots.length>0&&(this.selectedRoots.length!=b.length)){this.facade.raiseEvent({type:ORYX.CONFIG.EVENT_NOTIFICATION_SHOW,ntype:"error",msg:ORYX.I18N.patternCreator.errorAttaching,title:""});
return
}for(var a=0;
a<f.length;
a++){var d=f[a];
if(this.patternShapes[d.id]===undefined){this.createElement(d,c);
this.createElementChildren(d,f,c)
}else{this.createElementChildren(d,f,c)
}}this.updateParentContainer()
}}this.facade.setSelection([]);
this.facade.getCanvas().update();
this.facade.updateSelection()
}else{this.facade.raiseEvent({type:ORYX.CONFIG.EVENT_NOTIFICATION_SHOW,ntype:"error",msg:ORYX.I18N.patternCreator.invalidData,title:""})
}},updateParentContainer:function(){if(!(this.patternContainer instanceof ORYX.Core.Canvas)){var b=0;
var a=0;
var c=100;
this.patternContainer.getChildShapes(false,function(f){var e=f.bounds;
b=Math.max(b,e.lowerRight().x+c);
a=Math.max(a,e.lowerRight().y+c)
});
if(this.patternContainer.bounds.width()<b||this.patternContainer.bounds.height()<a){var d=this.patternContainer.bounds.upperLeft();
this.patternContainer.bounds.set(d.x,d.y,d.x+b,d.y+a);
this.patternContainer.update();
this.facade.getCanvas().update()
}}},getPatternRoots:function(e){var a=[];
var d=0;
for(var b=0;
b<e.length;
b++){var c=e[b];
if(c.parent.length==0){a[d]=c;
d++
}}return a
},findChildObject:function(a,d){for(var b=0;
b<d.length;
b++){var c=d[b];
if(c.id==a){return c
}}return undefined
},createElement:function(d,c){var g;
var f=this.facade.getCanvas().getAbstractShapesAtPosition(c.pos);
if(f.length<=0){g=ORYX.EDITOR._canvas
}if(f.lenght==1&&f[0] instanceof ORYX.Core.Canvas){g=ORYX.EDITOR._canvas
}else{var a=f.reverse().find(function(h){return(h instanceof ORYX.Core.Canvas||h instanceof ORYX.Core.Node||h instanceof ORYX.Core.Edge)
});
g=a
}if(!this.patternContainer||this.patternContainer===undefined){this.patternContainer=g
}if(d.parent.length==0&&this.selectedRoots.length>0){this.patternShapes[d.id]=this.selectedRoots[this.createdElementCount];
this.patternPositions[d.id]=this.selectedRoots[this.createdElementCount].absoluteCenterXY();
this.createdElementCount++;
return
}var e={x:0,y:0};
if(this.patternPositions[d.id]===undefined){e.x=c.pos.x;
e.y=c.pos.y
}else{e.x=this.patternPositions[d.id].x;
e.y=this.patternPositions[d.id].y
}e.x+=d.xyOffset[0];
e.y+=d.xyOffset[1];
var b={type:d.nodetype,namespace:d.namespace,connectingType:d.connectingType,position:e,parent:g};
this.patternShapes[d.id]=this.facade.createShape(b);
this.patternPositions[d.id]=e;
this.setElementProperties(d);
this.patternShapes[d.id].refresh();
this.facade.getCanvas().update()
},createElementChildren:function(e,j,n){var m=e.children;
for(var d=0;
d<m.length;
d++){var g=m[d];
if(this.patternShapes[g]===undefined){var f=this.findChildObject(g,j);
if(f){var c={x:0,y:0};
c.x=this.patternPositions[e.id].x;
c.y=this.patternPositions[e.id].y;
c.x+=f.xyOffset[0];
c.y+=f.xyOffset[1];
var b={type:f.nodetype,namespace:f.namespace,connectingType:f.connectingType,connectedShape:this.patternShapes[e.id],position:c,parent:this.patternContainer};
this.patternShapes[f.id]=this.facade.createShape(b);
this.patternPositions[f.id]=c;
this.setElementProperties(f);
this.patternShapes[f.id].refresh();
this.facade.getCanvas().update()
}}else{var a;
var f=this.findChildObject(g,j);
var i=ORYX.Core.StencilSet.stencil(f.connectingType);
a=new ORYX.Core.Edge({eventHandlerCallback:this.facade.raiseEvent},i);
a.dockers.first().setDockedShape(this.patternShapes[e.id]);
var h=this.patternShapes[e.id].getDefaultMagnet();
var l=h?h.bounds.center():this.patternShapes[e.id].bounds.midPoint();
a.dockers.first().setReferencePoint(l);
a.dockers.last().setDockedShape(this.patternShapes[g]);
a.dockers.last().setReferencePoint(this.patternShapes[g].getDefaultMagnet().bounds.center());
this.facade.getCanvas().add(a);
this.facade.getCanvas().update()
}}},createPatternFromSelection:function(){var d=this.facade.getSelection();
if(d&&d.size()>0){var c=this.findParentShapes(d);
if(c&&c.size()>0){var e=new Ext.form.TextField({fieldLabel:ORYX.I18N.patternCreator.patternName,allowBlank:false,id:"patternName",regex:/^[a-z0-9 \-\.\_]*$/i});
var a=new Ext.form.FormPanel({baseCls:"x-plain",labelWidth:150,labelAlign:"right",bodyStyle:"padding:15x 15px 15px 15px",defaultType:"textfield",items:[e]});
var b=new Ext.Window({layout:"anchor",autoCreate:true,title:ORYX.I18N.patternCreator.create,height:150,width:400,modal:true,collapsible:false,fixedcenter:true,shadow:true,resizable:true,proxyDrag:true,autoScroll:true,keys:[{key:27,fn:function(){b.hide()
}.bind(this)}],items:[a],listeners:{hide:function(){b.destroy()
}.bind(this)},buttons:[{text:ORYX.I18N.PropertyWindow.ok,handler:function(){b.hide()
}.bind(this)},{text:ORYX.I18N.PropertyWindow.cancel,handler:function(){b.hide()
}.bind(this)}]});
b.show()
}else{this.facade.raiseEvent({type:ORYX.CONFIG.EVENT_NOTIFICATION_SHOW,ntype:"error",msg:ORYX.I18N.patternCreator.invalidSelect,title:""})
}}else{this.facade.raiseEvent({type:ORYX.CONFIG.EVENT_NOTIFICATION_SHOW,ntype:"error",msg:ORYX.I18N.patternCreator.noNodesSel,title:""})
}},setElementProperties:function(b){if(b.properties){var c=b.properties;
for(var a in c){this.patternShapes[b.id].setProperty("oryx-"+a,c[a])
}}},findParentShapes:function(c){var a=[];
var b=0;
c.each(function(d){if(d.getIncomingShapes()&&d.getIncomingShapes().size()>0){if(!this.isInSelection(c,d.getIncomingShapes())){if(d instanceof ORYX.Core.Node){a[b]=d;
b++
}}}else{a[b]=d;
b++
}}.bind(this));
return a
},isInSelection:function(d,a){var b=false;
if(!a||a.size()==0){return false
}for(var c=0;
c<a.length;
c++){d.each(function(e){if(e.resourceId==a[c].resourceId){b=true
}}.bind(this))
}return b
}});
|
brian-kelley/seacas
|
docs/ioss_html/classIogs_1_1IOFactory.js
|
<reponame>brian-kelley/seacas
var classIogs_1_1IOFactory =
[
[ "IOFactory", "classIogs_1_1IOFactory.html#ad1776901ec22677b54e5d1f21b7f7289", null ],
[ "factory", "classIogs_1_1IOFactory.html#acdfdf15dabab3f8f5b241c91c1420098", null ],
[ "make_IO", "classIogs_1_1IOFactory.html#aae6db274c5d4f146ca50b4ad2679e95b", null ]
];
|
arguiot/Cascade
|
src/static/all.js
|
Cascade.all = Cascade.init("*")
|
ScalablyTyped/SlinkyTyped
|
b/blueprintjs__core/src/main/scala/typingsSlinky/blueprintjsCore/hotkeyParserMod.scala
|
package typingsSlinky.blueprintjsCore
import org.scalablytyped.runtime.NumberDictionary
import org.scalablytyped.runtime.StringDictionary
import org.scalajs.dom.raw.KeyboardEvent
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
object hotkeyParserMod {
@JSImport("@blueprintjs/core/lib/esm/components/hotkeys/hotkeyParser", "Aliases")
@js.native
val Aliases: IKeyMap = js.native
@JSImport("@blueprintjs/core/lib/esm/components/hotkeys/hotkeyParser", "KeyCodes")
@js.native
val KeyCodes: IKeyCodeTable = js.native
@JSImport("@blueprintjs/core/lib/esm/components/hotkeys/hotkeyParser", "ModifierBitMasks")
@js.native
val ModifierBitMasks: IKeyCodeReverseTable = js.native
@JSImport("@blueprintjs/core/lib/esm/components/hotkeys/hotkeyParser", "Modifiers")
@js.native
val Modifiers: IKeyCodeTable = js.native
@JSImport("@blueprintjs/core/lib/esm/components/hotkeys/hotkeyParser", "ShiftKeys")
@js.native
val ShiftKeys: IKeyMap = js.native
@JSImport("@blueprintjs/core/lib/esm/components/hotkeys/hotkeyParser", "comboMatches")
@js.native
def comboMatches(a: IKeyCombo, b: IKeyCombo): Boolean = js.native
@JSImport("@blueprintjs/core/lib/esm/components/hotkeys/hotkeyParser", "getKeyCombo")
@js.native
def getKeyCombo(e: KeyboardEvent): IKeyCombo = js.native
@JSImport("@blueprintjs/core/lib/esm/components/hotkeys/hotkeyParser", "getKeyComboString")
@js.native
def getKeyComboString(e: KeyboardEvent): String = js.native
@JSImport("@blueprintjs/core/lib/esm/components/hotkeys/hotkeyParser", "normalizeKeyCombo")
@js.native
def normalizeKeyCombo(combo: String): js.Array[String] = js.native
@JSImport("@blueprintjs/core/lib/esm/components/hotkeys/hotkeyParser", "normalizeKeyCombo")
@js.native
def normalizeKeyCombo(combo: String, platformOverride: String): js.Array[String] = js.native
@JSImport("@blueprintjs/core/lib/esm/components/hotkeys/hotkeyParser", "parseKeyCombo")
@js.native
def parseKeyCombo(combo: String): IKeyCombo = js.native
type IKeyCodeReverseTable = StringDictionary[Double]
type IKeyCodeTable = NumberDictionary[String]
@js.native
trait IKeyCombo extends StObject {
var key: js.UndefOr[String] = js.native
var modifiers: Double = js.native
}
object IKeyCombo {
@scala.inline
def apply(modifiers: Double): IKeyCombo = {
val __obj = js.Dynamic.literal(modifiers = modifiers.asInstanceOf[js.Any])
__obj.asInstanceOf[IKeyCombo]
}
@scala.inline
implicit class IKeyComboMutableBuilder[Self <: IKeyCombo] (val x: Self) extends AnyVal {
@scala.inline
def setKey(value: String): Self = StObject.set(x, "key", value.asInstanceOf[js.Any])
@scala.inline
def setKeyUndefined: Self = StObject.set(x, "key", js.undefined)
@scala.inline
def setModifiers(value: Double): Self = StObject.set(x, "modifiers", value.asInstanceOf[js.Any])
}
}
type IKeyMap = StringDictionary[String]
}
|
liuyanyi/mmdetection
|
tools/dota/dota_image.py
|
<reponame>liuyanyi/mmdetection<filename>tools/dota/dota_image.py
import os
from argparse import ArgumentParser
from mmdet.apis import (inference_detector,
init_detector)
def parse_args():
parser = ArgumentParser()
parser.add_argument('img_dir', help='Image file folder')
parser.add_argument('out_dir', help='Image file output folder')
parser.add_argument('config', help='Config file')
parser.add_argument('checkpoint', help='Checkpoint file')
parser.add_argument(
'--device', default='cuda:0', help='Device used for inference')
parser.add_argument(
'--score-thr', type=float, default=0.3, help='bbox score threshold')
args = parser.parse_args()
return args
def main(args):
# build the model from a config file and a checkpoint file
model = init_detector(args.config, args.checkpoint, device=args.device)
files = os.listdir(args.img_dir) # 得到文件夹下的所有文件名称
for file in files: # 遍历文件夹
if not os.path.isdir(file): # 判断是否是文件夹,不是文件夹才打开
file_path = os.path.join(args.img_dir, file)
# test a single image
result = inference_detector(model, file_path)
# show the results
model.show_result(
file_path,
result,
score_thr=args.score_thr,
show=False,
wait_time=0,
bbox_color=(72, 101, 241),
text_color=(72, 101, 241),
out_file=os.path.join(args.out_dir, file)
)
if __name__ == '__main__':
args = parse_args()
main(args)
|
battila7/dijon
|
src/main/java/io/risotto/binding/InstanceBinding.java
|
<gh_stars>1-10
package io.risotto.binding;
import static io.risotto.instantiation.InstantiationMode.INSTANCE;
import io.risotto.instantiation.InstantiationMode;
import io.risotto.instantiation.InstantiatorFactory;
import io.risotto.instantiation.NoOpInstantiator;
import java.util.Objects;
/**
* This binding binds an actual instance to its bound class. The class of the instance held in the
* binding must be a subclass of the binding's bound class. This instance is then used to resolve
* dependencies with appropriate types.
* @param <T> the bound type
*/
public class InstanceBinding<T> extends InstantiatableBinding<T> {
private final T instance;
/**
* Constructs a new {@code InstanceBinding} holding the specified instance and wrapping the
* specified binding.
* @param binding the binding to wrap
* @param instance the associated instance
* @param <I> the type of the instance, must be a subtype of the bound type
* @throws NullPointerException if a parameter is {@code null}
*/
public <I extends T> InstanceBinding(Binding<T> binding, I instance) {
super(binding);
this.instance = Objects.requireNonNull(instance);
instantiator =
InstantiatorFactory
.decorateInstantiatorForMode(new NoOpInstantiator<>(instance), instantiationMode);
}
/**
* Applies the specified {@code InstantiationMode} to the binding. Can be used to alter the
* behaviour of {@link #getInstance()}.
* @param mode the new mode
* @return the current instance
* @throws IllegalArgumentException if the mode is {@link InstantiationMode#INSTANCE}
*/
@Override
public InstantiatableBinding<T> withMode(InstantiationMode mode) {
if (mode == INSTANCE) {
throw new IllegalArgumentException("INSTANCE mode cannot be applied to this binding!");
}
return super.withMode(mode);
}
@Override
public String toString() {
return "InstanceBinding{" +
"instance=" + instance +
"} " + super.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
InstanceBinding<?> that = (InstanceBinding<?>) o;
return instance.equals(that.instance);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + instance.hashCode();
return result;
}
}
|
tusharchoudhary0003/Custom-Football-Game
|
sources/p019d/p143b/p144a/p147c/C7203ra.java
|
package p019d.p143b.p144a.p147c;
import p019d.p143b.p150d.C7251a;
import p019d.p143b.p150d.C7253c;
import p019d.p143b.p150d.C7267q;
/* renamed from: d.b.a.c.ra */
final class C7203ra implements Runnable {
/* renamed from: a */
final /* synthetic */ C7253c f13932a;
/* renamed from: b */
final /* synthetic */ C7251a f13933b;
/* renamed from: c */
final /* synthetic */ C7267q f13934c;
C7203ra(C7253c cVar, C7251a aVar, C7267q qVar) {
this.f13932a = cVar;
this.f13933b = aVar;
this.f13934c = qVar;
}
public void run() {
try {
this.f13932a.adHidden(C7171ja.m15282b(this.f13933b));
} catch (Throwable th) {
this.f13934c.mo23049b().mo22919c("ListenerCallbackInvoker", "Unable to notify ad event listener about ad being hidden", th);
}
}
}
|
eebenson/haggle
|
src/bbs/httpd.h
|
/* Copyright 2008 Uppsala University
*
* 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.
*/
#ifndef _httpd_h_
#define _httpd_h_
#include "databuf.h"
/*
Minimalistic httpd helper library.
This is not exactly inteded as a complete HTTP implementation, but
something that mimics HTTP enough to fool a web browser such as Safari,
IE, or Firefox.
*/
/**
Sets up the httpd helper library, and starts listening for HTTP connections
on the given port.
Returns true iff the helper library can be further used.
*/
bool httpd_startup(int port);
/**
Starts accepting client connections. Will not return until httpd_shutdown
is called.
*/
void httpd_accept_connections(void);
/**
Closes the http port opened using httpd_startup. Shuts down the httpd
helper library.
The helper library can not be used further after calling this function.
*/
void httpd_shutdown(void);
/**
Returns a error message to the client and shuts the connection down.
Only meant for 4XX,5XX errors like: 404/Not found, 500/Infernal server
error.
*/
void http_reply_err(int err);
/**
Returns the given data to the client, then closes the connection.
The client will get a 200/OK, then the given data.
The content_type variable should point to a null-terminated string
containing a content type, (such as "text/html"), it should not contain
any carriage returns or line feeds.
*/
void http_reply_data(char *data, long len, char *content_type);
/*
Called whenever a HTTP GET request is made by a client.
This function has to be implemented by whatever uses this library.
The string is null-terminated.
*/
void httpd_process_GET(char *resource_name);
/*
Called whenever a HTTP POST request is made by a client.
This function has to be implemented by whatever uses this library.
The resource name string is null-terminated.
The post_data string is null-terminated, but the null-terminating character
is not included in the data_len count.
Modifying the given strings is fine, but do not assume you can write to any
byte beyond them.
*/
void httpd_process_POST(char *resource_name, char *post_data, long data_len);
/*
Function to get the content of the input field with the given name.
The returned data should not be deallocated (it's just a reference into
the original data buffer).
The returned data will not need decoding.
The given data buffer will be modified (but not beyond the given bounds).
Returns NULL/0 if there was no such input field.
*/
data_buffer httpd_post_data_get_data_for_input(
char *input,
char *data,
long data_len);
#endif
|
Legend383838/AresClient-Deobf
|
Ares/mods/impl/ModArmorStatus.java
|
<filename>Ares/mods/impl/ModArmorStatus.java
package Ares.mods.impl;
import Ares.GuiIngameMods;
import Ares.event.gui.hud.ScreenPosition;
import Ares.mods.ModDraggable;
import java.awt.Color;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import org.lwjgl.opengl.GL11;
public class ModArmorStatus extends ModDraggable {
public static String Text = "on";
private ScreenPosition pos = ScreenPosition.fromRalativePosition(0.5D, 0.5D);
public void renderDummy(ScreenPosition var1) {
this.renderItemStack(var1, 3, new ItemStack(Items.diamond_helmet));
this.renderItemStack(var1, 2, new ItemStack(Items.diamond_chestplate));
this.renderItemStack(var1, 1, new ItemStack(Items.diamond_leggings));
this.renderItemStack(var1, 0, new ItemStack(Items.diamond_boots));
}
public int getWidth() {
return 64;
}
public void render(ScreenPosition var1) {
if (GuiIngameMods.Armor.contains("on")) {
for(int var2 = 0; var2 < this.mc.thePlayer.inventory.armorInventory.length; ++var2) {
ItemStack var3 = this.mc.thePlayer.inventory.armorInventory[var2];
this.renderItemStack(var1, var2, var3);
}
}
}
public int getHeight() {
return 64;
}
static int DamageToColor(double var0) {
if (var0 > 1.0D) {
var0 = 1.0D;
} else if (var0 < 0.0D) {
var0 = 0.0D;
}
int var2 = (int)(255.0D * (1.0D - var0));
int var3 = (int)(255.0D * var0);
boolean var4 = false;
return (new Color(255, 255, 255)).getRGB();
}
private void renderItemStack(ScreenPosition var1, int var2, ItemStack var3) {
if (var3 != null) {
GL11.glPushMatrix();
int var4 = -16 * var2 + 48;
if (var3.getItem().isDamageable()) {
double var5 = (double)(var3.getMaxDamage() - var3.getItemDamage()) / (double)var3.getMaxDamage() * 100.0D;
if (Text.contains("on")) {
this.font.drawStringWithShadow(String.format("%.2f%%", var5), (float)(var1.getAbsoluteX() + 20), (float)(var1.getAbsoluteY() + var4 + 5), DamageToColor(var5 / 100.0D));
}
}
RenderHelper.enableGUIStandardItemLighting();
this.mc.getRenderItem().renderItemAndEffectIntoGUI(var3, var1.getAbsoluteX(), var1.getAbsoluteY() + var4);
GL11.glPopMatrix();
}
}
}
|
BTWS2/dodona
|
config/application.rb
|
require_relative "boot"
require "rails/all"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Dodona
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.1
config.dodona_email = '<EMAIL>'
# Configuration for the application, engines, and railties goes here.
#
# These settings can be overridden in specific environments using the files
# in config/environments, which are processed later.
#
# Application hosts
# The main webapp
config.default_host = 'dodona.localhost'
# The sandboxed host with user provided content, without authentication
config.sandbox_host = 'sandbox.localhost'
config.tutor_url = URI::HTTP.build(host: 'tutor.localhost', port: 8080, path: "/cgi-bin/build_trace.py")
# Where we host our assets (a single domain, for caching)
# Port is needed somehow...
config.action_controller.asset_host = 'dodona.localhost:3000'
config.time_zone = 'Brussels'
config.i18n.available_locales = %w[en nl]
config.i18n.default_locale = :nl
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
config.eager_load_paths += Dir[Rails.root.join('app', 'helpers', 'renderers')]
config.eager_load_paths += Dir[Rails.root.join('app', 'models', 'transient')]
config.active_job.queue_adapter = :delayed_job
config.active_storage.queues.analysis = :default
config.active_storage.queues.purge = :default
config.action_view.default_form_builder = "StandardFormBuilder"
end
end
|
bio-nim/pbbam
|
src/XmlReader.cpp
|
<gh_stars>0
#include "PbbamInternalConfig.h"
#include "XmlReader.h"
#include <cassert>
#include <istream>
#include <memory>
#include <stdexcept>
#include <typeinfo>
#include <vector>
#include <pbbam/StringUtilities.h>
#include "pugixml/pugixml.hpp"
using DataSetElement = PacBio::BAM::internal::DataSetElement;
using FromInputXml = PacBio::BAM::internal::FromInputXml;
namespace PacBio {
namespace BAM {
namespace {
std::unique_ptr<DataSetBase> MakeDataSetBase(const pugi::xml_node& xmlNode)
{
const FromInputXml fromInputXml{};
std::string name = xmlNode.name();
const auto foundColon = name.find(':');
if (foundColon != std::string::npos) {
name = name.substr(foundColon + 1);
}
const auto type = ElementTypeFromName(name);
switch (type) {
case XmlElementType::ALIGNMENT_SET:
return std::make_unique<AlignmentSet>(fromInputXml);
case XmlElementType::BARCODE_SET:
return std::make_unique<BarcodeSet>(fromInputXml);
case XmlElementType::CONSENSUS_ALIGNMENT_SET:
return std::make_unique<ConsensusAlignmentSet>(fromInputXml);
case XmlElementType::CONSENSUS_READ_SET:
return std::make_unique<ConsensusReadSet>(fromInputXml);
case XmlElementType::CONTIG_SET:
return std::make_unique<ContigSet>(fromInputXml);
case XmlElementType::HDF_SUBREAD_SET:
return std::make_unique<HdfSubreadSet>(fromInputXml);
case XmlElementType::REFERENCE_SET:
return std::make_unique<ReferenceSet>(fromInputXml);
case XmlElementType::SUBREAD_SET:
return std::make_unique<SubreadSet>(fromInputXml);
case XmlElementType::TRANSCRIPT_SET:
return std::make_unique<TranscriptSet>(fromInputXml);
case XmlElementType::TRANSCRIPT_ALIGNMENT_SET:
return std::make_unique<TranscriptAlignmentSet>(fromInputXml);
case XmlElementType::GENERIC_DATASET:
return std::make_unique<DataSetBase>(fromInputXml);
default:
// unreachable
throw std::runtime_error{"[pbbam] XML reader ERROR: unknown data set label: " + name};
}
}
std::shared_ptr<DataSetElement> MakeElement(const pugi::xml_node& xmlNode)
{
std::string name = xmlNode.name();
const auto foundColon = name.find(':');
if (foundColon != std::string::npos) {
name = name.substr(foundColon + 1);
}
const FromInputXml fromInputXml{};
const auto type = ElementTypeFromName(name);
switch (type) {
case XmlElementType::AUTOMATION:
return std::make_shared<Automation>(fromInputXml);
case XmlElementType::AUTOMATION_PARAMETER:
return std::make_shared<AutomationParameter>(fromInputXml);
case XmlElementType::AUTOMATION_PARAMETERS:
return std::make_shared<AutomationParameters>(fromInputXml);
case XmlElementType::BINDING_KIT:
return std::make_shared<BindingKit>(fromInputXml);
case XmlElementType::BIOSAMPLE:
return std::make_shared<BioSample>("", fromInputXml);
case XmlElementType::BIOSAMPLES:
return std::make_shared<BioSamples>(fromInputXml);
case XmlElementType::COLLECTIONS:
return std::make_shared<Collections>(fromInputXml);
case XmlElementType::COLLECTION_METADATA:
return std::make_shared<CollectionMetadata>(fromInputXml);
case XmlElementType::CONTROL_KIT:
return std::make_shared<ControlKit>(fromInputXml);
case XmlElementType::DATASET_METADATA:
return std::make_shared<DataSetMetadata>(fromInputXml);
case XmlElementType::DNA_BARCODE:
return std::make_shared<DNABarcode>("", fromInputXml);
case XmlElementType::DNA_BARCODES:
return std::make_shared<DNABarcodes>(fromInputXml);
case XmlElementType::EXTENSION:
return std::make_shared<ExtensionElement>(fromInputXml);
case XmlElementType::EXTENSIONS:
return std::make_shared<Extensions>(fromInputXml);
case XmlElementType::EXTERNAL_RESOURCE:
return std::make_shared<ExternalResource>("", "", fromInputXml);
case XmlElementType::EXTERNAL_RESOURCES:
return std::make_shared<ExternalResources>(fromInputXml);
case XmlElementType::FILE_INDEX:
return std::make_shared<FileIndex>("", "", fromInputXml);
case XmlElementType::FILE_INDICES:
return std::make_shared<FileIndices>(fromInputXml);
case XmlElementType::FILTER:
return std::make_shared<Filter>(fromInputXml);
case XmlElementType::FILTERS:
return std::make_shared<Filters>(fromInputXml);
case XmlElementType::PARENT_TOOL:
return std::make_shared<ParentTool>(fromInputXml);
case XmlElementType::PPACONFIG:
return std::make_shared<PPAConfig>(fromInputXml);
case XmlElementType::PROPERTY:
return std::make_shared<Property>("", "", "", fromInputXml);
case XmlElementType::PROPERTIES:
return std::make_shared<Properties>(fromInputXml);
case XmlElementType::PROVENANCE:
return std::make_shared<Provenance>(fromInputXml);
case XmlElementType::SEQUENCING_KIT_PLATE:
return std::make_shared<SequencingKitPlate>(fromInputXml);
case XmlElementType::TEMPLATE_PREP_KIT:
return std::make_shared<TemplatePrepKit>(fromInputXml);
case XmlElementType::ALIGNMENT_SET:
return std::make_shared<AlignmentSet>(fromInputXml);
case XmlElementType::BARCODE_SET:
return std::make_shared<BarcodeSet>(fromInputXml);
case XmlElementType::CONSENSUS_ALIGNMENT_SET:
return std::make_shared<ConsensusAlignmentSet>(fromInputXml);
case XmlElementType::CONSENSUS_READ_SET:
return std::make_shared<ConsensusReadSet>(fromInputXml);
case XmlElementType::CONTIG_SET:
return std::make_shared<ContigSet>(fromInputXml);
case XmlElementType::HDF_SUBREAD_SET:
return std::make_shared<HdfSubreadSet>(fromInputXml);
case XmlElementType::SUBREAD_SET:
return std::make_shared<SubreadSet>(fromInputXml);
case XmlElementType::REFERENCE_SET:
return std::make_shared<ReferenceSet>(fromInputXml);
case XmlElementType::TRANSCRIPT_SET:
return std::make_shared<TranscriptSet>(fromInputXml);
case XmlElementType::TRANSCRIPT_ALIGNMENT_SET:
return std::make_shared<TranscriptAlignmentSet>(fromInputXml);
case XmlElementType::SUBDATASETS:
return std::make_shared<SubDataSets>(fromInputXml);
case XmlElementType::GENERIC_DATASET:
return std::make_shared<DataSetBase>(fromInputXml);
case XmlElementType::GENERIC_ELEMENT:
return std::make_shared<DataSetElement>(name, fromInputXml);
default:
// unreachable
throw std::runtime_error{"[pbbam] XML reader ERROR: unknown data element label: " +
name};
}
}
void UpdateRegistry(const std::string& attributeName, const std::string& attributeValue,
NamespaceRegistry& registry)
{
std::vector<std::string> nameParts = Split(attributeName, ':');
assert(!nameParts.empty());
if (nameParts.size() > 2)
throw std::runtime_error{"[pbbam] XML reader ERROR: malformed xmlns attribute: " +
attributeName};
const bool isDefault = (nameParts.size() == 1);
const XsdType xsd = registry.XsdForUri(attributeValue);
if (isDefault)
registry.SetDefaultXsd(xsd);
else {
assert(nameParts.size() == 2);
const std::string& name = nameParts.at(1);
const std::string& uri = attributeValue;
NamespaceInfo namespaceInfo(name, uri);
registry.Register(xsd, namespaceInfo);
}
}
void FromXml(const pugi::xml_node& xmlNode, DataSetElement& parent)
{
// ignore non-named XML nodes
//
// pugi::xml separates XML parts into more node types than we use
//
const std::string label = xmlNode.name();
if (label.empty()) return;
auto e = MakeElement(xmlNode);
e->Label(xmlNode.name());
e->Text(xmlNode.text().get());
// iterate attributes
auto attrIter = xmlNode.attributes_begin();
auto attrEnd = xmlNode.attributes_end();
for (; attrIter != attrEnd; ++attrIter)
e->Attribute(attrIter->name(), attrIter->value());
// iterate children, recursively building up subtree
auto childIter = xmlNode.begin();
auto childEnd = xmlNode.end();
for (; childIter != childEnd; ++childIter) {
pugi::xml_node childNode = *childIter;
FromXml(childNode, *e.get());
}
parent.AddChild(e);
}
} // namespace
std::unique_ptr<DataSetBase> XmlReader::FromStream(std::istream& in)
{
pugi::xml_document doc;
const pugi::xml_parse_result loadResult = doc.load(in);
if (!loadResult) {
throw std::runtime_error{
"[pbbam] XML reader ERROR: could not read XML document\n"
" reason: " +
std::string{loadResult.description()}};
}
// parse top-level attributes
pugi::xml_node rootNode = doc.document_element();
if (rootNode == pugi::xml_node())
throw std::runtime_error{"[pbbam] XML reader ERROR: could not fetch XML root node"};
// create dataset matching type strings
auto dataset = MakeDataSetBase(rootNode);
dataset->Label(rootNode.name());
// iterate attributes, capture namespace info
const std::string xmlnsPrefix("xmlns");
auto attrIter = rootNode.attributes_begin();
auto attrEnd = rootNode.attributes_end();
for (; attrIter != attrEnd; ++attrIter) {
const std::string name = attrIter->name();
const std::string value = attrIter->value();
dataset->Attribute(name, value);
if (name.find(xmlnsPrefix) == 0) {
UpdateRegistry(name, value, dataset->Namespaces());
}
}
// iterate children, recursively building up subtree
auto childIter = rootNode.begin();
auto childEnd = rootNode.end();
for (; childIter != childEnd; ++childIter) {
pugi::xml_node childNode = *childIter;
FromXml(childNode, *dataset.get());
}
return dataset;
}
} // namespace BAM
} // namespace PacBio
|
bdutro-sv/map
|
sparta/sparta/report/format/PythonDict.hpp
|
// <PythonDict> -*- C++ -*-
/*!
* \file PythonDict.hpp
* \brief PythonDict Report output formatter
*/
#ifndef __SPARTA_REPORT_FORMAT_PYTHONDICT_H__
#define __SPARTA_REPORT_FORMAT_PYTHONDICT_H__
#include <iostream>
#include <sstream>
#include <math.h>
#include "sparta/report/format/BaseOstreamFormatter.hpp"
#include "sparta/utils/SpartaException.hpp"
#include "sparta/utils/SpartaAssert.hpp"
namespace sparta
{
namespace report
{
namespace format
{
/*!
* \brief Report formatter for PythonDict output
* \note Non-Copyable
*/
class PythonDict : public BaseOstreamFormatter
{
public:
/*!
* \brief Constructor
* \param r Report to provide output formatting for
* \param output Osteram to write to when write() is called
*/
PythonDict(const Report* r, std::ostream& output) :
BaseOstreamFormatter(r, output)
{ }
/*!
* \brief Constructor
* \param r Report to provide output formatting for
* \param filename File which will be opened and appended to when write() is
* called
* \param mode. Optional open mode. Should be std::ios::out or
* std::ios::app. Other values cause undefined behavior
*/
PythonDict(const Report* r,
const std::string& filename,
std::ios::openmode mode=std::ios::app) :
BaseOstreamFormatter(r, filename, mode)
{ }
/*!
* \brief Constructor
* \param r Report to provide output formatting for
*/
PythonDict(const Report* r) :
BaseOstreamFormatter(r)
{ }
/*!
* \brief Virtual Destructor
*/
virtual ~PythonDict()
{
}
protected:
//! \name Output
//! @{
////////////////////////////////////////////////////////////////////////
/*!
* \brief Writes a header to some output based on the report
*/
virtual void writeHeaderToStream_(std::ostream& out) const override {
(void) out;
}
/*!
* \brief Writes the content of this report to some output
*/
virtual void writeContentToStream_(std::ostream& out) const override
{
out << "{" ;
writeDictContents_(out, report_, 1);
out << "}" ;
out << std::endl;
}
////////////////////////////////////////////////////////////////////////
//! @}
/*!
* \brief Write Python Dictionary
*/
int writeDictContents_(std::ostream& out, const Report* r, int idx) const
{
out << "\"" << r->getName() << "\"" << ": {" ;
int elements_=0;
for (const Report::stat_pair_t& si : r->getStatistics()) {
if(si.first != ""){
if(elements_ > 0){
out << ", ";
}
out << "\"" << si.first << "\": " ;
double val = si.second->getValue();
if(isnan(val)){
out << "float('nan')";
}else if(isinf(val)){
out << "float('inf')";
}else{
out << Report::formatNumber(val);
}
elements_++;
}
}
for (const Report& sr : r->getSubreports()) {
if(elements_ > 0){
out << ", ";
}
writeDictContents_(out, &sr, idx);
elements_++;
}
out << "}" ;
return idx;
}
};
//! \brief PythonDict stream operator
inline std::ostream& operator<< (std::ostream& out, PythonDict & f) {
out << &f;
return out;
}
} // namespace format
} // namespace report
} // namespace sparta
// __SPARTA_REPORT_FORMAT_PYTHONDICT_H__
#endif
|
axetang/AxeCoding
|
Golang/gopkg/fmt/fmt.f.Fprintln.go
|
/************************************************************************************
**Author: <NAME>; Email: <EMAIL>
**Package: fmt
**Element: fmt.Fprintln
**Type: func
------------------------------------------------------------------------------------
**Definition:
func Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
------------------------------------------------------------------------------------
**Description:
Fprintln formats using the default formats for its operands and writes to w. Spaces
are always added between operands and a newline is appended. It returns the number
of bytes written and any write error encountered.
------------------------------------------------------------------------------------
**要点总结:
1. 查看标准包源码,Fprintln定义和实现如下,Fprintln把参数a切片中的值按照缺省格式写入io.Writer
接口实例,操作符之间自动添加空格,最后增加一个换行,并返回写入的字节数
func Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
p := newPrinter()
p.doPrintln(a)
n, err = w.Write(p.buf)
p.free()
return
}
2. Fprintln调用了fmt包的私有函数newPrinter和doPrintln,查阅标准包源代码,两个函数定义如下。其中,
doPrintln函数是pp类型的方法,pp类型定义也一并列出如下;
func newPrinter() *pp {
p := ppFree.Get().(*pp)
p.panicking = false
p.erroring = false
p.fmt.init(&p.buf)
return p
}
func (p *pp) doPrintln(a []interface{}) {
for argNum, arg := range a {
if argNum > 0 {
p.buf.WriteByte(' ')
}
p.printArg(arg, 'v')
}
p.buf.WriteByte('\n')
}
type pp struct {
buf buffer
// arg holds the current item, as an interface{}.
arg interface{}
// value is used instead of arg for reflect values.
value reflect.Value
// fmt is used to format basic items such as integers or strings.
fmt fmt
// reordered records whether the format string used argument reordering.
reordered bool
// goodArgNum records whether the most recent reordering directive was valid.
goodArgNum bool
// panicking is set by catchPanic to avoid infinite panic, recover, panic, ... recursion.
panicking bool
// erroring is set when printing an error string to guard against calling handleMethods.
erroring bool
}
*************************************************************************************/
package main
import (
"fmt"
"os"
)
func main() {
i := 0
str := "abc"
t := true
fmt.Fprintln(os.Stdout, i, str, t)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.