code
stringlengths 4
1.01M
| language
stringclasses 2
values |
|---|---|
# Syntriandrum Engl. GENUS
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
# Tradescantia harbisonii Bush SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
# Chondria decidua Tani & Masuda, 2003 SPECIES
#### Status
ACCEPTED
#### According to
World Register of Marine Species
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
# Depazea erdingeri Thüm. SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Depazea erdingeri Thüm.
### Remarks
null
|
Java
|
# Callaeolepium warscewiczii Karst. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
# Arctium concolor Kuntze SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
# Vincetoxicum raddeanum Albov SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
# Salacia obovata var. obovata VARIETY
#### Status
ACCEPTED
#### According to
NUB Generator [autonym]
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
function buildName(firstName = "Will", lastName: string) {
return firstName + " " + lastName;
}
let result1 = buildName("Bob"); // error, too few parameters
let result2 = buildName("Bob", "Adams", "Sr."); // error, too many parameters
let result3 = buildName("Bob", "Adams"); // okay and returns "Bob Adams"
let result4 = buildName(undefined, "Adams"); // okay and returns "Will Adams"
|
Java
|
#!/usr/bin/env ruby
require 'erb'
require 'json'
require 'optparse'
@target = nil
@users = 1
@concurrency = 1
@maxrate = 10
@maxhits = nil
OptionParser.new do | opts |
opts.banner = "Usage: generate.rb [options] target"
opts.on('--target [string]', "Specify the target server for requests (required)") do | v |
@target = v.split(':')
end
opts.on('--virtual-users [int]', Integer, "Specify the number of virtual users (default: #{@users})") do | v |
@users = v
end
opts.on('--virtual-user-clones [int]', Integer, "Specify the number of each virtual user clones (default: #{@concurrency})") do | v |
@concurrency = v
end
opts.on('--max-request-rate [float]', Float, "Specify the maximum requests per minute (default: #{@maxrate})") do | v |
@maxrate = v
end
opts.on('--max-hits [int]', Integer, "Maximum number of hits to generate jmeter requests (default: #{@maxhits})") do | v |
@maxhits = v
end
opts.on('-h', '--help', 'Display this help') do
puts opts
exit
end
end.parse!
raise OptionParser::InvalidOption if @target.nil?
json = JSON.parse ARGF.read
@buckets = Array.new(@users) { Array.new }
json['hits']['hits'].each_with_index do | hit, i |
next if not @maxhits.nil? and i > @maxhits
source = hit['_source']
next if '/_bulk' == source['path']
@buckets[i % @users].push(
{
:id => hit['_index'] + ':' + hit['_id'],
:method => source['method'],
:path => source['path'],
:querydata => source['querystr'],
:requestdata => source['data'],
}
)
end
template = ERB.new File.new("jmeter.jmx.erb").read, nil, "%"
puts template.result(binding)
|
Java
|
# Buchnera floridana Gand. SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Bull. Soc. Bot. France 66:217. 1919
#### Original name
null
### Remarks
null
|
Java
|
/*
* @(#)TIFFHeader.java
*
* $Date: 2014-03-13 04:15:48 -0400 (Thu, 13 Mar 2014) $
*
* Copyright (c) 2011 by Jeremy Wood.
* All rights reserved.
*
* The copyright of this software is owned by Jeremy Wood.
* You may not use, copy or modify this software, except in
* accordance with the license agreement you entered into with
* Jeremy Wood. For details see accompanying license terms.
*
* This software is probably, but not necessarily, discussed here:
* https://javagraphics.java.net/
*
* That site should also contain the most recent official version
* of this software. (See the SVN repository for more details.)
*
Modified BSD License
Copyright (c) 2015, Jeremy Wood.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* The name of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission.
*
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package gr.iti.mklab.reveal.forensics.util.ThumbnailExtractor.image.jpeg;
import java.io.IOException;
import java.io.InputStream;
class TIFFHeader {
boolean bigEndian;
int ifdOffset;
TIFFHeader(InputStream in) throws IOException {
byte[] array = new byte[4];
if(JPEGMarkerInputStream.readFully(in, array, 2, false)!=2) {
throw new IOException("Incomplete TIFF Header");
}
if(array[0]==73 && array[1]==73) { //little endian
bigEndian = false;
} else if(array[0]==77 && array[1]==77) { //big endian
bigEndian = true;
} else {
throw new IOException("Unrecognized endian encoding.");
}
if(JPEGMarkerInputStream.readFully(in, array, 2, !bigEndian)!=2) {
throw new IOException("Incomplete TIFF Header");
}
if(!(array[0]==0 && array[1]==42)) { //required byte in TIFF header
throw new IOException("Missing required identifier 0x002A.");
}
if(JPEGMarkerInputStream.readFully(in, array, 4, !bigEndian)!=4) {
throw new IOException("Incomplete TIFF Header");
}
ifdOffset = ((array[0] & 0xff) << 24) + ((array[1] & 0xff) << 16) +
((array[2] & 0xff) << 8) + ((array[3] & 0xff) << 0) ;
}
/** The length of this TIFF header. */
int getLength() {
return 8;
}
}
|
Java
|
<?php
use App\Models\Post;
use Illuminate\Support\Facades\DB;
use Test\Factory;
use Test\TestCase;
class PostControllerTest extends TestCase {
public function setUp() {
parent::setUp();
DB::table('posts')->delete();
$this->user = Factory::create('user');
$this->be($this->user);
}
public function testIndex()
{
$this->call('GET', 'posts');
$this->assertResponseOk();
$this->assertViewHas('posts');
}
public function testCreate()
{
$this->call('GET', 'posts/create');
$this->assertResponseOk();
}
public function testStore()
{
$countPosts = Post::count();
$inputs = [
'title' => 'title POst',
'content' => 'Content posts'
];
$this->call('POST', 'posts', $inputs);
$this->assertEquals($countPosts + 1, Post::count());
$this->assertRedirectedTo('/posts');
}
public function testEdit()
{
$post = Factory::create('post');
$this->call('GET', 'posts/'.$post->id.'/edit');
$this->assertResponseOk();
}
public function testUpdate()
{
$oldTitle = 'Old title';
$newTitle = 'New title';
$post = Factory::create('post', ['title' => $oldTitle]);
$inputs = [
'title' => $newTitle,
];
$this->shouldRedirectBack();
$this->call('PUT', 'posts/'.$post->id, $inputs);
$freshPost = Post::find($post->id);
$this->assertEquals($newTitle, $freshPost->title);
}
public function testDestroy()
{
$post = Factory::create('post');
$countPosts = Post::count();
$this->shouldRedirectBack();
$this->call('DELETE', 'posts/'.$post->id);
$this->assertEquals($countPosts - 1, Post::count());
}
}
|
Java
|
/**
*
*/
/**
* @author root
*
*/
package com.amanaje.activities;
|
Java
|
package eu.ailao.hub.dialog;
import eu.ailao.hub.corefresol.answers.ClueMemorizer;
import eu.ailao.hub.corefresol.concepts.ConceptMemorizer;
import eu.ailao.hub.questions.Question;
import java.util.ArrayList;
/**
* Created by Petr Marek on 24.02.2016.
* Dialog class represents dialog. It contains id of dialog and ids of questions in this dialog.
*/
public class Dialog {
private int id;
private ArrayList<Question> questionsOfDialogue;
private ConceptMemorizer conceptMemorizer;
private ClueMemorizer clueMemorizer;
public Dialog(int id) {
this.id = id;
this.questionsOfDialogue = new ArrayList<>();
this.conceptMemorizer = new ConceptMemorizer();
this.clueMemorizer = new ClueMemorizer();
}
/**
* Adds question to dialog
* @param questionID id of question
*/
public void addQuestion(Question questionID) {
questionsOfDialogue.add(questionID);
}
public ArrayList<Question> getQuestions() {
return questionsOfDialogue;
}
/**
* Gets all question's ids of dialog
* @return array list of question's ids in dialog
*/
public ArrayList<Integer> getQuestionsIDs() {
ArrayList<Integer> questionIDs = new ArrayList<Integer>();
for (int i = 0; i < questionsOfDialogue.size(); i++) {
questionIDs.add(questionsOfDialogue.get(i).getYodaQuestionID());
}
return questionIDs;
}
public int getId() {
return id;
}
public ConceptMemorizer getConceptMemorizer() {
return conceptMemorizer;
}
public ClueMemorizer getClueMemorizer() {
return clueMemorizer;
}
public boolean hasQuestionWithId(int id) {
for (Question question : questionsOfDialogue) {
if (question.getYodaQuestionID() == id) {
return true;
}
}
return false;
}
}
|
Java
|
// Copyright 2016 Yahoo Inc.
// Licensed under the terms of the Apache license. Please see LICENSE.md file distributed with this work for terms.
package com.yahoo.bard.webservice.data.metric;
/**
* LogicalMetricColumn.
*/
public class LogicalMetricColumn extends MetricColumn {
private final LogicalMetric metric;
/**
* Constructor.
*
* @param name The column name
* @param metric The logical metric
*
* @deprecated because LogicalMetricColumn is really only a thing for LogicalTable, so there's no reason for there
* to be an alias on the LogicalMetric inside the LogicalTableSchema.
*/
@Deprecated
public LogicalMetricColumn(String name, LogicalMetric metric) {
super(name);
this.metric = metric;
}
/**
* Constructor.
*
* @param metric The logical metric
*/
public LogicalMetricColumn(LogicalMetric metric) {
super(metric.getName());
this.metric = metric;
}
/**
* Getter for a logical metric.
*
* @return logical metric
*/
public LogicalMetric getLogicalMetric() {
return this.metric;
}
@Override
public String toString() {
return "{logicalMetric:'" + getName() + "'}";
}
}
|
Java
|
require 'tpaga'
Tpaga::Swagger.configure do |config|
config.scheme = 'https'
config.host = 'sandbox.tpaga.co'
config.base_path = '/api'
config.inject_format = false
config.api_key = ENV["TPAGA_API_KEY"]
end
|
Java
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Belkyra</title>
<!-- Bootstrap Core CSS -->
<link href="../css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="../css/services.css" rel="stylesheet">
<!-- Import fonts -->
<link href="https://fonts.googleapis.com/css?family=Alegreya+Sans+SC|Open+Sans" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<!-- contact-bar -->
<div class="contact-bar container">
<div class="contact-info">
<div class="phone-number">
<a id="facebook-icon" href="https://www.facebook.com/mdlaserskinclinic">
<img width="20px" height="20px" src="https://cdn1.iconfinder.com/data/icons/logotypes/32/square-facebook-512.png">
</a>
<p>416-445-7546</p>
</div>
</div>
</div>
<div class="container">
<div class="navbar-header page-scroll">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<div class="navbar-header">
<a class= "navbar-brand logo page-scroll" href="../index.html"> <img id="MD-logo" alt="logo" src="../css/imgs/logo.png"> </a>
<a id="title" class= "navbar-brand text page-scroll" href="../index.html"> Laser Skin Clinic </br> and medi-spa </a>
</div>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav navbar-right">
<!-- Hidden li included to remove active class from about link when scrolled up past about section -->
<li class="hidden">
<a class="page-scroll" href="../index.html#page-top"></a>
</li>
<li>
<a class="page-scroll" href="../index.html#about">about</a>
</li>
<li>
<a class="page-scroll" href="../index.html#treatments">treatments</a>
</li>
<li>
<a class="page-scroll" href="../index.html#products">products</a>
</li>
<li>
<a class="page-scroll" href="../index.html#specials">specials</a>
</li>
<li>
<a class="page-scroll" href="../index.html#staff"> staff </a>
</li>
<li>
<a class="page-scroll" href="../index.html#contact">contact</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<div class="container information">
<div class="row">
<h1>BELKYRA®</h1>
<div class="col-sm-8">
<p class="description">BELKYRA® is an innovative injection treatment for both men and women who want to permanently reduce the appearance of a mild to moderate “double chin”, (that is, the fat area under the mandible), without surgery. BELKYRA® is the first and only Health Canada approved injectable treatment for this purpose, meeting research-based, safety requirements. It is not recommended for the treatment of severe fat accumulation in the chin and neck.
</p>
<br><br>
</div>
<div class="col-sm-4 photo">
<img src="../css/imgs/belkyra-add.png">
</div>
</div>
<div class="row">
<div class="faq col-sm-8">
<h3>How does BELKYRA® work?</h3>
<p>
The active ingredient in BELKYRA® is deoxycholic acid, a naturally occurring molecule in the body that aids in the breakdown and absorption of dietary fat. Once it is injected into the skin under the submental chin area, BELKYRA® targets and eliminates fat cells when injected into the area under your chin over a period of 6-8 weeks. Many patients treated with BELKYRA® experience visible improvement with 2 – 4 treatments. Very rarely, up to a maximum of 6 treatments are needed to achieve ideal results.
</p>
<br>
<h3>How is BELKYRA® administered?</h3>
<p>
BELKYRA® is given in a series of small injections into the skin under the chin, requiring about 15-20mins to complete. It is relatively painless, but some burning sensation within the first 15-20 mins is expected and desired.
</p>
<br>
<h3>What are the side effects and is there downtime?</h3>
<p>
For most people, the downtime is minimal and occurs most after the first treatment session. As with other injectible treatments, you may experience some post-op transient pain, bruising and numbness under the chin after the procedure. . In most cases, the use of ice packs will make the injection procedure completely tolerable without using topical anaesthetic creams. In clinical trials, mild burning pain after treatment was gone within 15-30 minutes of treatment.
<br>
However, the main side-effect from the procedure is immediate swelling in the area due to injecting fluid under the chin, and later, due to inflammation as the fat cells melt down and are disposed by the immune system. Therefore, it is important to expect that things will look worse, before it gets better. Given that the result is permanent without surgery, the side effects are insignificant.
</p>
<br>
<h3>How much does it cost?</h3>
<p>
BELKYRA® injections require a minimum of 2 to 4 treatments to have efficacy to reduce a double chin depending on the size of the area to be treated. The maximum number of treatments is six, according to the approved guidelines. At MD Laser Skin Clinic, we charge $2200 for the first 2 sessions (spaced 6-8 weeks apart), and $800 for any subsequent treatments, up to a maximum of 6.
</p>
<br>
<p>
For more information and an assessment if BELKYRA therapy is the right treatment for you, please call us for a consultation with our trained medical professional.
</p>
<a id="book-btn" href="../index.html#contact"><button type="button" class="btn btn-default"> Book Today </button></a>
</div>
<div class="treatments-menu col-sm-4">
<h3>More Treatments:</h3>
<ul>
<li><a href="botox-for-wrinkles.html">Botox Cosmetic®</a></li>
<li><a href="filler.html">Fillers</a></li>
<li><a href="botox-for-sweating.html">Botox Therapeutic® (exessive sweating)</a></li>
<li><a href="laser-IPL-hair-removal.html">Laser Hair Removal</a></li>
<li><a href="botox-for-tmjd.html">Botox Therapeutic® (TMJ muscle pain)</a></li>
<li><a href="microneedling.html">Microneedling</a></li>
<li><a href="medical-facials.html">Medical Facials</a></li>
<li><a href="IPL-photofacial.html">IPL Photofacial Rejuvenation</a></li>
<li><a href="chemical-peel.html">Chemical Peeling</a></li>
<li><a href="belkyra.html">Belkyra®</a></li>
</ul>
</div>
</div>
</div>
<footer>
<div class="row container">
<div class="col-md-4 nav">
<h4> MD Laser Skin Clinic</h4>
<a href="../index.html#about">About</a> </br>
<a href="../index.html#treatments">Treatments</a></br>
<a href="../index.html#products">Products</a></br>
<a href="../index.html#staff">Staff</a></br>
<a href="../index.html#specials">Specials</a></br>
<a href="../index.html#contact">Contact</a></br>
</div>
<div class="col-md-4 contact-info">
<h4>Contact Us</h4>
<p> Call: 416-445-7546</p>
<p> Email: smilestoronto@bellnet.ca</p>
<p id="trademark">BOTOX COSMETIC® is a registered trademark of Allergan Inc. <br>
LATISSE® is a registered trademark of Allergan Inc. <br>
SOFT LIFT™ is a trademark of Allergan Inc. <br>
JUVEDERM® is a registered trademark of Allergan Holdings France SAS <br>
VOLBELLA™ is a trademark of Allergan Inc. <br>
VOLUMA® is a registered trademark of Allergan Inc.
</p>
<a href="../disclaimer.html">disclaimer</a>
</div>
<div class="col-md-4 address">
<h4>Address</h4>
<p>1200 Lawrence Avenue East</p>
<p>Suite 204</p>
<p>North York, Ontario</p>
<p>M3A 1C1</p>
</div>
</div>
</footer>
<!-- jQuery -->
<script src="js/jquery.js"></script>
<script src="js/custom-jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<!-- Scrolling Nav JavaScript -->
<script src="js/jquery.easing.min.js"></script>
<script src="js/scrolling-nav.js"></script>
</body>
</html>
|
Java
|
package esidev
import (
"net/http"
"time"
"github.com/gorilla/mux"
)
var _ time.Time
var _ = mux.NewRouter
func GetIncursions(w http.ResponseWriter, r *http.Request) {
var (
localV interface{}
err error
datasource string
)
// shut up warnings
localV = localV
err = err
j := `[ {
"constellation_id" : 20000607,
"faction_id" : 500019,
"has_boss" : true,
"infested_solar_systems" : [ 30004148, 30004149, 30004150, 30004151, 30004152, 30004153, 30004154 ],
"influence" : 0.9,
"staging_solar_system_id" : 30004154,
"state" : "mobilizing",
"type" : "Incursion"
} ]`
if err := r.ParseForm(); err != nil {
errorOut(w, r, err)
return
}
if r.Form.Get("datasource") != "" {
localV, err = processParameters(datasource, r.Form.Get("datasource"))
if err != nil {
errorOut(w, r, err)
return
}
datasource = localV.(string)
}
if r.Form.Get("page") != "" {
var (
localPage int32
localIntPage interface{}
)
localIntPage, err := processParameters(localPage, r.Form.Get("page"))
if err != nil {
errorOut(w, r, err)
return
}
localPage = localIntPage.(int32)
if localPage > 1 {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte("[]"))
return
}
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(j))
}
|
Java
|
using System.Collections.Generic;
using RestSharp;
using SimpleJson;
namespace MoneySharp.Internal.Model
{
public class SalesInvoicePost : SalesInvoice
{
public IList<SalesInvoiceDetail> details_attributes { get; set; }
public JsonObject custom_fields_attributes { get; set; }
}
}
|
Java
|
package coop.ekologia.presentation.controller.user;
import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import coop.ekologia.presentation.EkologiaServlet;
import coop.ekologia.presentation.session.LoginSession;
/**
* Servlet implementation class LoginConnectionServlet
*/
@WebServlet(LoginDeconnectionServlet.routing)
public class LoginDeconnectionServlet extends EkologiaServlet {
private static final long serialVersionUID = 1L;
public static final String routing = "/login/deconnection";
public static final String routing(HttpServletRequest request) {
return getUrl(request, routing);
}
@Inject
LoginSession loginSession;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginDeconnectionServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
loginSession.setUser(null);
response.sendRedirect(request.getHeader("referer"));
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
|
Java
|
/*
* Copyright 2010-2020 Alfresco Software, Ltd.
*
* 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.activiti.engine.impl.cmd;
import java.io.InputStream;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.ActivitiObjectNotFoundException;
import org.activiti.engine.delegate.event.ActivitiEventType;
import org.activiti.engine.delegate.event.impl.ActivitiEventBuilder;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.AttachmentEntity;
import org.activiti.engine.impl.persistence.entity.ByteArrayEntity;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.util.IoUtil;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Attachment;
import org.activiti.engine.task.Task;
/**
*/
// Not Serializable
public class CreateAttachmentCmd implements Command<Attachment> {
protected String attachmentType;
protected String taskId;
protected String processInstanceId;
protected String attachmentName;
protected String attachmentDescription;
protected InputStream content;
protected String url;
public CreateAttachmentCmd(String attachmentType, String taskId, String processInstanceId, String attachmentName, String attachmentDescription, InputStream content, String url) {
this.attachmentType = attachmentType;
this.taskId = taskId;
this.processInstanceId = processInstanceId;
this.attachmentName = attachmentName;
this.attachmentDescription = attachmentDescription;
this.content = content;
this.url = url;
}
public Attachment execute(CommandContext commandContext) {
if (taskId != null) {
verifyTaskParameters(commandContext);
}
if (processInstanceId != null) {
verifyExecutionParameters(commandContext);
}
return executeInternal(commandContext);
}
protected Attachment executeInternal(CommandContext commandContext) {
AttachmentEntity attachment = commandContext.getAttachmentEntityManager().create();
attachment.setName(attachmentName);
attachment.setProcessInstanceId(processInstanceId);
attachment.setTaskId(taskId);
attachment.setDescription(attachmentDescription);
attachment.setType(attachmentType);
attachment.setUrl(url);
attachment.setUserId(Authentication.getAuthenticatedUserId());
attachment.setTime(commandContext.getProcessEngineConfiguration().getClock().getCurrentTime());
commandContext.getAttachmentEntityManager().insert(attachment, false);
if (content != null) {
byte[] bytes = IoUtil.readInputStream(content, attachmentName);
ByteArrayEntity byteArray = commandContext.getByteArrayEntityManager().create();
byteArray.setBytes(bytes);
commandContext.getByteArrayEntityManager().insert(byteArray);
attachment.setContentId(byteArray.getId());
attachment.setContent(byteArray);
}
commandContext.getHistoryManager().createAttachmentComment(taskId, processInstanceId, attachmentName, true);
if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
// Forced to fetch the process-instance to associate the right
// process definition
String processDefinitionId = null;
if (attachment.getProcessInstanceId() != null) {
ExecutionEntity process = commandContext.getExecutionEntityManager().findById(processInstanceId);
if (process != null) {
processDefinitionId = process.getProcessDefinitionId();
}
}
commandContext.getProcessEngineConfiguration().getEventDispatcher()
.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_CREATED, attachment, processInstanceId, processInstanceId, processDefinitionId));
commandContext.getProcessEngineConfiguration().getEventDispatcher()
.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_INITIALIZED, attachment, processInstanceId, processInstanceId, processDefinitionId));
}
return attachment;
}
protected TaskEntity verifyTaskParameters(CommandContext commandContext) {
TaskEntity task = commandContext.getTaskEntityManager().findById(taskId);
if (task == null) {
throw new ActivitiObjectNotFoundException("Cannot find task with id " + taskId, Task.class);
}
if (task.isSuspended()) {
throw new ActivitiException("It is not allowed to add an attachment to a suspended task");
}
return task;
}
protected ExecutionEntity verifyExecutionParameters(CommandContext commandContext) {
ExecutionEntity execution = commandContext.getExecutionEntityManager().findById(processInstanceId);
if (execution == null) {
throw new ActivitiObjectNotFoundException("Process instance " + processInstanceId + " doesn't exist", ProcessInstance.class);
}
if (execution.isSuspended()) {
throw new ActivitiException("It is not allowed to add an attachment to a suspended process instance");
}
return execution;
}
}
|
Java
|
//
// WebViewPushController.h
// Tools
//
// Created by 张书孟 on 2018/4/16.
// Copyright © 2018年 张书孟. All rights reserved.
//
#import "BaseViewController.h"
@interface WebViewPushController : BaseViewController
@property (nonatomic, strong) NSString *url;
@end
|
Java
|
package org.seasar.doma.internal.jdbc.dialect;
import org.seasar.doma.internal.jdbc.sql.SimpleSqlNodeVisitor;
import org.seasar.doma.internal.jdbc.sql.node.AnonymousNode;
import org.seasar.doma.jdbc.SqlNode;
public class StandardCountCalculatingTransformer extends SimpleSqlNodeVisitor<SqlNode, Void> {
protected boolean processed;
public SqlNode transform(SqlNode sqlNode) {
AnonymousNode result = new AnonymousNode();
for (SqlNode child : sqlNode.getChildren()) {
result.appendNode(child.accept(this, null));
}
return result;
}
@Override
protected SqlNode defaultAction(SqlNode node, Void p) {
return node;
}
}
|
Java
|
# Boopis scapigera var. ventosa (Meyen) Wedd. VARIETY
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
# Phaeosphaeria juncicola (Rehm ex G. Winter) L. Holm, 1957 SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Symb. bot. upsal. 14(no. 3): 129 (1957)
#### Original name
Leptosphaeria juncicola Rehm, 1879
### Remarks
null
|
Java
|
<div class="uk-width-1-4@m">
<div class="uk-card uk-card-default uk-card-body uk-margin-large-bottom">
<h3 class="uk-panel-title">分类</h3>
<ul class="uk-list uk-list-line">
<li><a href="#">PHP</a></li>
<li><a href="#">Javascript</a></li>
</ul>
</div>
<div class="uk-card uk-card-default uk-card-body">
<h3 class="uk-panel-title">友情链接</h3>
<ul class="uk-list">
</ul>
</div>
</div>
|
Java
|
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* COPYRIGHT (C) 2007
* THE REGENTS OF THE UNIVERSITY OF MICHIGAN
* ALL RIGHTS RESERVED
*
* Permission is granted to use, copy, create derivative works
* and redistribute this software and such derivative works
* for any purpose, so long as the name of The University of
* Michigan is not used in any advertising or publicity
* pertaining to the use of distribution of this software
* without specific, written prior authorization. If the
* above copyright notice or any other identification of the
* University of Michigan is included in any copy of any
* portion of this software, then the disclaimer below must
* also be included.
*
* THIS SOFTWARE IS PROVIDED AS IS, WITHOUT REPRESENTATION
* FROM THE UNIVERSITY OF MICHIGAN AS TO ITS FITNESS FOR ANY
* PURPOSE, AND WITHOUT WARRANTY BY THE UNIVERSITY OF
* MICHIGAN OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
* WITHOUT LIMITATION THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
* REGENTS OF THE UNIVERSITY OF MICHIGAN SHALL NOT BE LIABLE
* FOR ANY DAMAGES, INCLUDING SPECIAL, INDIRECT, INCIDENTAL, OR
* CONSEQUENTIAL DAMAGES, WITH RESPECT TO ANY CLAIM ARISING
* OUT OF OR IN CONNECTION WITH THE USE OF THE SOFTWARE, EVEN
* IF IT HAS BEEN OR IS HEREAFTER ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
*/
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <regex.h>
#include "pkinit.h"
typedef struct _pkinit_cert_info pkinit_cert_info;
typedef enum {
kw_undefined = 0,
kw_subject = 1,
kw_issuer = 2,
kw_san = 3,
kw_eku = 4,
kw_ku = 5
} keyword_type;
static char *
keyword2string(unsigned int kw)
{
switch(kw) {
case kw_undefined: return "NONE"; break;
case kw_subject: return "SUBJECT"; break;
case kw_issuer: return "ISSUER"; break;
case kw_san: return "SAN"; break;
case kw_eku: return "EKU"; break;
case kw_ku: return "KU"; break;
default: return "INVALID"; break;
}
}
typedef enum {
relation_none = 0,
relation_and = 1,
relation_or = 2
} relation_type;
static char *
relation2string(unsigned int rel)
{
switch(rel) {
case relation_none: return "NONE"; break;
case relation_and: return "AND"; break;
case relation_or: return "OR"; break;
default: return "INVALID"; break;
}
}
typedef enum {
kwvaltype_undefined = 0,
kwvaltype_regexp = 1,
kwvaltype_list = 2
} kw_value_type;
static char *
kwval2string(unsigned int kwval)
{
switch(kwval) {
case kwvaltype_undefined: return "NONE"; break;
case kwvaltype_regexp: return "REGEXP"; break;
case kwvaltype_list: return "LIST"; break;
default: return "INVALID"; break;
}
}
struct keyword_desc {
const char *value;
size_t length;
keyword_type kwtype;
kw_value_type kwvaltype;
} matching_keywords[] = {
{ "<KU>", 4, kw_ku, kwvaltype_list },
{ "<EKU>", 5, kw_eku, kwvaltype_list },
{ "<SAN>", 5, kw_san, kwvaltype_regexp },
{ "<ISSUER>", 8, kw_issuer, kwvaltype_regexp },
{ "<SUBJECT>", 9, kw_subject, kwvaltype_regexp },
{ NULL, 0, kw_undefined, kwvaltype_undefined},
};
struct ku_desc {
const char *value;
size_t length;
unsigned int bitval;
};
struct ku_desc ku_keywords[] = {
{ "digitalSignature", 16, PKINIT_KU_DIGITALSIGNATURE },
{ "keyEncipherment", 15, PKINIT_KU_KEYENCIPHERMENT },
{ NULL, 0, 0 },
};
struct ku_desc eku_keywords[] = {
{ "pkinit", 6, PKINIT_EKU_PKINIT },
{ "msScLogin", 9, PKINIT_EKU_MSSCLOGIN },
{ "clientAuth", 10, PKINIT_EKU_CLIENTAUTH },
{ "emailProtection", 15, PKINIT_EKU_EMAILPROTECTION },
{ NULL, 0, 0 },
};
/* Rule component */
typedef struct _rule_component {
struct _rule_component *next;
keyword_type kw_type;
kw_value_type kwval_type;
regex_t regexp; /* Compiled regular expression */
char *regsrc; /* The regular expression source (for debugging) */
unsigned int ku_bits;
unsigned int eku_bits;
} rule_component;
/* Set rule components */
typedef struct _rule_set {
relation_type relation;
int num_crs;
rule_component *crs;
} rule_set;
static krb5_error_code
free_rule_component(krb5_context context,
rule_component *rc)
{
if (rc == NULL)
return 0;
if (rc->kwval_type == kwvaltype_regexp) {
free(rc->regsrc);
regfree(&rc->regexp);
}
free(rc);
return 0;
}
static krb5_error_code
free_rule_set(krb5_context context,
rule_set *rs)
{
rule_component *rc, *trc;
if (rs == NULL)
return 0;
for (rc = rs->crs; rc != NULL;) {
trc = rc->next;
free_rule_component(context, rc);
rc = trc;
}
free(rs);
return 0;
}
static krb5_error_code
parse_list_value(krb5_context context,
keyword_type type,
char *value,
rule_component *rc)
{
krb5_error_code retval;
char *comma;
struct ku_desc *ku = NULL;
int found;
size_t len;
unsigned int *bitptr;
if (value == NULL || value[0] == '\0') {
pkiDebug("%s: Missing or empty value for list keyword type %d\n",
__FUNCTION__, type);
retval = EINVAL;
goto out;
}
if (type == kw_eku) {
bitptr = &rc->eku_bits;
} else if (type == kw_ku) {
bitptr = &rc->ku_bits;
} else {
pkiDebug("%s: Unknown list keyword type %d\n", __FUNCTION__, type);
retval = EINVAL;
goto out;
}
do {
found = 0;
comma = strchr(value, ',');
if (comma != NULL)
len = comma - value;
else
len = strlen(value);
if (type == kw_eku) {
ku = eku_keywords;
} else if (type == kw_ku) {
ku = ku_keywords;
}
for (; ku->value != NULL; ku++) {
if (strncasecmp(value, ku->value, len) == 0) {
*bitptr |= ku->bitval;
found = 1;
pkiDebug("%s: Found value '%s', bitfield is now 0x%x\n",
__FUNCTION__, ku->value, *bitptr);
break;
}
}
if (found) {
value += ku->length;
if (*value == ',')
value += 1;
} else {
pkiDebug("%s: Urecognized value '%s'\n", __FUNCTION__, value);
retval = EINVAL;
goto out;
}
} while (found && *value != '\0');
retval = 0;
out:
pkiDebug("%s: returning %d\n", __FUNCTION__, retval);
return retval;
}
static krb5_error_code
parse_rule_component(krb5_context context,
const char **rule,
int *remaining,
rule_component **ret_rule)
{
krb5_error_code retval;
rule_component *rc = NULL;
keyword_type kw_type;
kw_value_type kwval_type;
char err_buf[128];
int ret;
struct keyword_desc *kw, *nextkw;
char *nk;
int found_next_kw = 0;
char *value = NULL;
size_t len;
for (kw = matching_keywords; kw->value != NULL; kw++) {
if (strncmp(*rule, kw->value, kw->length) == 0) {
kw_type = kw->kwtype;
kwval_type = kw->kwvaltype;
*rule += kw->length;
*remaining -= kw->length;
break;
}
}
if (kw->value == NULL) {
pkiDebug("%s: Missing or invalid keyword in rule '%s'\n",
__FUNCTION__, *rule);
retval = ENOENT;
goto out;
}
pkiDebug("%s: found keyword '%s'\n", __FUNCTION__, kw->value);
rc = calloc(1, sizeof(*rc));
if (rc == NULL) {
retval = ENOMEM;
goto out;
}
rc->next = NULL;
rc->kw_type = kw_type;
rc->kwval_type = kwval_type;
/*
* Before procesing the value for this keyword,
* (compiling the regular expression or processing the list)
* we need to find the end of it. That means parsing for the
* beginning of the next keyword (or the end of the rule).
*/
nk = strchr(*rule, '<');
while (nk != NULL) {
/* Possibly another keyword, check it out */
for (nextkw = matching_keywords; nextkw->value != NULL; nextkw++) {
if (strncmp(nk, nextkw->value, nextkw->length) == 0) {
/* Found a keyword, nk points to the beginning */
found_next_kw = 1;
break; /* Need to break out of the while! */
}
}
if (!found_next_kw)
nk = strchr(nk+1, '<'); /* keep looking */
else
break;
}
if (nk != NULL && found_next_kw)
len = (nk - *rule);
else
len = (*remaining);
if (len == 0) {
pkiDebug("%s: Missing value for keyword '%s'\n",
__FUNCTION__, kw->value);
retval = EINVAL;
goto out;
}
value = calloc(1, len+1);
if (value == NULL) {
retval = ENOMEM;
goto out;
}
memcpy(value, *rule, len);
*remaining -= len;
*rule += len;
pkiDebug("%s: found value '%s'\n", __FUNCTION__, value);
if (kw->kwvaltype == kwvaltype_regexp) {
ret = regcomp(&rc->regexp, value, REG_EXTENDED);
if (ret) {
regerror(ret, &rc->regexp, err_buf, sizeof(err_buf));
pkiDebug("%s: Error compiling reg-exp '%s': %s\n",
__FUNCTION__, value, err_buf);
retval = ret;
goto out;
}
rc->regsrc = strdup(value);
if (rc->regsrc == NULL) {
retval = ENOMEM;
goto out;
}
} else if (kw->kwvaltype == kwvaltype_list) {
retval = parse_list_value(context, rc->kw_type, value, rc);
if (retval) {
pkiDebug("%s: Error %d, parsing list values for keyword %s\n",
__FUNCTION__, retval, kw->value);
goto out;
}
}
*ret_rule = rc;
retval = 0;
out:
free(value);
if (retval && rc != NULL)
free_rule_component(context, rc);
pkiDebug("%s: returning %d\n", __FUNCTION__, retval);
return retval;
}
static krb5_error_code
parse_rule_set(krb5_context context,
const char *rule_in,
rule_set **out_rs)
{
const char *rule;
int remaining;
krb5_error_code ret, retval;
rule_component *rc = NULL, *trc;
rule_set *rs;
if (rule_in == NULL)
return EINVAL;
rule = rule_in;
remaining = strlen(rule);
rs = calloc(1, sizeof(*rs));
if (rs == NULL) {
retval = ENOMEM;
goto cleanup;
}
rs->relation = relation_none;
if (remaining > 1) {
if (rule[0] == '&' && rule[1] == '&') {
rs->relation = relation_and;
rule += 2;
remaining -= 2;
} else if (rule_in[0] == '|' && rule_in[1] == '|') {
rs->relation = relation_or;
rule +=2;
remaining -= 2;
}
}
rs->num_crs = 0;
while (remaining > 0) {
if (rs->relation == relation_none && rs->num_crs > 0) {
pkiDebug("%s: Assuming AND relation for multiple components in rule '%s'\n",
__FUNCTION__, rule_in);
rs->relation = relation_and;
}
ret = parse_rule_component(context, &rule, &remaining, &rc);
if (ret) {
retval = ret;
goto cleanup;
}
pkiDebug("%s: After parse_rule_component, remaining %d, rule '%s'\n",
__FUNCTION__, remaining, rule);
rs->num_crs++;
/*
* Chain the new component on the end (order matters since
* we can short-circuit an OR or an AND relation if an
* earlier check passes
*/
for (trc = rs->crs; trc != NULL && trc->next != NULL; trc = trc->next);
if (trc == NULL)
rs->crs = rc;
else {
trc->next = rc;
}
}
*out_rs = rs;
retval = 0;
cleanup:
if (retval && rs != NULL) {
free_rule_set(context, rs);
}
pkiDebug("%s: returning %d\n", __FUNCTION__, retval);
return retval;
}
static int
regexp_match(krb5_context context, rule_component *rc, char *value)
{
int code;
pkiDebug("%s: checking %s rule '%s' with value '%s'\n",
__FUNCTION__, keyword2string(rc->kw_type), rc->regsrc, value);
code = regexec(&rc->regexp, value, 0, NULL, 0);
pkiDebug("%s: the result is%s a match\n", __FUNCTION__,
code == REG_NOMATCH ? " NOT" : "");
return (code == 0 ? 1: 0);
}
static int
component_match(krb5_context context,
rule_component *rc,
pkinit_cert_matching_data *md)
{
int match = 0;
int i;
krb5_principal p;
char *princ_string;
switch (rc->kwval_type) {
case kwvaltype_regexp:
switch (rc->kw_type) {
case kw_subject:
match = regexp_match(context, rc, md->subject_dn);
break;
case kw_issuer:
match = regexp_match(context, rc, md->issuer_dn);
break;
case kw_san:
if (md->sans == NULL)
break;
for (i = 0, p = md->sans[i]; p != NULL; p = md->sans[++i]) {
krb5_unparse_name(context, p, &princ_string);
match = regexp_match(context, rc, princ_string);
krb5_free_unparsed_name(context, princ_string);
if (match)
break;
}
break;
default:
pkiDebug("%s: keyword %s, keyword value %s mismatch\n",
__FUNCTION__, keyword2string(rc->kw_type),
kwval2string(kwvaltype_regexp));
break;
}
break;
case kwvaltype_list:
switch(rc->kw_type) {
case kw_eku:
pkiDebug("%s: checking %s: rule 0x%08x, cert 0x%08x\n",
__FUNCTION__, keyword2string(rc->kw_type),
rc->eku_bits, md->eku_bits);
if ((rc->eku_bits & md->eku_bits) == rc->eku_bits)
match = 1;
break;
case kw_ku:
pkiDebug("%s: checking %s: rule 0x%08x, cert 0x%08x\n",
__FUNCTION__, keyword2string(rc->kw_type),
rc->ku_bits, md->ku_bits);
if ((rc->ku_bits & md->ku_bits) == rc->ku_bits)
match = 1;
break;
default:
pkiDebug("%s: keyword %s, keyword value %s mismatch\n",
__FUNCTION__, keyword2string(rc->kw_type),
kwval2string(kwvaltype_regexp));
break;
}
break;
default:
pkiDebug("%s: unknown keyword value type %d\n",
__FUNCTION__, rc->kwval_type);
break;
}
pkiDebug("%s: returning match = %d\n", __FUNCTION__, match);
return match;
}
/*
* Returns match_found == 1 only if exactly one certificate matches
* the given rule
*/
static krb5_error_code
check_all_certs(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_principal princ,
rule_set *rs, /* rule to check */
pkinit_cert_matching_data **matchdata,
int *match_found,
size_t *match_index)
{
krb5_error_code retval;
pkinit_cert_matching_data *md;
int i;
int comp_match = 0;
int total_cert_matches = 0;
rule_component *rc;
int certs_checked = 0;
size_t save_index = 0;
if (match_found == NULL || match_index == NULL)
return EINVAL;
*match_index = 0;
*match_found = 0;
pkiDebug("%s: matching rule relation is %s with %d components\n",
__FUNCTION__, relation2string(rs->relation), rs->num_crs);
/*
* Loop through all the certs available and count
* how many match the rule
*/
for (i = 0, md = matchdata[i]; md != NULL; md = matchdata[++i]) {
pkiDebug("%s: subject: '%s'\n", __FUNCTION__, md->subject_dn);
#if 0
pkiDebug("%s: issuer: '%s'\n", __FUNCTION__, md->subject_dn);
for (j = 0, p = md->sans[j]; p != NULL; p = md->sans[++j]) {
char *san_string;
krb5_unparse_name(context, p, &san_string);
pkiDebug("%s: san: '%s'\n", __FUNCTION__, san_string);
krb5_free_unparsed_name(context, san_string);
}
#endif
certs_checked++;
for (rc = rs->crs; rc != NULL; rc = rc->next) {
comp_match = component_match(context, rc, md);
if (comp_match) {
pkiDebug("%s: match for keyword type %s\n",
__FUNCTION__, keyword2string(rc->kw_type));
}
if (comp_match && rs->relation == relation_or) {
pkiDebug("%s: cert matches rule (OR relation)\n",
__FUNCTION__);
total_cert_matches++;
save_index = i;
goto nextcert;
}
if (!comp_match && rs->relation == relation_and) {
pkiDebug("%s: cert does not match rule (AND relation)\n",
__FUNCTION__);
goto nextcert;
}
}
if (rc == NULL && comp_match) {
pkiDebug("%s: cert matches rule (AND relation)\n", __FUNCTION__);
total_cert_matches++;
save_index = i;
}
nextcert:
continue;
}
pkiDebug("%s: After checking %d certs, we found %d matches\n",
__FUNCTION__, certs_checked, total_cert_matches);
if (total_cert_matches == 1) {
*match_found = 1;
*match_index = save_index;
}
retval = 0;
pkiDebug("%s: returning %d, match_found %d\n",
__FUNCTION__, retval, *match_found);
return retval;
}
krb5_error_code
pkinit_cert_matching(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_principal princ)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
int x;
char **rules = NULL;
rule_set *rs = NULL;
int match_found = 0;
pkinit_cert_matching_data **matchdata = NULL;
size_t match_index = 0;
/* If no matching rules, select the default cert and we're done */
pkinit_libdefault_strings(context, krb5_princ_realm(context, princ),
KRB5_CONF_PKINIT_CERT_MATCH, &rules);
if (rules == NULL) {
pkiDebug("%s: no matching rules found in config file\n", __FUNCTION__);
retval = crypto_cert_select_default(context, plg_cryptoctx,
req_cryptoctx, id_cryptoctx);
goto cleanup;
}
/* parse each rule line one at a time and check all the certs against it */
for (x = 0; rules[x] != NULL; x++) {
pkiDebug("%s: Processing rule '%s'\n", __FUNCTION__, rules[x]);
/* Free rules from previous time through... */
if (rs != NULL) {
free_rule_set(context, rs);
rs = NULL;
}
retval = parse_rule_set(context, rules[x], &rs);
if (retval) {
if (retval == EINVAL) {
pkiDebug("%s: Ignoring invalid rule pkinit_cert_match = '%s'\n",
__FUNCTION__, rules[x]);
continue;
}
goto cleanup;
}
/*
* Optimize so that we do not get cert info unless we have
* valid rules to check. Once obtained, keep it around
* until we are done.
*/
if (matchdata == NULL) {
retval = crypto_cert_get_matching_data(context, plg_cryptoctx,
req_cryptoctx, id_cryptoctx,
&matchdata);
if (retval || matchdata == NULL) {
pkiDebug("%s: Error %d obtaining certificate information\n",
__FUNCTION__, retval);
retval = ENOENT;
goto cleanup;
}
}
retval = check_all_certs(context, plg_cryptoctx, req_cryptoctx,
id_cryptoctx, princ, rs, matchdata,
&match_found, &match_index);
if (retval) {
pkiDebug("%s: Error %d, checking certs against rule '%s'\n",
__FUNCTION__, retval, rules[x]);
goto cleanup;
}
if (match_found) {
pkiDebug("%s: We have an exact match with rule '%s'\n",
__FUNCTION__, rules[x]);
break;
}
}
if (match_found) {
pkiDebug("%s: Selecting the matching cert!\n", __FUNCTION__);
retval = crypto_cert_select(context, id_cryptoctx, match_index);
if (retval) {
pkiDebug("%s: crypto_cert_select error %d, %s\n",
__FUNCTION__, retval, error_message(retval));
goto cleanup;
}
} else {
TRACE_PKINIT_NO_MATCHING_CERT(context);
retval = ENOENT; /* XXX */
goto cleanup;
}
retval = 0;
cleanup:
profile_free_list(rules);
free_rule_set(context, rs);
crypto_cert_free_matching_data_list(context, matchdata);
return retval;
}
krb5_error_code
pkinit_client_cert_match(krb5_context context,
pkinit_plg_crypto_context plgctx,
pkinit_req_crypto_context reqctx,
const char *match_rule,
krb5_boolean *matched)
{
krb5_error_code ret;
pkinit_cert_matching_data *md = NULL;
rule_component *rc = NULL;
int comp_match = 0;
rule_set *rs = NULL;
*matched = FALSE;
ret = parse_rule_set(context, match_rule, &rs);
if (ret)
goto cleanup;
ret = crypto_req_cert_matching_data(context, plgctx, reqctx, &md);
if (ret)
goto cleanup;
for (rc = rs->crs; rc != NULL; rc = rc->next) {
comp_match = component_match(context, rc, md);
if ((comp_match && rs->relation == relation_or) ||
(!comp_match && rs->relation == relation_and)) {
break;
}
}
*matched = comp_match;
cleanup:
free_rule_set(context, rs);
crypto_cert_free_matching_data(context, md);
return ret;
}
|
Java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache.persistence;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.file.OpenOption;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteException;
import org.apache.ignite.IgniteSystemProperties;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.DataRegionConfiguration;
import org.apache.ignite.configuration.DataStorageConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.managers.communication.GridIoMessage;
import org.apache.ignite.internal.processors.cache.CacheGroupContext;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionSupplyMessage;
import org.apache.ignite.internal.processors.cache.persistence.checkpoint.CheckpointHistory;
import org.apache.ignite.internal.processors.cache.persistence.file.FileIO;
import org.apache.ignite.internal.processors.cache.persistence.file.FileIOFactory;
import org.apache.ignite.internal.util.lang.GridAbsPredicate;
import org.apache.ignite.internal.util.typedef.G;
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteInClosure;
import org.apache.ignite.plugin.extensions.communication.Message;
import org.apache.ignite.spi.IgniteSpiException;
import org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Assert;
/**
*
*/
public class LocalWalModeChangeDuringRebalancingSelfTest extends GridCommonAbstractTest {
/** */
private static boolean disableWalDuringRebalancing = true;
/** */
private static final AtomicReference<CountDownLatch> supplyMessageLatch = new AtomicReference<>();
/** */
private static final AtomicReference<CountDownLatch> fileIOLatch = new AtomicReference<>();
/** Replicated cache name. */
private static final String REPL_CACHE = "cache";
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
cfg.setDataStorageConfiguration(
new DataStorageConfiguration()
.setDefaultDataRegionConfiguration(
new DataRegionConfiguration()
.setPersistenceEnabled(true)
.setMaxSize(200 * 1024 * 1024)
.setInitialSize(200 * 1024 * 1024)
)
// Test verifies checkpoint count, so it is essencial that no checkpoint is triggered by timeout
.setCheckpointFrequency(999_999_999_999L)
.setFileIOFactory(new TestFileIOFactory(new DataStorageConfiguration().getFileIOFactory()))
);
cfg.setCacheConfiguration(
new CacheConfiguration(DEFAULT_CACHE_NAME)
// Test checks internal state before and after rebalance, so it is configured to be triggered manually
.setRebalanceDelay(-1),
new CacheConfiguration(REPL_CACHE)
.setRebalanceDelay(-1)
.setCacheMode(CacheMode.REPLICATED)
);
cfg.setCommunicationSpi(new TcpCommunicationSpi() {
@Override public void sendMessage(ClusterNode node, Message msg) throws IgniteSpiException {
if (msg instanceof GridIoMessage && ((GridIoMessage)msg).message() instanceof GridDhtPartitionSupplyMessage) {
int grpId = ((GridDhtPartitionSupplyMessage)((GridIoMessage)msg).message()).groupId();
if (grpId == CU.cacheId(DEFAULT_CACHE_NAME)) {
CountDownLatch latch0 = supplyMessageLatch.get();
if (latch0 != null)
try {
latch0.await();
}
catch (InterruptedException ex) {
throw new IgniteException(ex);
}
}
}
super.sendMessage(node, msg);
}
@Override public void sendMessage(ClusterNode node, Message msg,
IgniteInClosure<IgniteException> ackC) throws IgniteSpiException {
if (msg instanceof GridIoMessage && ((GridIoMessage)msg).message() instanceof GridDhtPartitionSupplyMessage) {
int grpId = ((GridDhtPartitionSupplyMessage)((GridIoMessage)msg).message()).groupId();
if (grpId == CU.cacheId(DEFAULT_CACHE_NAME)) {
CountDownLatch latch0 = supplyMessageLatch.get();
if (latch0 != null)
try {
latch0.await();
}
catch (InterruptedException ex) {
throw new IgniteException(ex);
}
}
}
super.sendMessage(node, msg, ackC);
}
});
cfg.setConsistentId(igniteInstanceName);
System.setProperty(IgniteSystemProperties.IGNITE_DISABLE_WAL_DURING_REBALANCING,
Boolean.toString(disableWalDuringRebalancing));
return cfg;
}
/** {@inheritDoc} */
@Override protected void beforeTestsStarted() throws Exception {
super.beforeTestsStarted();
cleanPersistenceDir();
}
/** {@inheritDoc} */
@Override protected void afterTest() throws Exception {
super.afterTest();
CountDownLatch msgLatch = supplyMessageLatch.get();
if (msgLatch != null) {
while (msgLatch.getCount() > 0)
msgLatch.countDown();
supplyMessageLatch.set(null);
}
CountDownLatch fileLatch = fileIOLatch.get();
if (fileLatch != null) {
while (fileLatch.getCount() > 0)
fileLatch.countDown();
fileIOLatch.set(null);
}
stopAllGrids();
cleanPersistenceDir();
disableWalDuringRebalancing = true;
}
/**
* @return Count of entries to be processed within test.
*/
protected int getKeysCount() {
return 10_000;
}
/**
* @throws Exception If failed.
*/
public void testWalDisabledDuringRebalancing() throws Exception {
doTestSimple();
}
/**
* @throws Exception If failed.
*/
public void testWalNotDisabledIfParameterSetToFalse() throws Exception {
disableWalDuringRebalancing = false;
doTestSimple();
}
/**
* @throws Exception If failed.
*/
private void doTestSimple() throws Exception {
Ignite ignite = startGrids(3);
ignite.cluster().active(true);
IgniteCache<Integer, Integer> cache = ignite.cache(DEFAULT_CACHE_NAME);
int keysCnt = getKeysCount();
for (int k = 0; k < keysCnt; k++)
cache.put(k, k);
IgniteEx newIgnite = startGrid(3);
final CheckpointHistory cpHist =
((GridCacheDatabaseSharedManager)newIgnite.context().cache().context().database()).checkpointHistory();
GridTestUtils.waitForCondition(new GridAbsPredicate() {
@Override public boolean apply() {
return !cpHist.checkpoints().isEmpty();
}
}, 10_000);
U.sleep(10); // To ensure timestamp granularity.
long newIgniteStartedTimestamp = System.currentTimeMillis();
ignite.cluster().setBaselineTopology(4);
CacheGroupContext grpCtx = newIgnite.cachex(DEFAULT_CACHE_NAME).context().group();
assertEquals(!disableWalDuringRebalancing, grpCtx.walEnabled());
U.sleep(10); // To ensure timestamp granularity.
long rebalanceStartedTimestamp = System.currentTimeMillis();
for (Ignite g : G.allGrids())
g.cache(DEFAULT_CACHE_NAME).rebalance();
awaitPartitionMapExchange();
assertTrue(grpCtx.walEnabled());
U.sleep(10); // To ensure timestamp granularity.
long rebalanceFinishedTimestamp = System.currentTimeMillis();
for (Integer k = 0; k < keysCnt; k++)
assertEquals("k=" + k, k, cache.get(k));
int checkpointsBeforeNodeStarted = 0;
int checkpointsBeforeRebalance = 0;
int checkpointsAfterRebalance = 0;
for (Long timestamp : cpHist.checkpoints()) {
if (timestamp < newIgniteStartedTimestamp)
checkpointsBeforeNodeStarted++;
else if (timestamp >= newIgniteStartedTimestamp && timestamp < rebalanceStartedTimestamp)
checkpointsBeforeRebalance++;
else if (timestamp >= rebalanceStartedTimestamp && timestamp <= rebalanceFinishedTimestamp)
checkpointsAfterRebalance++;
}
assertEquals(1, checkpointsBeforeNodeStarted); // checkpoint on start
assertEquals(0, checkpointsBeforeRebalance);
assertEquals(disableWalDuringRebalancing ? 1 : 0, checkpointsAfterRebalance); // checkpoint if WAL was re-activated
}
/**
* @throws Exception If failed.
*/
public void testLocalAndGlobalWalStateInterdependence() throws Exception {
Ignite ignite = startGrids(3);
ignite.cluster().active(true);
IgniteCache<Integer, Integer> cache = ignite.cache(DEFAULT_CACHE_NAME);
for (int k = 0; k < getKeysCount(); k++)
cache.put(k, k);
IgniteEx newIgnite = startGrid(3);
ignite.cluster().setBaselineTopology(ignite.cluster().nodes());
CacheGroupContext grpCtx = newIgnite.cachex(DEFAULT_CACHE_NAME).context().group();
assertFalse(grpCtx.walEnabled());
ignite.cluster().disableWal(DEFAULT_CACHE_NAME);
for (Ignite g : G.allGrids())
g.cache(DEFAULT_CACHE_NAME).rebalance();
awaitPartitionMapExchange();
assertFalse(grpCtx.walEnabled()); // WAL is globally disabled
ignite.cluster().enableWal(DEFAULT_CACHE_NAME);
assertTrue(grpCtx.walEnabled());
}
/**
* Test that local WAL mode changing works well with exchanges merge.
*
* @throws Exception If failed.
*/
public void testWithExchangesMerge() throws Exception {
final int nodeCnt = 5;
final int keyCnt = getKeysCount();
Ignite ignite = startGrids(nodeCnt);
ignite.cluster().active(true);
IgniteCache<Integer, Integer> cache = ignite.cache(REPL_CACHE);
for (int k = 0; k < keyCnt; k++)
cache.put(k, k);
stopGrid(2);
stopGrid(3);
stopGrid(4);
// Rewrite data to trigger further rebalance.
for (int k = 0; k < keyCnt; k++)
cache.put(k, k * 2);
// Start several grids in parallel to trigger exchanges merge.
startGridsMultiThreaded(2, 3);
for (int nodeIdx = 2; nodeIdx < nodeCnt; nodeIdx++) {
CacheGroupContext grpCtx = grid(nodeIdx).cachex(REPL_CACHE).context().group();
assertFalse(grpCtx.walEnabled());
}
// Invoke rebalance manually.
for (Ignite g : G.allGrids())
g.cache(REPL_CACHE).rebalance();
awaitPartitionMapExchange();
for (int nodeIdx = 2; nodeIdx < nodeCnt; nodeIdx++) {
CacheGroupContext grpCtx = grid(nodeIdx).cachex(REPL_CACHE).context().group();
assertTrue(grpCtx.walEnabled());
}
// Check no data loss.
for (int nodeIdx = 2; nodeIdx < nodeCnt; nodeIdx++) {
IgniteCache<Integer, Integer> cache0 = grid(nodeIdx).cache(REPL_CACHE);
for (int k = 0; k < keyCnt; k++)
Assert.assertEquals("nodeIdx=" + nodeIdx + ", key=" + k, (Integer) (2 * k), cache0.get(k));
}
}
/**
* @throws Exception If failed.
*/
public void testParallelExchangeDuringRebalance() throws Exception {
doTestParallelExchange(supplyMessageLatch);
}
/**
* @throws Exception If failed.
*/
public void testParallelExchangeDuringCheckpoint() throws Exception {
doTestParallelExchange(fileIOLatch);
}
/**
* @throws Exception If failed.
*/
private void doTestParallelExchange(AtomicReference<CountDownLatch> latchRef) throws Exception {
Ignite ignite = startGrids(3);
ignite.cluster().active(true);
IgniteCache<Integer, Integer> cache = ignite.cache(DEFAULT_CACHE_NAME);
for (int k = 0; k < getKeysCount(); k++)
cache.put(k, k);
IgniteEx newIgnite = startGrid(3);
CacheGroupContext grpCtx = newIgnite.cachex(DEFAULT_CACHE_NAME).context().group();
CountDownLatch latch = new CountDownLatch(1);
latchRef.set(latch);
ignite.cluster().setBaselineTopology(ignite.cluster().nodes());
for (Ignite g : G.allGrids())
g.cache(DEFAULT_CACHE_NAME).rebalance();
assertFalse(grpCtx.walEnabled());
// TODO : test with client node as well
startGrid(4); // Trigger exchange
assertFalse(grpCtx.walEnabled());
latch.countDown();
assertFalse(grpCtx.walEnabled());
for (Ignite g : G.allGrids())
g.cache(DEFAULT_CACHE_NAME).rebalance();
awaitPartitionMapExchange();
assertTrue(grpCtx.walEnabled());
}
/**
* @throws Exception If failed.
*/
public void testDataClearedAfterRestartWithDisabledWal() throws Exception {
Ignite ignite = startGrid(0);
ignite.cluster().active(true);
IgniteCache<Integer, Integer> cache = ignite.cache(DEFAULT_CACHE_NAME);
int keysCnt = getKeysCount();
for (int k = 0; k < keysCnt; k++)
cache.put(k, k);
IgniteEx newIgnite = startGrid(1);
ignite.cluster().setBaselineTopology(2);
CacheGroupContext grpCtx = newIgnite.cachex(DEFAULT_CACHE_NAME).context().group();
assertFalse(grpCtx.localWalEnabled());
stopGrid(1);
stopGrid(0);
newIgnite = startGrid(1);
newIgnite.cluster().active(true);
newIgnite.cluster().setBaselineTopology(newIgnite.cluster().nodes());
cache = newIgnite.cache(DEFAULT_CACHE_NAME);
for (int k = 0; k < keysCnt; k++)
assertFalse("k=" + k +", v=" + cache.get(k), cache.containsKey(k));
}
/**
* @throws Exception If failed.
*/
public void testWalNotDisabledAfterShrinkingBaselineTopology() throws Exception {
Ignite ignite = startGrids(4);
ignite.cluster().active(true);
IgniteCache<Integer, Integer> cache = ignite.cache(DEFAULT_CACHE_NAME);
int keysCnt = getKeysCount();
for (int k = 0; k < keysCnt; k++)
cache.put(k, k);
for (Ignite g : G.allGrids()) {
CacheGroupContext grpCtx = ((IgniteEx)g).cachex(DEFAULT_CACHE_NAME).context().group();
assertTrue(grpCtx.walEnabled());
}
stopGrid(2);
ignite.cluster().setBaselineTopology(5);
for (Ignite g : G.allGrids()) {
CacheGroupContext grpCtx = ((IgniteEx)g).cachex(DEFAULT_CACHE_NAME).context().group();
assertTrue(grpCtx.walEnabled());
g.cache(DEFAULT_CACHE_NAME).rebalance();
}
awaitPartitionMapExchange();
for (Ignite g : G.allGrids()) {
CacheGroupContext grpCtx = ((IgniteEx)g).cachex(DEFAULT_CACHE_NAME).context().group();
assertTrue(grpCtx.walEnabled());
}
}
/**
*
*/
private static class TestFileIOFactory implements FileIOFactory {
/** */
private final FileIOFactory delegate;
/**
* @param delegate Delegate.
*/
TestFileIOFactory(FileIOFactory delegate) {
this.delegate = delegate;
}
/** {@inheritDoc} */
@Override public FileIO create(File file) throws IOException {
return new TestFileIO(delegate.create(file));
}
/** {@inheritDoc} */
@Override public FileIO create(File file, OpenOption... modes) throws IOException {
return new TestFileIO(delegate.create(file, modes));
}
}
/**
*
*/
private static class TestFileIO implements FileIO {
/** */
private final FileIO delegate;
/**
* @param delegate Delegate.
*/
TestFileIO(FileIO delegate) {
this.delegate = delegate;
}
/** {@inheritDoc} */
@Override public long position() throws IOException {
return delegate.position();
}
/** {@inheritDoc} */
@Override public void position(long newPosition) throws IOException {
delegate.position(newPosition);
}
/** {@inheritDoc} */
@Override public int read(ByteBuffer destBuf) throws IOException {
return delegate.read(destBuf);
}
/** {@inheritDoc} */
@Override public int read(ByteBuffer destBuf, long position) throws IOException {
return delegate.read(destBuf, position);
}
/** {@inheritDoc} */
@Override public int read(byte[] buf, int off, int len) throws IOException {
return delegate.read(buf, off, len);
}
/** {@inheritDoc} */
@Override public int write(ByteBuffer srcBuf) throws IOException {
CountDownLatch latch = fileIOLatch.get();
if (latch != null && Thread.currentThread().getName().contains("checkpoint"))
try {
latch.await();
}
catch (InterruptedException ex) {
throw new IgniteException(ex);
}
return delegate.write(srcBuf);
}
/** {@inheritDoc} */
@Override public int write(ByteBuffer srcBuf, long position) throws IOException {
CountDownLatch latch = fileIOLatch.get();
if (latch != null && Thread.currentThread().getName().contains("checkpoint"))
try {
latch.await();
}
catch (InterruptedException ex) {
throw new IgniteException(ex);
}
return delegate.write(srcBuf, position);
}
/** {@inheritDoc} */
@Override public int write(byte[] buf, int off, int len) throws IOException {
CountDownLatch latch = fileIOLatch.get();
if (latch != null && Thread.currentThread().getName().contains("checkpoint"))
try {
latch.await();
}
catch (InterruptedException ex) {
throw new IgniteException(ex);
}
return delegate.write(buf, off, len);
}
/** {@inheritDoc} */
@Override public MappedByteBuffer map(int maxWalSegmentSize) throws IOException {
return delegate.map(maxWalSegmentSize);
}
/** {@inheritDoc} */
@Override public void force() throws IOException {
delegate.force();
}
/** {@inheritDoc} */
@Override public void force(boolean withMetadata) throws IOException {
delegate.force(withMetadata);
}
/** {@inheritDoc} */
@Override public long size() throws IOException {
return delegate.size();
}
/** {@inheritDoc} */
@Override public void clear() throws IOException {
delegate.clear();
}
/** {@inheritDoc} */
@Override public void close() throws IOException {
delegate.close();
}
}
}
|
Java
|
package marcin_szyszka.mobileseconndhand.models;
/**
* Created by marcianno on 2016-03-02.
*/
public class RegisterUserModel {
public String Email;
public String Password;
public String ConfirmPassword;
public RegisterUserModel(){
}
}
|
Java
|
//
// MianTableViewCell.h
// SweetFood
//
// Created by scjy on 16/3/4.
// Copyright © 2016年 范芳芳. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "MianModel.h"
#import "MainModel.h"
@interface MianTableViewCell : UITableViewCell
@property (strong, nonatomic) UIImageView *cellImage;
@property (strong, nonatomic) UILabel *titleLable;
@end
|
Java
|
# Xanthophyllum subglobosum Elmer SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
# AUTOGENERATED FILE
FROM balenalib/raspberrypi0-2w-64-fedora:34-build
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
RUN dnf install -y \
python3-pip \
python3-dbus \
&& dnf clean all
# install "virtualenv", since the vast majority of users of this image will want it
RUN pip3 install -U --no-cache-dir --ignore-installed pip setuptools \
&& pip3 install --no-cache-dir virtualenv
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'As of January 1st, 2020, Python 2 was end-of-life, we will change the latest tag for Balenalib Python base image to Python 3.x and drop support for Python 2 soon. So after 1st July, 2020, all the balenalib Python latest tag will point to the latest Python 3 version and no changes, or fixes will be made to balenalib Python 2 base image. If you are using Python 2 for your application, please upgrade to Python 3 before 1st July.' > /.balena/messages/python-deprecation-warning
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \
&& echo "Running test-stack@python" \
&& chmod +x test-stack@python.sh \
&& bash test-stack@python.sh \
&& rm -rf test-stack@python.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Fedora 34 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.8.12, Pip v21.3.1, Setuptools v60.5.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
Java
|
// Generated by esidl 0.3.0.
// This file is expected to be modified for the Web IDL interface
// implementation. Permission to use, copy, modify and distribute
// this file in any software license is hereby granted.
#include "AudioTrackListImp.h"
namespace org
{
namespace w3c
{
namespace dom
{
namespace bootstrap
{
unsigned int AudioTrackListImp::getLength()
{
// TODO: implement me!
return 0;
}
html::AudioTrack AudioTrackListImp::getElement(unsigned int index)
{
// TODO: implement me!
return nullptr;
}
html::AudioTrack AudioTrackListImp::getTrackById(const std::u16string& id)
{
// TODO: implement me!
return nullptr;
}
events::EventHandlerNonNull AudioTrackListImp::getOnchange()
{
// TODO: implement me!
return nullptr;
}
void AudioTrackListImp::setOnchange(events::EventHandlerNonNull onchange)
{
// TODO: implement me!
}
events::EventHandlerNonNull AudioTrackListImp::getOnaddtrack()
{
// TODO: implement me!
return nullptr;
}
void AudioTrackListImp::setOnaddtrack(events::EventHandlerNonNull onaddtrack)
{
// TODO: implement me!
}
events::EventHandlerNonNull AudioTrackListImp::getOnremovetrack()
{
// TODO: implement me!
return nullptr;
}
void AudioTrackListImp::setOnremovetrack(events::EventHandlerNonNull onremovetrack)
{
// TODO: implement me!
}
}
}
}
}
|
Java
|
package org.annoconf;
/**
* Created by roma on 3/19/17.
*/
public interface PropertyValueSource {
boolean hasValue(String key);
String getValue(String key);
}
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_29) on Sun Feb 05 12:13:54 CET 2012 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory (The Netty Project API Reference (3.3.1.Final))
</TITLE>
<META NAME="date" CONTENT="2012-02-05">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory (The Netty Project API Reference (3.3.1.Final))";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/jboss/netty/channel/socket/nio/NioClientSocketChannelFactory.html" title="class in org.jboss.netty.channel.socket.nio"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?org/jboss/netty/channel/socket/nio//class-useNioClientSocketChannelFactory.html" target="_top"><B>FRAMES</B></A>
<A HREF="NioClientSocketChannelFactory.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory</B></H2>
</CENTER>
No usage of org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/jboss/netty/channel/socket/nio/NioClientSocketChannelFactory.html" title="class in org.jboss.netty.channel.socket.nio"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?org/jboss/netty/channel/socket/nio//class-useNioClientSocketChannelFactory.html" target="_top"><B>FRAMES</B></A>
<A HREF="NioClientSocketChannelFactory.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2008-2012 <a href="http://netty.io/">The Netty Project</a>. All Rights Reserved.
</BODY>
</HTML>
|
Java
|
/******************************************************************************
* 版权所有 刘大磊 2013-07-01 *
* 作者:刘大磊 *
* 电话:13336390671 *
* email:ldlqdsd@126.com *
*****************************************************************************/
package com.delmar.core.service;
import com.delmar.core.model.CorePage;
import com.delmar.core.service.CoreService;
/**
* @author 刘大磊 2016-08-26 17:08:24
*/
public interface CorePageService extends CoreService<CorePage> {
/**
* @param ids
*/
void deleteCorePageList(Integer[] ids);
}
|
Java
|
package de.hsmainz.pubapp.geocoder.controller;
import com.google.gson.Gson;
import de.hsmainz.pubapp.geocoder.model.ClientInputJson;
import de.hsmainz.pubapp.geocoder.model.ErrorJson;
import de.hsmainz.pubapp.geocoder.model.geojson.GeoJsonCollection;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Locale;
import java.util.ResourceBundle;
/**
* Interface for all different geocoder APIs
*
* @author Arno
* @since 15.12.2016
*/
public abstract class HttpAPIRequest {
//****************************************
// CONSTANTS
//****************************************
static final ResourceBundle lables = ResourceBundle.getBundle("lable", Locale.getDefault());
static final Logger logger = LogManager.getLogger(HttpGraphhopperRequest.class);
//****************************************
// VARIABLES
//****************************************
Gson gson = new Gson();
//****************************************
// INIT/CONSTRUCTOR
//****************************************
//****************************************
// GETTER/SETTER
//****************************************
//****************************************
// PUBLIC METHODS
//****************************************
/**
* Executes request to geocoder API and creates GeoJSON. Custom ClientJson is used for the input
*
* @param inputJson the request parameters combined in a custom ClientJson
* @return API response converted to a String
*/
public String requestGeocoder(ClientInputJson inputJson) {
String returnString;
if (!validateInput(inputJson)) {
returnString = gson.toJson(new ErrorJson(lables.getString("message_Input_Empty")));
} else {
returnString = requestGeocoder(inputJson.getQueryString(), inputJson.getLocale());
}
return returnString;
}
/**
* Executes request to geocoder API and creates GeoJSON
*
* @param queryString the string containing the address
* @param locale the string defining the used language
* @return API response converted to a String
*/
public String requestGeocoder(String queryString, String locale) {
String returnString;
if (!validateInput(queryString)) {
returnString = gson.toJson(new ErrorJson(lables.getString("message_Input_Empty")));
} else {
try {
URI uri = buildUri(queryString, locale);
returnString = request(uri);
} catch (URISyntaxException e) {
logger.catching(e);
returnString = gson.toJson(new ErrorJson(lables.getString("error_incorrect_URI")));
}
}
return returnString;
}
//****************************************
// PRIVATE METHODS
//****************************************
/**
* Creates the URI for API request
*
* @param queryString the string containing the address
* @param locale the string defining the used language
* @return Uri for geocoder request to graphhopper API
*/
abstract URI buildUri(String queryString, String locale) throws URISyntaxException;
/**
* Executes the request to the API
*
* @param uri the geocoder URL
* @return the requested geoJSON
* @throws throws an exception if the request fails
*/
abstract GeoJsonCollection doHttpGet(URI uri) throws IOException;
/**
* Method to catch exceptions and create ErrorJSONs
*
* @param uri
* @return returns the GeoJSON or ErrorJSON as a String
*/
String request(URI uri) {
String returnString;
try {
GeoJsonCollection geoJsonCollection = doHttpGet(uri);
if (validateOutput(geoJsonCollection)) {
returnString = gson.toJson(geoJsonCollection);
} else {
returnString = gson.toJson(new ErrorJson(lables.getString("message_no_location")));
}
} catch (IOException e) {
logger.catching(e);
returnString = gson.toJson(new ErrorJson(lables.getString("error_API_request_Faild")));
}
return returnString;
}
/**
* validates the Input to reduce unnecessary request to API
*
* @param inputJson the InputJSON to be validated
* @return returns true if InputJSON is valid
*/
boolean validateInput(ClientInputJson inputJson) {
boolean returnValue = true;
if (inputJson.getQueryString() == null || inputJson.getQueryString().isEmpty()) {
returnValue = false;
}
if (inputJson.getLocale() == null || inputJson.getLocale().isEmpty()) {
returnValue = false;
}
return returnValue;
}
/**
* validates the Input to reduce unnecessary request to API
*
* @param inputString the Input String to be validated
* @return true if Input String is not Empty
*/
boolean validateInput(String inputString) {
boolean returnValue = true;
if (inputString == null || inputString.isEmpty()) {
returnValue = false;
}
return returnValue;
}
/**
* validates the output from the API
*
* @param geoJsonCollection the API outputJSON to be validated
* @return returns true if the outputJSON is not empty
*/
private boolean validateOutput(GeoJsonCollection geoJsonCollection) {
return !geoJsonCollection.getFeatures().isEmpty();
}
//****************************************
// INNER CLASSES
//****************************************
}
|
Java
|
package com.txtr.hibernatedelta.model;
import static javax.xml.bind.annotation.XmlAccessType.FIELD;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlType;
import org.apache.commons.lang3.StringUtils;
@XmlAccessorType(FIELD)
@XmlType(propOrder = {"name", "columns", "explicitIndexes"})
public class HibernateTable implements IHibernateDatabaseObject {
@XmlAttribute
private String name;
@XmlElementWrapper(name = "columns")
@XmlElement(name = "column")
private List<HibernateColumn> columns = new ArrayList<HibernateColumn>();
@XmlElementWrapper(name = "indexes")
@XmlElement(name = "index")
private List<ExplicitHibernateIndex> explicitIndexes = new ArrayList<ExplicitHibernateIndex>();
@XmlAttribute
private String sequenceName;
@XmlAttribute
private boolean virtualRootTable;
public HibernateTable(String name, String sequenceName, boolean virtualRootTable) {
this.sequenceName = sequenceName;
this.virtualRootTable = virtualRootTable;
this.name = name;
}
@SuppressWarnings("UnusedDeclaration")
public HibernateTable() {
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<HibernateColumn> getColumns() {
return columns;
}
public List<ExplicitHibernateIndex> getExplicitIndexes() {
return explicitIndexes;
}
public void addColumn(HibernateColumn column) {
columns.add(column);
}
public HibernateColumn getColumn(String name) {
for (HibernateColumn column : columns) {
if (column.getName().equalsIgnoreCase(name)) {
return column;
}
}
throw new IllegalArgumentException("column not found: " + name);
}
public void addExplicitIndex(ExplicitHibernateIndex hibernateIndex) {
explicitIndexes.add(hibernateIndex);
}
public String getIndexPrefix() {
return StringUtils.left(name, 28);
}
public List<HibernateColumn> getPrimaryKeyColumns() {
List<HibernateColumn> result = new ArrayList<HibernateColumn>();
for (HibernateColumn column : columns) {
if (column.isPrimaryKey()) {
result.add(column);
}
}
return result;
}
public String getSequenceName() {
return sequenceName;
}
public boolean isVirtualRootTable() {
return virtualRootTable;
}
}
|
Java
|
# Nassella sadae Phil. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
/**
*
*/
package me.learn.personal.month5;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Title :
*
* Date : Dec 23, 2020
*
* @author bramanarayan
*
*/
public class WordBreakable {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> wordDictSet = new HashSet<>(wordDict);
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for (int i = 1; i <= s.length(); i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && wordDictSet.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
}
|
Java
|
/*
Copyright 2015 Ricardo Tubio-Pardavila
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.
*/
angular.module('snRequestsDirective', [
'ngMaterial',
'snCommonFilters', 'snApplicationBus',
'snRequestsFilters', 'snControllers', 'snJRPCServices'
])
.controller('snRequestSlotCtrl', [
'$scope', '$mdDialog', '$mdToast', 'satnetRPC', 'snDialog', 'snMessageBus',
/**
* Controller function for handling the SatNet requests dialog.
*
* @param {Object} $scope $scope for the controller
*/
function ($scope, $mdDialog, $mdToast, satnetRPC, snDialog, snMessageBus) {
$scope.gui = {
groundstation_id: '',
spacecraft_id: '',
primary: '',
hide: {
accept: true,
drop: true,
deny: true,
},
slot: {}
};
/**
* Function that handles the process of accepting a given request that
* has already been selected.
*/
$scope.accept = function () {
satnetRPC.rCall(
'gs.operational.accept', [
$scope.groundstation_id, [$scope.slot.identifier]
]
).then(function (results) {
snDialog.toastAction('Confirmed slot #',$scope.slot.identifier);
$scope.slot.state = 'RESERVED';
snMessageBus.send(
snMessageBus.CHANNELS.requests.id,
snMessageBus.EVENTS.accepted.id, {
gs_id: $scope.gui.groundstation_id,
sc_id: $scope.gui.spacecraft_id,
primary: $scope.gui.primary,
slot: $scope.gui.slot
}
);
}).catch(function (c) {
snDialog.exception('gs.operational.accept', '', c);
});
};
/**
* Function that handles the process of denying a given request that
* has already been selected.
*
* TODO :: Temporary, it has been linked to the drop function so that
* the slot does not stay forever with the DENIED state.
*/
$scope.deny = function () {
satnetRPC.rCall(
'gs.operational.drop', [
$scope.groundstation_id, [$scope.slot.identifier]
]
).then(function (results) {
snDialog.toastAction('Denied slot #', $scope.slot.identifier);
$scope.slot.state = 'FREE';
snMessageBus.send(
snMessageBus.CHANNELS.requests.id,
snMessageBus.EVENTS.denied.id, {
gs_id: $scope.gui.groundstation_id,
sc_id: $scope.gui.spacecraft_id,
primary: $scope.gui.primary,
slot: $scope.gui.slot
}
);
}).catch(function (c) {
snDialog.exception('gs.operational.drop', '', c);
});
};
/**
* Function that handles the process of droping a given request that
* has already been booked.
*
* IMPORTANT: This function works both for spacecraft and for
* groundstation slots; therefore, there is an inherent
* level of complexity added in addition in order to
* handle both cases.
*/
$scope.drop = function () {
var rpc = ($scope.gui.primary === 'groundstation') ?
'gs.operational.drop' : 'sc.cancel',
segment_id = ($scope.gui.primary === 'groundstation') ?
$scope.groundstation_id : $scope.spacecraft_id;
satnetRPC.rCall(
rpc, [segment_id, [$scope.slot.identifier]]
).then(function (results) {
snDialog.toastAction('Dropped slot #', $scope.slot.identifier);
$scope.slot.state = 'FREE';
snMessageBus.send(
snMessageBus.CHANNELS.requests.id,
snMessageBus.EVENTS.dropped.id, {
gs_id: $scope.gui.groundstation_id,
sc_id: $scope.gui.spacecraft_id,
primary: $scope.gui.primary,
slot: $scope.gui.slot
}
);
}).catch(function (c) {
snDialog.exception(rpc, '', c);
});
};
/**
* Function that returns whether o not the "accept" button should be
* displayed, taking into account the state of the controller.
*/
$scope.showAccept = function () {
return ($scope.gui.slot.state === 'SELECTED') &&
!($scope.gui.hide.accept);
};
/**
* Function that returns whether o not the "deny" button should be
* displayed, taking into account the state of the controller.
*/
$scope.showDeny = function () {
return ($scope.gui.slot.state === 'SELECTED') &&
!($scope.gui.hide.deny);
};
/**
* Function that returns whether o not the "drop" button should be
* displayed, taking into account the state of the controller.
*/
$scope.showDrop = function () {
if ($scope.gui.primary === 'spacecraft') {
return !($scope.gui.hide.drop) && (
($scope.gui.slot.state === 'SELECTED') ||
($scope.gui.slot.state === 'RESERVED')
);
} else {
return !($scope.gui.hide.drop) && (
($scope.gui.slot.state === 'RESERVED')
);
}
};
/**
* Initialization of the controller.
*/
$scope.init = function () {
$scope.gui.groundstation_id = $scope.gs;
$scope.gui.spacecraft_id = $scope.sc;
$scope.gui.primary = $scope.primary;
$scope.gui.slot = $scope.slot;
if ( $scope.gui.primary === 'spacecraft' ) {
$scope.gui.hide.drop = false;
} else {
$scope.gui.hide.accept = false;
$scope.gui.hide.deny = false;
$scope.gui.hide.drop = false;
}
};
$scope.init();
}
])
.directive('snRequestSlot',
/**
* Function that creates the directive itself returning the object required
* by Angular.
*
* @returns {Object} Object directive required by Angular, with restrict
* and templateUrl
*/
function () {
return {
restrict: 'E',
templateUrl: 'operations/templates/requests/slot.html',
controller: 'snRequestSlotCtrl',
scope: {
sc: '@',
gs: '@',
primary: '@',
slot: '='
}
};
}
)
.controller('snRequestsDlgCtrl', [
'$scope', '$log', '$mdDialog', 'satnetRPC','snDialog', 'snMessageBus',
/**
* Controller function for handling the SatNet requests dialog.
*
* @param {Object} $scope $scope for the controller
*/
function ($scope, $log, $mdDialog, satnetRPC, snDialog, snMessageBus) {
$scope.events = {
requests: {
accepted: {
id: snMessageBus.createName(
snMessageBus.CHANNELS.requests.id,
snMessageBus.EVENTS.accepted.id
)
},
denied: {
id: snMessageBus.createName(
snMessageBus.CHANNELS.requests.id,
snMessageBus.EVENTS.denied.id
)
},
dropped: {
id: snMessageBus.createName(
snMessageBus.CHANNELS.requests.id,
snMessageBus.EVENTS.dropped.id
)
}
}
};
/**
* This function finds the given slot within the dictionary/array of
* slots within this controller.
*
* @param {String} segmentId Identifier of the segment
* @param {String} slotId Identifier of the slot
*/
$scope._findSlot = function (segmentId, slotId) {
var slots = $scope.gui.slots[segmentId];
if ((slots === undefined) || (slots.length === 0)) {
throw 'No slots for ss = ' + segmentId;
}
for (var i = 0, L = slots.length; i < L; i++) {
if (slots[i].identifier === slotId) {
return {
index: i,
slot: slots[i]
};
}
}
throw 'Slot not found for ss = ' + segmentId;
};
/**
* Updates the slots dictionary when the slot that triggered the event
* was updated to the "FREE" state.
*
* @param {Object} data The data object attached to the event
*/
$scope._updateFree = function (data) {
var ss_id = (data.primary === 'spacecraft') ?
data.gs_id: data.sc_id,
other_ss_id = (data.primary === 'spacecraft') ?
data.sc_id: data.gs_id,
slot = $scope._findSlot(ss_id, data.slot.identifier),
slot_other = $scope._findSlot(
other_ss_id, data.slot.identifier
);
$scope.gui.slots[ss_id].splice(slot.index, 1);
$scope.gui.slots[other_ss_id].splice(slot_other.index, 1);
};
/**
* Updates the slots dictionary when the slot that triggered the event
* was not updated to the "FREE" state.
*
* @param {Object} data The data object attached to the event
*/
$scope._updateNonFree = function (data) {
var ss_id = (data.primary === 'spacecraft') ?
data.gs_id: data.sc_id,
slot = $scope._findSlot(ss_id, data.slot.identifier);
slot.slot.state = data.slot.state;
};
/**
* CALLBACK
* This function is the callback that handles the event triggered
* whenever a request slot has been accepted, canceled or denied.
*
* @param {String} event The name of the event
* @param {Object} data The data object generated by the event
*/
$scope._updateRequestCb = function (event, data) {
try {
if (data.slot.state === 'FREE') { $scope._updateFree(data); }
else { $scope._updateNonFree(data); }
} catch (e) { $log.info(e); }
};
$scope.$on(
$scope.events.requests.accepted.id, $scope._updateRequestCb
);
$scope.$on(
$scope.events.requests.denied.id, $scope._updateRequestCb
);
$scope.$on(
$scope.events.requests.dropped.id, $scope._updateRequestCb
);
$scope.gui = {
gss: [],
scs: [],
slots: {},
filtered: {}
};
/**
* Function that closes the dialog.
*/
$scope.close = function () { $mdDialog.hide(); };
/**
* This function is used to check whether the given slot has to be
* discarded from amongst the other slots or not.
*
* @param {Object} slot The slot to be checked
* @param {Boolean} 'true' if the slot has to be discarded
*/
$scope._filterByState = function(slot) {
return (slot.state !== 'SELECTED') && (slot.state !== 'RESERVED');
};
/**
* This function processes the slots received from the server in order
* to adapt them to a more JavaScript "friendly" data structure. It
* stores the results directly in the controller's data section.
*
* @param {String} segmentId Identifier of the segment
* @param {Object} results Object with the results from the server
*/
$scope._processSlots = function (segmentId, results) {
$scope.gui.slots[segmentId] = [];
if ((results === null) || (angular.equals({}, results))) {
return;
}
var ss_id = Object.keys(results)[0],
slots = results[ss_id];
for (var i = 0, L = slots.length; i < L; i++) {
if ($scope._filterByState(slots[i])) {continue;}
slots[i].segment_id = ss_id;
$scope.gui.slots[segmentId].push(slots[i]);
}
};
/**
* This function retrieves the operational slots from the server for a
* given segment and stores them internally in a single list for the
* controller.
* IMPORTANT: It processes the list so that it adds the reference to
* the other segment related in the slot by place its id inside the
* object of the slot rather than as a key to access the slot.
* IMPORTANT 2: It filters out all the slots whose states are neither
* 'SELECTED' nor 'BOOKED'.
*
* @param segmentType String that indicates whether the reference
* segment is a ground station ('sc') or a
* spacecraft ('sc')
* @param segmentId String Identifier of the segment
*/
$scope._pullSlots = function (segmentType, segmentId) {
var rpc_name = segmentType + '.operational';
satnetRPC.rCall(rpc_name, [segmentId]).then(function (results) {
$scope._processSlots(segmentId, results);
}).catch(function (cause) {
snDialog.exception(segmentType + '.operational', '-', cause);
});
};
/**
* Retrieves the slots for all the ground stations owned by the
* currently logged-in user.
* @returns
*/
$scope._pullGsSlots = function () {
satnetRPC.rCall('gs.list.mine', []).then(function (results) {
$scope.gui.gss = results;
for (var i = 0, l = $scope.gui.gss.length;i < l; i++) {
$scope._pullSlots('gs', $scope.gui.gss[i]);
}
}).catch(function (cause) {
snDialog.exception('gs.list.mine', '-', cause);
});
};
/**
* Retrieves the slots for all the spacecraft owned by the
* currently logged-in user.
* @returns
*/
$scope._pullScSlots = function () {
satnetRPC.rCall('sc.list.mine', []).then(function (results) {
$scope.gui.scs = results;
for (var i = 0, l = $scope.gui.scs.length; i < l; i++ ) {
$scope._pullSlots('sc', $scope.gui.scs[i]);
}
}).catch(function (cause) {
snDialog.exception('sc.list.mine', '-', cause);
});
};
/**
* Initialization of the controller.
*/
$scope.init = function () {
$scope._pullGsSlots();
$scope._pullScSlots();
};
$scope.init();
}
])
.controller('snRequestsCtrl', [
'$scope', '$mdDialog',
/**
* Controller function for opening the SatNet requests dialog.
*
* @param {Object} $scope $scope for the controller
* @param {Object} $mdDialog Angular material Dialog service
*/
function ($scope, $mdDialog) {
/**
* Function that opens the dialog when the snRequests button is
* clicked.
*/
$scope.openDialog = function () {
$mdDialog.show({
templateUrl: 'operations/templates/requests/list.html',
controller: 'snRequestsDlgCtrl'
});
};
}
])
.directive('snRequests',
/**
* Function that creates the directive itself returning the object required
* by Angular.
*
* @returns {Object} Object directive required by Angular, with restrict
* and templateUrl
*/
function () {
return {
restrict: 'E',
templateUrl: 'operations/templates/requests/menu.html',
controller: 'snRequestsCtrl'
};
}
);
|
Java
|
package scadla.utils
import scadla._
import squants.space.Length
import scala.language.postfixOps
import squants.space.LengthConversions._
object Tube {
def apply(outerRadius: Length, innerRadius: Length, height: Length) = {
Difference(
Cylinder(outerRadius, height),
Translate(0 mm, 0 mm, -1 mm, Cylinder(innerRadius, height + (2 mm)))
)
}
}
|
Java
|
package web;
import graphUtil.CycleChainDecomposition;
import graphUtil.EdgeChain;
import ilog.concert.IloException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import kepLib.KepInstance;
import kepLib.KepProblemData;
import kepModeler.ChainsForcedRemainOpenOptions;
import kepModeler.KepModeler;
import kepModeler.ModelerInputs;
import kepModeler.ObjectiveMode;
import replicator.DonorEdge;
import threading.FixedThreadPool;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import data.Donor;
import data.ExchangeUnit;
import database.KidneyDataBase;
import exchangeGraph.CycleChainPackingSubtourElimination;
import exchangeGraph.SolverOption;
public class KidneyServerSolver {
private KidneyDataBase database;
private Map<String, ModelerInputs<ExchangeUnit, DonorEdge>> dataCache = new HashMap<String, ModelerInputs<ExchangeUnit, DonorEdge>>();
private Optional<FixedThreadPool> threadPool;
Optional<Double> maxSolveTimeMs = Optional.of(100.0);
public KidneyServerSolver(KidneyDataBase database,
Optional<FixedThreadPool> threadPool) {
this.database = database;
this.threadPool = threadPool;
}
public ImmutableList<String> availableDatasets() {
return database.availableDatasets();
}
public Map<Object, Object> getInputs(String databaseName) {
return flattenModelerInputs(getModelerInputs(databaseName));
}
public Map<Object, Object> getSolution(String databaseName)
throws IloException {
ModelerInputs<ExchangeUnit, DonorEdge> inputs = getModelerInputs(databaseName);
KepModeler modeler = new KepModeler(3, Integer.MAX_VALUE,
ChainsForcedRemainOpenOptions.none,
new ObjectiveMode.MaximumCardinalityMode());
KepInstance<ExchangeUnit, DonorEdge> instance = modeler.makeKepInstance(
inputs, null);
CycleChainPackingSubtourElimination<ExchangeUnit, DonorEdge> solver = new CycleChainPackingSubtourElimination<ExchangeUnit, DonorEdge>(
instance, true, maxSolveTimeMs, threadPool,
SolverOption.makeCheckedOptions(SolverOption.cutsetMode,
SolverOption.lazyConstraintCallback, SolverOption.userCutCallback));
solver.solve();
CycleChainDecomposition<ExchangeUnit, DonorEdge> solution = solver
.getSolution();
solver.cleanUp();
return flattenSolution(inputs.getKepProblemData(), solution);
}
private ModelerInputs<ExchangeUnit, DonorEdge> getModelerInputs(
String databaseName) {
if (this.dataCache.containsKey(databaseName)) {
return this.dataCache.get(databaseName);
} else {
ModelerInputs<ExchangeUnit, DonorEdge> inputs = database
.loadInputs(databaseName);
this.dataCache.put(databaseName, inputs);
return inputs;
}
}
public static Map<Object, Object> flattenModelerInputs(
ModelerInputs<ExchangeUnit, DonorEdge> inputs) {
Map<Object, Object> ans = new HashMap<Object, Object>();
List<Map<Object, Object>> flatUnits = Lists.newArrayList();
List<Map<Object, Object>> flatEdges = Lists.newArrayList();
for (ExchangeUnit unit : inputs.getKepProblemData().getGraph()
.getVertices()) {
flatUnits.add(flattenExchangeUnit(inputs, unit));
}
for (DonorEdge edge : inputs.getKepProblemData().getGraph().getEdges()) {
flatEdges.add(flattenDonorEdge(inputs.getKepProblemData(), edge));
}
ans.put("nodes", flatUnits);
ans.put("links", flatEdges);
return ans;
}
public static Map<Object, Object> flattenSolution(
KepProblemData<ExchangeUnit, DonorEdge> problemData,
CycleChainDecomposition<ExchangeUnit, DonorEdge> solution) {
Map<Object, Object> ans = new HashMap<Object, Object>();
List<Map<Object, Object>> flatEdges = Lists.newArrayList();
for (EdgeChain<DonorEdge> edgeChain : solution.getEdgeChains()) {
for (DonorEdge edge : edgeChain) {
flatEdges.add(flattenDonorEdge(problemData, edge));
}
}
ans.put("links", flatEdges);
return ans;
}
private static Map<Object, Object> flattenDonorEdge(
KepProblemData<ExchangeUnit, DonorEdge> kepProblemData, DonorEdge edge) {
Map<Object, Object> ans = new HashMap<Object, Object>();
ExchangeUnit source = kepProblemData.getGraph().getSource(edge);
ExchangeUnit dest = kepProblemData.getGraph().getDest(edge);
String sourceId = makeNodeId(kepProblemData, source);
String destId = makeNodeId(kepProblemData, dest);
ans.put("sourceId", sourceId);
ans.put("targetId", destId);
ans.put("id", sourceId + destId);
return ans;
}
private static Map<Object, Object> flattenExchangeUnit(
ModelerInputs<ExchangeUnit, DonorEdge> inputs, ExchangeUnit unit) {
Map<Object, Object> ans = new HashMap<Object, Object>();
ans.put("id", makeNodeId(inputs.getKepProblemData(), unit));
ans.put("type", makeType(inputs.getKepProblemData(), unit));
ans.put("reachable", true);
ans.put("sensitized", computeSensitization(inputs, unit));
return ans;
}
private static String makeNodeId(
KepProblemData<ExchangeUnit, DonorEdge> kepProblemData, ExchangeUnit unit) {
if (kepProblemData.getRootNodes().contains(unit)) {
return unit.getDonor().get(0).getId();
} else {
return unit.getReceiver().getId();
}
}
private static String makeType(
KepProblemData<ExchangeUnit, DonorEdge> kepProblemData, ExchangeUnit unit) {
if (kepProblemData.getRootNodes().contains(unit)) {
return "root";
} else if (kepProblemData.getPairedNodes().contains(unit)) {
return "paired";
} else if (kepProblemData.getTerminalNodes().contains(unit)) {
return "terminal";
} else {
throw new RuntimeException();
}
}
private static int computeSensitization(
ModelerInputs<ExchangeUnit, DonorEdge> inputs, ExchangeUnit unit) {
Map<ExchangeUnit, Double> donorPower = inputs.getAuxiliaryInputStatistics()
.getDonorPowerPostPreference();
Map<ExchangeUnit, Double> receiverPower = inputs
.getAuxiliaryInputStatistics().getReceiverPowerPostPreference();
// System.out.println(donorPower);
// System.out.println(receiverPower);
if (inputs.getKepProblemData().getRootNodes().contains(unit)) {
if (donorPower.containsKey(unit.getDonor().get(0))) {
return singlePersonSensitization(donorPower.get(unit.getDonor().get(0)));
} else {
// System.err.println("missing donor power data for: " + unit);
return 0;
}
} else if (inputs.getKepProblemData().getPairedNodes().contains(unit)) {
double unitDonorPower = 0;
for (Donor donor : unit.getDonor()) {
if (donorPower.containsKey(donor)) {
unitDonorPower += donorPower.get(donor);
} else {
// System.err.println("missing donor power data for: " + unit);
return 0;
}
}
if (receiverPower.containsKey(unit.getReceiver())) {
return twoPersonSensitization(unitDonorPower,
receiverPower.get(unit.getReceiver()));
} else {
// System.err.println("missing receiver power for: " + unit);
return 0;
}
} else if (inputs.getKepProblemData().getTerminalNodes().contains(unit)) {
if (receiverPower.containsKey(unit.getReceiver())) {
return singlePersonSensitization(receiverPower.get(unit.getReceiver()));
} else {
// System.err.println("missing receiver power for: " + unit);
return 0;
}
} else {
throw new RuntimeException();
}
}
private static int singlePersonSensitization(double matchPower) {
if (matchPower < .01) {
return 3;
} else if (matchPower < .08) {
return 2;
} else if (matchPower < .2) {
return 1;
} else {
return 0;
}
}
private static int twoPersonSensitization(double donorMatchPower,
double receiverMatchPower) {
double pmp = 10000 * donorMatchPower * receiverMatchPower;
if (pmp < .1) {
return 4;
} else if (pmp < 5) {
return 3;
} else if (pmp < 20) {
return 2;
} else if (pmp < 60) {
return 1;
} else {
return 0;
}
}
}
|
Java
|
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Journey'
db.create_table('places_journey', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('route', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['places.Route'])),
('external_ref', self.gf('django.db.models.fields.TextField')()),
('notes', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('runs_on_monday', self.gf('django.db.models.fields.BooleanField')(default=False)),
('runs_on_tuesday', self.gf('django.db.models.fields.BooleanField')(default=False)),
('runs_on_wednesday', self.gf('django.db.models.fields.BooleanField')(default=False)),
('runs_on_thursday', self.gf('django.db.models.fields.BooleanField')(default=False)),
('runs_on_friday', self.gf('django.db.models.fields.BooleanField')(default=False)),
('runs_on_saturday', self.gf('django.db.models.fields.BooleanField')(default=False)),
('runs_on_sunday', self.gf('django.db.models.fields.BooleanField')(default=False)),
('runs_in_termtime', self.gf('django.db.models.fields.BooleanField')(default=False)),
('runs_in_school_holidays', self.gf('django.db.models.fields.BooleanField')(default=False)),
('runs_on_bank_holidays', self.gf('django.db.models.fields.BooleanField')(default=False)),
('runs_on_non_bank_holidays', self.gf('django.db.models.fields.BooleanField')(default=False)),
('runs_from', self.gf('django.db.models.fields.DateField')()),
('runs_until', self.gf('django.db.models.fields.DateField')()),
('vehicle', self.gf('django.db.models.fields.TextField')()),
))
db.send_create_signal('places', ['Journey'])
# Adding model 'ScheduledStop'
db.create_table('places_scheduledstop', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('entity', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['places.Entity'])),
('journey', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['places.Journey'])),
('order', self.gf('django.db.models.fields.IntegerField')()),
('sta', self.gf('django.db.models.fields.TimeField')(null=True, blank=True)),
('std', self.gf('django.db.models.fields.TimeField')(null=True, blank=True)),
('times_estimated', self.gf('django.db.models.fields.BooleanField')(default=False)),
('fare_stage', self.gf('django.db.models.fields.BooleanField')(default=False)),
('activity', self.gf('django.db.models.fields.CharField')(default='B', max_length=1)),
))
db.send_create_signal('places', ['ScheduledStop'])
def backwards(self, orm):
# Deleting model 'Journey'
db.delete_table('places_journey')
# Deleting model 'ScheduledStop'
db.delete_table('places_scheduledstop')
models = {
'places.entity': {
'Meta': {'object_name': 'Entity'},
'_identifiers': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['places.Identifier']", 'symmetrical': 'False'}),
'_metadata': ('django.db.models.fields.TextField', [], {'default': "'{}'"}),
'absolute_url': ('django.db.models.fields.TextField', [], {}),
'all_types': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'entities'", 'blank': 'True', 'to': "orm['places.EntityType']"}),
'all_types_completion': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'entities_completion'", 'blank': 'True', 'to': "orm['places.EntityType']"}),
'geometry': ('django.contrib.gis.db.models.fields.GeometryField', [], {'null': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['places.EntityGroup']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'identifier_scheme': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'identifier_value': ('django.db.models.fields.CharField', [], {'max_length': '256'}),
'is_stack': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_sublocation': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'location': ('django.contrib.gis.db.models.fields.PointField', [], {'null': 'True'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['places.Entity']", 'null': 'True'}),
'primary_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['places.EntityType']", 'null': 'True'}),
'source': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['places.Source']"})
},
'places.entitygroup': {
'Meta': {'object_name': 'EntityGroup'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'ref_code': ('django.db.models.fields.CharField', [], {'max_length': '256'}),
'source': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['places.Source']"})
},
'places.entitygroupname': {
'Meta': {'unique_together': "(('entity_group', 'language_code'),)", 'object_name': 'EntityGroupName'},
'entity_group': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'names'", 'to': "orm['places.EntityGroup']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language_code': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
'title': ('django.db.models.fields.TextField', [], {})
},
'places.entityname': {
'Meta': {'unique_together': "(('entity', 'language_code'),)", 'object_name': 'EntityName'},
'entity': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'names'", 'to': "orm['places.Entity']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language_code': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
'title': ('django.db.models.fields.TextField', [], {})
},
'places.entitytype': {
'Meta': {'object_name': 'EntityType'},
'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['places.EntityTypeCategory']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'note': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'show_in_category_list': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'show_in_nearby_list': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'db_index': 'True'}),
'subtype_of': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'subtypes'", 'blank': 'True', 'to': "orm['places.EntityType']"}),
'subtype_of_completion': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'subtypes_completion'", 'blank': 'True', 'to': "orm['places.EntityType']"})
},
'places.entitytypecategory': {
'Meta': {'object_name': 'EntityTypeCategory'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.TextField', [], {})
},
'places.entitytypename': {
'Meta': {'unique_together': "(('entity_type', 'language_code'),)", 'object_name': 'EntityTypeName'},
'entity_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'names'", 'to': "orm['places.EntityType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language_code': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
'verbose_name': ('django.db.models.fields.TextField', [], {}),
'verbose_name_plural': ('django.db.models.fields.TextField', [], {}),
'verbose_name_singular': ('django.db.models.fields.TextField', [], {})
},
'places.identifier': {
'Meta': {'object_name': 'Identifier'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'scheme': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'value': ('django.db.models.fields.CharField', [], {'max_length': '256'})
},
'places.journey': {
'Meta': {'object_name': 'Journey'},
'external_ref': ('django.db.models.fields.TextField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'notes': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'route': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['places.Route']"}),
'runs_from': ('django.db.models.fields.DateField', [], {}),
'runs_in_school_holidays': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'runs_in_termtime': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'runs_on_bank_holidays': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'runs_on_friday': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'runs_on_monday': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'runs_on_non_bank_holidays': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'runs_on_saturday': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'runs_on_sunday': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'runs_on_thursday': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'runs_on_tuesday': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'runs_on_wednesday': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'runs_until': ('django.db.models.fields.DateField', [], {}),
'vehicle': ('django.db.models.fields.TextField', [], {})
},
'places.route': {
'Meta': {'object_name': 'Route'},
'external_ref': ('django.db.models.fields.TextField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'operator': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'service_id': ('django.db.models.fields.TextField', [], {}),
'service_name': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'stops': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['places.Entity']", 'through': "orm['places.StopOnRoute']", 'symmetrical': 'False'})
},
'places.scheduledstop': {
'Meta': {'ordering': "['order']", 'object_name': 'ScheduledStop'},
'activity': ('django.db.models.fields.CharField', [], {'default': "'B'", 'max_length': '1'}),
'entity': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['places.Entity']"}),
'fare_stage': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'journey': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['places.Journey']"}),
'order': ('django.db.models.fields.IntegerField', [], {}),
'sta': ('django.db.models.fields.TimeField', [], {'null': 'True', 'blank': 'True'}),
'std': ('django.db.models.fields.TimeField', [], {'null': 'True', 'blank': 'True'}),
'times_estimated': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
},
'places.source': {
'Meta': {'object_name': 'Source'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'module_name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'})
},
'places.stoponroute': {
'Meta': {'ordering': "['order']", 'object_name': 'StopOnRoute'},
'entity': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['places.Entity']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'order': ('django.db.models.fields.IntegerField', [], {}),
'route': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['places.Route']"})
}
}
complete_apps = ['places']
|
Java
|
package com.jaivox.ui.appmaker;
import java.io.*;
import java.util.*;
import bitpix.list.*;
public class Rule2Fsm {
static String dir = "./";
basicTree tree;
TreeMap <String, String> states;
TreeMap <String, String> tags;
static String name = "data/road1.tree";
static String yes = "yes";
String startState = "def";
static String casedefault = "(default) (def)";
static basicNode casedefaultnode;
Vector <String> store;
public Rule2Fsm () {
String filename = dir + name;
startState = startState;
tree = new basicTree (filename);
// tree.WriteTree ();
states = new TreeMap <String, String> ();
tags = new TreeMap <String, String> ();
Vector <bitpix.list.basicNode> list = tree.Root.ListChild;
casedefaultnode = new basicNode (casedefault);
store = new Vector <String> ();
store.add ("\n#include errors.dlg\n");
for (int i=0; i<list.size (); i++) {
basicNode child = list.elementAt (i);
gt (child, startState);
}
int pos = filename.lastIndexOf (".");
String outfile = filename.substring (0, pos+1) + "dlg";
// writefile (outfile, store);
}
void Debug (String s) {
System.out.println ("[Rule2Fsm]" + s);
}
void gt (basicNode node, String sofar) {
Vector <bitpix.list.basicNode> list = node.ListChild;
if (list == null || list.size () == 0) {
// emit a state with def
emit (node, sofar, "def");
}
else {
String nextstate = createNextState (node);
String morefar = sofar + " " + nextstate;
emit (node, sofar, nextstate);
list.add (casedefaultnode);
for (int i=0; i<list.size (); i++) {
basicNode child = list.elementAt (i);
gt (child, morefar);
}
}
}
void emit (basicNode node, String sofar, String next) {
int pos = sofar.lastIndexOf (" ");
pos++;
String last = sofar.substring (pos);
String tag = sofar.replaceAll (" ", "_");
tag = tag + "_" + next;
tag = getuniquetag (tag);
StringBuffer sb = new StringBuffer ();
sb.append ("{\n["+tag+"]\n");
String t = (String)node.Tag;
if (t.trim ().length () == 0) return;
StringTokenizer st = new StringTokenizer (t, "()");
if (st.countTokens () < 2) {
Debug ("Don't have two tokens from "+t);
return;
}
String input = filter (st.nextToken ()).trim ();
String output = filter (st.nextToken ()).trim ();
while (output.length () == 0)
output = filter (st.nextToken ()).trim ();
// Debug ("tag="+t+" / input="+input+" output="+output);
// sb.append ("\t"+sofar+" ;\n");
// with Gui2Gram, convert input and output to use dotted head tag form
String indot = input.replaceAll (" ", ".");
String outdot = output.replaceAll (" ", ".");
sb.append ("\t"+last+" ;\n");
// sb.append ("\t"+input+" ;\n");
// sb.append ("\t"+output+" ;\n");
sb.append ("\t"+indot+" ;\n");
sb.append ("\t"+outdot+" ;\n");
sb.append ("\t"+next+" ;\n");
sb.append ("}\n");
String all = new String (sb);
store.add (all);
// System.out.println (all);
}
static String filter (String line) {
return Gui2Gram.filter (line);
}
String createNextState (basicNode node) {
String tag = (String)(node.Tag);
StringTokenizer st = new StringTokenizer (tag, "()");
if (st.countTokens () < 2) {
Debug ("don't have two tokens in "+tag);
return "def";
}
String input = st.nextToken ().trim ();
String output = st.nextToken ().trim ();
while (output.length () == 0)
output = st.nextToken ().trim ();
StringTokenizer tt = new StringTokenizer (output);
int n = tt.countTokens ();
StringBuffer sb = new StringBuffer ();
for (int i=0; i<Math.min (n, 3); i++) {
String token = tt.nextToken ();
sb.append (token.charAt (0));
}
if (n < 3) {
for (int j=n; j<3; j++) {
sb.append ('x');
}
}
String s = new String (sb);
String test = states.get (s);
if (test != null) {
for (int i=1; i<10; i++) {
String next = s + i;
if (states.get (next) == null) {
s = next;
break;
}
}
}
states.put (s, yes);
return s;
}
String getuniquetag (String in) {
if (tags.get (in) == null) {
tags.put (in, yes);
return in;
}
else {
for (int i=1; i<99; i++) {
String next = in+"_"+i;
if (tags.get (next) != null) {
continue;
}
tags.put (next, yes);
return next;
}
Debug ("More than 99 tags starting with "+in);
return "error";
}
}
void writeRules (PrintWriter out) {
try {
for (int i=0; i<store.size (); i++) {
out.println (store.elementAt (i));
}
}
catch (Exception e) {
e.printStackTrace ();
}
}
}
|
Java
|
# Unona pilosa (Baill.) Baill. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
/*
* Copyright (C) 2012 Jason Gedge <http://www.gedge.ca>
*
* This file is part of the OpGraph project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Provides commands for the Application API.
*/
package ca.phon.opgraph.app.commands;
|
Java
|
<?php
class Gep_ScoreController extends Zend_Controller_Action {
public function init()
{
/* Initialize action controller here */
header('content-type: text/html; charset=utf8');
}
public function indexAction(){
}
public function fullResultAction(){
}
}
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Wed Jan 16 10:54:22 MST 2019 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.wildfly.swarm.jaeger (BOM: * : All 2.3.0.Final-SNAPSHOT API)</title>
<meta name="date" content="2019-01-16">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<h1 class="bar"><a href="../../../../org/wildfly/swarm/jaeger/package-summary.html" target="classFrame">org.wildfly.swarm.jaeger</a></h1>
<div class="indexContainer">
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="JaegerFraction.html" title="class in org.wildfly.swarm.jaeger" target="classFrame">JaegerFraction</a></li>
</ul>
</div>
</body>
</html>
|
Java
|
/*
* Copyright 2013 DigitasLBi Netherlands B.V.
*
* 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.
*/
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.Diagnostics;
using LBi.Cli.Arguments;
namespace LBi.LostDoc.ConsoleApplication.Extensibility
{
public abstract class Command : ICommand
{
[Parameter(HelpMessage = "Include errors and warning output only.")]
public LBi.Cli.Arguments.Switch Quiet { get; set; }
[Parameter(HelpMessage = "Include verbose output.")]
public LBi.Cli.Arguments.Switch Verbose { get; set; }
public abstract void Invoke(CompositionContainer container);
protected void ConfigureTraceLevels(IEnumerable<TraceSource> sources)
{
SourceLevels currentLevel;
if (this.Quiet.IsPresent)
{
currentLevel = SourceLevels.Error | SourceLevels.Warning | SourceLevels.Critical;
}
else if (this.Verbose.IsPresent)
{
currentLevel = SourceLevels.All;
}
else
{
currentLevel = SourceLevels.Information |
SourceLevels.Warning |
SourceLevels.Error |
SourceLevels.Critical |
SourceLevels.ActivityTracing;
}
foreach (TraceSource source in sources)
source.Switch.Level = currentLevel;
}
}
}
|
Java
|
CREATE TABLE TASK_EXECUTION (
TASK_EXECUTION_ID BIGINT NOT NULL PRIMARY KEY ,
START_TIME DATETIME DEFAULT NULL ,
END_TIME DATETIME DEFAULT NULL ,
TASK_NAME VARCHAR(100) ,
EXIT_CODE INTEGER ,
EXIT_MESSAGE VARCHAR(2500) ,
ERROR_MESSAGE VARCHAR(2500) ,
LAST_UPDATED DATETIME ,
EXTERNAL_EXECUTION_ID VARCHAR(255),
PARENT_EXECUTION_ID BIGINT
);
CREATE TABLE TASK_EXECUTION_PARAMS (
TASK_EXECUTION_ID BIGINT NOT NULL ,
TASK_PARAM VARCHAR(2500) ,
constraint TASK_EXEC_PARAMS_FK foreign key (TASK_EXECUTION_ID)
references TASK_EXECUTION(TASK_EXECUTION_ID)
) ;
CREATE TABLE TASK_TASK_BATCH (
TASK_EXECUTION_ID BIGINT NOT NULL ,
JOB_EXECUTION_ID BIGINT NOT NULL ,
constraint TASK_EXEC_BATCH_FK foreign key (TASK_EXECUTION_ID)
references TASK_EXECUTION(TASK_EXECUTION_ID)
) ;
CREATE TABLE TASK_SEQ (ID BIGINT IDENTITY);
|
Java
|
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../../style.css');
@import url('../../../../../tree.css');
</style>
<script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../../clover.js" type="text/javascript"></script>
<script src="../../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../../cloud.js" type="text/javascript"></script>
<title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title>
</head>
<body>
<div id="page">
<header id="header" role="banner">
<nav class="aui-header aui-dropdown2-trigger-group" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo aui-header-logo-clover">
<a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a>
</h1>
</div>
<div class="aui-header-secondary">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online documentation" target="_blank"
href="http://openclover.org/documentation">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="aui-page-panel-inner">
<div class="aui-page-panel-nav aui-page-panel-nav-clover">
<div class="aui-page-header-inner" style="margin-bottom: 20px;">
<div class="aui-page-header-image">
<a href="http://cardatechnologies.com" target="_top">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</a>
</div>
<div class="aui-page-header-main" >
<h1>
<a href="http://cardatechnologies.com" target="_top">
ABA Route Transit Number Validator 1.0.1-SNAPSHOT
</a>
</h1>
</div>
</div>
<nav class="aui-navgroup aui-navgroup-vertical">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading packages-nav-heading">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui package-filter-container">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="package-filter-no-results-message hidden">
<small>No results found.</small>
</p>
<div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator">
<div class="packages-tree-container"></div>
<div class="clover-packages-lozenges"></div>
</div>
</div>
</div>
</nav> </div>
<section class="aui-page-panel-content">
<div class="aui-page-panel-content-clover">
<div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li>
<li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li>
<li><a href="test-Test_AbaRouteValidator_03.html">Class Test_AbaRouteValidator_03</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_3149_good
</h1>
<table class="aui">
<thead>
<tr>
<th>Test</th>
<th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th>
<th><label title="When the test execution was started">Start time</label></th>
<th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th>
<th><label title="A failure or error message if the test is not successful.">Message</label></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_03.html?line=15641#src-15641" >testAbaNumberCheck_3149_good</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:33:30
</td>
<td>
0.0 </td>
<td>
<div></div>
<div class="errorMessage"></div>
</td>
</tr>
</tbody>
</table>
<div> </div>
<table class="aui aui-table-sortable">
<thead>
<tr>
<th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th>
<th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_3149_good</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=27318#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.7352941</span>73.5%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td>
</tr>
</tbody>
</table>
</div> <!-- class="aui-page-panel-content-clover" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1
on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT.
</li>
</ul>
<ul>
<li>OpenClover is free and open-source software. </li>
</ul>
</section>
</footer> </section> <!-- class="aui-page-panel-content" -->
</div> <!-- class="aui-page-panel-inner" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html>
|
Java
|
--!A cross-platform build utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2019, TBOOX Open Source Group.
--
-- @author ruki
-- @file vs201x_solution.lua
--
-- imports
import("core.project.project")
import("vsfile")
-- make header
function _make_header(slnfile, vsinfo)
slnfile:print("Microsoft Visual Studio Solution File, Format Version %s.00", vsinfo.solution_version)
slnfile:print("# Visual Studio %s", vsinfo.vstudio_version)
end
-- make projects
function _make_projects(slnfile, vsinfo)
-- the vstudio tool uuid for vc project
local vctool = "8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942"
-- make all targets
for targetname, target in pairs(project.targets()) do
if not target:isphony() then
-- enter project
slnfile:enter("Project(\"{%s}\") = \"%s\", \"%s\\%s.vcxproj\", \"{%s}\"", vctool, targetname, targetname, targetname, hash.uuid(targetname))
-- add dependences
for _, dep in ipairs(target:get("deps")) do
slnfile:enter("ProjectSection(ProjectDependencies) = postProject")
slnfile:print("{%s} = {%s}", hash.uuid(dep), hash.uuid(dep))
slnfile:leave("EndProjectSection")
end
-- leave project
slnfile:leave("EndProject")
end
end
end
-- make global
function _make_global(slnfile, vsinfo)
-- enter global
slnfile:enter("Global")
-- add solution configuration platforms
slnfile:enter("GlobalSection(SolutionConfigurationPlatforms) = preSolution")
for _, mode in ipairs(vsinfo.modes) do
for _, arch in ipairs(vsinfo.archs) do
slnfile:print("%s|%s = %s|%s", mode, arch, mode, arch)
end
end
slnfile:leave("EndGlobalSection")
-- add project configuration platforms
slnfile:enter("GlobalSection(ProjectConfigurationPlatforms) = postSolution")
for targetname, target in pairs(project.targets()) do
if not target:isphony() then
for _, mode in ipairs(vsinfo.modes) do
for _, arch in ipairs(vsinfo.archs) do
slnfile:print("{%s}.%s|%s.ActiveCfg = %s|%s", hash.uuid(targetname), mode, arch, mode, arch)
slnfile:print("{%s}.%s|%s.Build.0 = %s|%s", hash.uuid(targetname), mode, arch, mode, arch)
end
end
end
end
slnfile:leave("EndGlobalSection")
-- add solution properties
slnfile:enter("GlobalSection(SolutionProperties) = preSolution")
slnfile:print("HideSolutionNode = FALSE")
slnfile:leave("EndGlobalSection")
-- leave global
slnfile:leave("EndGlobal")
end
-- make solution
function make(vsinfo)
-- init solution name
vsinfo.solution_name = project.name() or "vs" .. vsinfo.vstudio_version
-- open solution file
local slnpath = path.join(vsinfo.solution_dir, vsinfo.solution_name .. ".sln")
local slnfile = vsfile.open(slnpath, "w")
-- init indent character
vsfile.indentchar('\t')
-- make header
_make_header(slnfile, vsinfo)
-- make projects
_make_projects(slnfile, vsinfo)
-- make global
_make_global(slnfile, vsinfo)
-- exit solution file
slnfile:close()
-- convert gb2312 to utf8
io.writefile(slnpath, io.readfile(slnpath):convert("gb2312", "utf8"))
end
|
Java
|
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoBusinessAllV2(t *testing.T) {
convey.Convey("BusinessAllV2", t, func(convCtx convey.C) {
var (
c = context.Background()
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
list, err := d.BusinessAllV2(c)
convCtx.Convey("Then err should be nil.list should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(list, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoBusinessInfoV2(t *testing.T) {
convey.Convey("BusinessInfoV2", t, func(convCtx convey.C) {
var (
c = context.Background()
name = "dm"
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
b, err := d.BusinessInfoV2(c, name)
convCtx.Convey("Then err should be nil.b should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(b, convey.ShouldNotBeNil)
})
})
})
}
//func TestDaoBusinessIns(t *testing.T) {
// convey.Convey("BusinessIns", t, func(convCtx convey.C) {
// var (
// c = context.Background()
// pid = int64(0)
// name = ""
// description = ""
// )
// convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
// rows, err := d.BusinessIns(c, pid, name, description)
// convCtx.Convey("Then err should be nil.rows should not be nil.", func(convCtx convey.C) {
// convCtx.So(err, convey.ShouldBeNil)
// convCtx.So(rows, convey.ShouldNotBeNil)
// })
// })
// })
//}
//func TestDaoBusinessUpdate(t *testing.T) {
// convey.Convey("BusinessUpdate", t, func(convCtx convey.C) {
// var (
// c = context.Background()
// name = ""
// field = ""
// value = ""
// )
// convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
// rows, err := d.BusinessUpdate(c, name, field, value)
// convCtx.Convey("Then err should be nil.rows should not be nil.", func(convCtx convey.C) {
// convCtx.So(err, convey.ShouldBeNil)
// convCtx.So(rows, convey.ShouldNotBeNil)
// })
// })
// })
//}
func TestDaoAssetDBTables(t *testing.T) {
convey.Convey("AssetDBTables", t, func(convCtx convey.C) {
var (
c = context.Background()
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
list, err := d.AssetDBTables(c)
convCtx.Convey("Then err should be nil.list should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(list, convey.ShouldNotBeNil)
})
})
})
}
//
//func TestDaoAssetDBIns(t *testing.T) {
// convey.Convey("AssetDBIns", t, func(convCtx convey.C) {
// var (
// c = context.Background()
// name = ""
// description = ""
// dsn = ""
// )
// convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
// rows, err := d.AssetDBIns(c, name, description, dsn)
// convCtx.Convey("Then err should be nil.rows should not be nil.", func(convCtx convey.C) {
// convCtx.So(err, convey.ShouldBeNil)
// convCtx.So(rows, convey.ShouldNotBeNil)
// })
// })
// })
//}
//func TestDaoAssetTableIns(t *testing.T) {
// convey.Convey("AssetTableIns", t, func(convCtx convey.C) {
// var (
// c = context.Background()
// name = ""
// db = ""
// regex = ""
// fields = ""
// description = ""
// )
// convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
// rows, err := d.AssetTableIns(c, name, db, regex, fields, description)
// convCtx.Convey("Then err should be nil.rows should not be nil.", func(convCtx convey.C) {
// convCtx.So(err, convey.ShouldBeNil)
// convCtx.So(rows, convey.ShouldNotBeNil)
// })
// })
// })
//}
func TestDaoAsset(t *testing.T) {
convey.Convey("Asset", t, func(convCtx convey.C) {
var (
c = context.Background()
name = "bilibili_article"
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
r, err := d.Asset(c, name)
convCtx.Convey("Then err should be nil.r should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(r, convey.ShouldNotBeNil)
})
})
})
}
|
Java
|
using UnityEngine;
namespace DefaultNamespace
{
public class FieldGenerationWithRespectToCodeStyleTest : MonoBehaviour
{
public void Update()
{
int[,] test = new int[2,2];
test[0, 0] = 5;
test[test[0,{caret} 1], test[0, test[0,1]]] = 5;
}
}
}
|
Java
|
/*
* Copyright 2013 JCertifLab.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jcertif.android.fragments;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Events;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jcertif.android.JcertifApplication;
import com.jcertif.android.MainActivity;
import com.jcertif.android.R;
import com.jcertif.android.adapters.SessionAdapter;
import com.jcertif.android.adapters.SpeedScrollListener;
import com.jcertif.android.dao.SessionProvider;
import com.jcertif.android.dao.SpeakerProvider;
import com.jcertif.android.model.Session;
import com.jcertif.android.model.Speaker;
import com.jcertif.android.service.RESTService;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import uk.co.senab.actionbarpulltorefresh.extras.actionbarsherlock.PullToRefreshAttacher;
/**
*
* @author Patrick Bashizi
*
*/
public class SessionListFragment extends RESTResponderFragment implements PullToRefreshAttacher.OnRefreshListener{
public static final String SESSIONS_LIST_URI = JcertifApplication.BASE_URL
+ "/session/list";
public static final String CATEGORY_LIST_URI = JcertifApplication.BASE_URL
+ "/ref/category/list";
private static String TAG = SessionListFragment.class.getName();
private List<Session> mSessions = new ArrayList<Session>();;
private ListView mLvSessions;
private SessionAdapter mAdapter;
private SessionProvider mProvider;
private SpeedScrollListener mListener;
private ActionMode mActionMode;
private Session mSelectedSession;
private PullToRefreshAttacher mPullToRefreshAttacher ;
public SessionListFragment() {
// Empty constructor required for fragment subclasses
}
public interface OnSessionUpdatedListener {
void onSessionUpdated(Session session);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// setRetainInstance(true);
View rootView = inflater.inflate(R.layout.fragment_session, container,
false);
mLvSessions = (ListView) rootView.findViewById(R.id.lv_session);
String session = getResources().getStringArray(R.array.menu_array)[0];
setHasOptionsMenu(true);
getActivity().setTitle(session);
mLvSessions = (ListView) rootView.findViewById(R.id.lv_session);
mPullToRefreshAttacher=((MainActivity)getSherlockActivity()).getmPullToRefreshAttacher();
mPullToRefreshAttacher.addRefreshableView(mLvSessions, this);
mLvSessions.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int pos,
long position) {
mAdapter.setSelectedIndex(pos);
mSelectedSession = ((Session) parent
.getItemAtPosition((int) position));
updateSession(mSelectedSession);
}
});
mLvSessions
.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0,
View arg1, int pos, long arg3) {
if (mActionMode != null) {
return false;
}
mActionMode = getSherlockActivity().startActionMode(
mActionModeCallback);
mSelectedSession = ((Session) arg0
.getItemAtPosition((int) pos));
mAdapter.setSelectedIndex(pos);
return true;
}
});
return rootView;
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_menu_session, menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_share:
shareSessionItem();
mode.finish(); // Action picked, so close the CAB
break;
case R.id.menu_add_to_schedule:
addSessionItemToSchedule();
mode.finish(); // Action picked, so close the CAB
break;
default:
return false;
}
return true;
}
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
};
private void addSessionItemToSchedule() {
if (android.os.Build.VERSION.SDK_INT >= 14){
Intent intent = new Intent(Intent.ACTION_INSERT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra(Events.TITLE, mSelectedSession.getTitle());
intent.putExtra(Events.EVENT_LOCATION,"Room"+ mSelectedSession.getSalle());
intent.putExtra(Events.DESCRIPTION, mSelectedSession.getDescription());
Date evStartDate= mSelectedSession.getStart();
Date evEndDate= mSelectedSession.getStart();
// Setting dates
GregorianCalendar startcalDate = new GregorianCalendar();
startcalDate.setTime(evStartDate);
// Setting dates
GregorianCalendar endCalDate = new GregorianCalendar();
endCalDate.setTime(evEndDate);
intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME,startcalDate.getTimeInMillis());
intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME,endCalDate.getTimeInMillis());
// Make it a full day event
intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true);
// Make it a recurring Event
// intent.putExtra(Events.RRULE, "WKST=SU");
// Making it private and shown as busy
intent.putExtra(Events.ACCESS_LEVEL, Events.ACCESS_PRIVATE);
intent.putExtra(Events.AVAILABILITY, Events.AVAILABILITY_BUSY);
//intent.putExtra(Events.DISPLAY_COLOR, Events.EVENT_COLOR);
startActivity(intent);
}else{
Toast.makeText(this.getSherlockActivity(),
"Not supported for your device :(", Toast.LENGTH_SHORT).show();
}
}
private void shareSessionItem() {
Speaker sp = new SpeakerProvider(this.getSherlockActivity())
.getByEmail(mSelectedSession.getSpeakers()[0]);
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
intent.putExtra(Intent.EXTRA_SUBJECT, "Share Session");
intent.putExtra(
Intent.EXTRA_TEXT,
"Checking out this #Jcertif2013 session : "
+ mSelectedSession.getTitle() + " by "
+ sp.getFirstname() + " " + sp.getLastname());
startActivity(intent);
}
protected void updateSession(Session s) {
if(onTablet()){
((OnSessionUpdatedListener) getParentFragment()).onSessionUpdated(s);
}else{
Intent intent = new Intent(this.getActivity().getApplicationContext(),
SessionDetailFragmentActivity.class);
String sessionJson= new Gson().toJson(s);
intent.putExtra("session",sessionJson);
startActivity(intent);
getSherlockActivity().overridePendingTransition ( 0 , R.anim.slide_up_left);
}
}
public SessionProvider getProvider() {
if (mProvider == null)
mProvider = new SessionProvider(this.getSherlockActivity());
return mProvider;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// This gets called each time our Activity has finished creating itself.
// First check the local cache, if it's empty data will be fetched from
// web
mSessions = loadSessionsFromCache();
setSessions();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
/**
* We cache our stored session here so that we can return right away on
* multiple calls to setSession() during the Activity lifecycle events (such
* as when the user rotates their device).
*/
private void setSessions() {
MainActivity activity = (MainActivity) getActivity();
setLoading(true);
if (mSessions.isEmpty() && activity != null) {
// This is where we make our REST call to the service. We also pass
// in our ResultReceiver
// defined in the RESTResponderFragment super class.
// We will explicitly call our Service since we probably want to
// keep it as a private component in our app.
Intent intent = new Intent(activity, RESTService.class);
intent.setData(Uri.parse(SESSIONS_LIST_URI));
// Here we are going to place our REST call parameters.
Bundle params = new Bundle();
params.putString(RESTService.KEY_JSON_PLAYLOAD, null);
intent.putExtra(RESTService.EXTRA_PARAMS, params);
intent.putExtra(RESTService.EXTRA_RESULT_RECEIVER,getResultReceiver());
// Here we send our Intent to our RESTService.
activity.startService(intent);
} else if (activity != null) {
// Here we check to see if our activity is null or not.
// We only want to update our views if our activity exists.
// Load our list adapter with our session.
updateList();
setLoading(false);
}
}
void updateList() {
mListener = new SpeedScrollListener();
mLvSessions.setOnScrollListener(mListener);
mAdapter = new SessionAdapter(this.getActivity(), mListener, mSessions);
mLvSessions.setAdapter(mAdapter);
if(refreshing){
refreshing=false;
mPullToRefreshAttacher.setRefreshComplete();
}
}
private boolean onTablet() {
return ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE);
}
public void updateList(String cat) {
if (cat.equals("All") || cat.equals("Tous")) {
mSessions = loadSessionsFromCache();
} else {
mSessions = getProvider().getSessionsByCategory(cat);
}
updateList();
}
@Override
public void onRESTResult(int code, Bundle resultData) {
// Here is where we handle our REST response.
// Check to see if we got an HTTP 200 code and have some data.
String result = null;
if (resultData != null) {
result = resultData.getString(RESTService.REST_RESULT);
} else {
return;
}
if (code == 200 && result != null) {
mSessions = parseSessionJson(result);
Log.d(TAG, result);
setSessions();
saveToCache(mSessions);
} else {
Activity activity = getActivity();
if (activity != null) {
Toast.makeText(
activity,
"Failed to load Session data. Check your internet settings.",
Toast.LENGTH_SHORT).show();
}
}
setLoading(false);
}
private List<Session> parseSessionJson(String result) {
Gson gson = new GsonBuilder().setDateFormat("dd/MM/yyyy hh:mm")
.create();
Session[] sessions = gson.fromJson(result, Session[].class);
return Arrays.asList(sessions);
}
protected void saveToCache(final List<Session> sessions) {
new Thread(new Runnable() {
@Override
public void run() {
for (Session session : sessions)
mProvider.store(session);
}
}).start();
}
private List<Session> loadSessionsFromCache() {
List<Session> list = getProvider().getAll(Session.class);
return list;
}
@Override
public void onPause() {
super.onDestroy();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onRefreshStarted(View view) {
mProvider.deleteAll(Session.class);
//mLvSessions.setAdapter(null);
mSessions = loadSessionsFromCache();
setSessions();
refreshing=true;
}
}
|
Java
|
/**
* Copyright 2014 Jordan Zimmerman
*
* 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.soabase.core.features.attributes;
import io.soabase.core.listening.Listenable;
import java.util.Collection;
/**
* Gives access to dynamic attributes. The various get methods return
* the current value for the given key after applying overrides and scopes, etc.
* Always call the methods to get the current value as it may change during runtime.
*/
public interface DynamicAttributes
{
public String getAttribute(String key);
public String getAttribute(String key, String defaultValue);
public boolean getAttributeBoolean(String key);
public boolean getAttributeBoolean(String key, boolean defaultValue);
public int getAttributeInt(String key);
public int getAttributeInt(String key, int defaultValue);
public long getAttributeLong(String key);
public long getAttributeLong(String key, long defaultValue);
public double getAttributeDouble(String key);
public double getAttributeDouble(String key, double defaultValue);
public void temporaryOverride(String key, boolean value);
public void temporaryOverride(String key, int value);
public void temporaryOverride(String key, long value);
public void temporaryOverride(String key, double value);
public void temporaryOverride(String key, String value);
public boolean removeOverride(String key);
public Collection<String> getKeys();
public Listenable<DynamicAttributeListener> getListenable();
}
|
Java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
AfterContentInit,
ChangeDetectionStrategy,
Component,
ElementRef,
EventEmitter,
Input,
OnInit,
Output,
ViewChild
} from '@angular/core';
import * as d3 from 'd3';
import { select, Selection } from 'd3-selection';
import { zoom, ZoomBehavior } from 'd3-zoom';
import { SafeAny } from 'interfaces';
@Component({
selector: 'flink-svg-container',
templateUrl: './svg-container.component.html',
styleUrls: ['./svg-container.component.less'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class SvgContainerComponent implements OnInit, AfterContentInit {
zoom = 1;
width: number;
height: number;
transform = 'translate(0, 0) scale(1)';
containerTransform = { x: 0, y: 0, k: 1 };
svgSelect: Selection<SafeAny, SafeAny, SafeAny, SafeAny>;
zoomController: ZoomBehavior<SafeAny, SafeAny>;
@ViewChild('svgContainer', { static: true }) svgContainer: ElementRef<SVGAElement>;
@ViewChild('svgInner', { static: true }) svgInner: ElementRef<SVGAElement>;
@Input() nzMaxZoom = 5;
@Input() nzMinZoom = 0.1;
@Output() clickBgEvent: EventEmitter<MouseEvent> = new EventEmitter();
@Output() zoomEvent: EventEmitter<number> = new EventEmitter();
@Output() transformEvent: EventEmitter<{ x: number; y: number; scale: number }> = new EventEmitter();
/**
* Zoom to spec level
*
* @param zoomLevel
*/
zoomTo(zoomLevel: number): void {
this.svgSelect
.transition()
.duration(0)
.call(this.zoomController.scaleTo, zoomLevel);
}
/**
* Set transform position
*
* @param transform
* @param animate
*/
setPositionByTransform(transform: { x: number; y: number; k: number }, animate = false): void {
this.svgSelect
.transition()
.duration(animate ? 500 : 0)
.call(this.zoomController.transform, transform);
}
constructor(private el: ElementRef) {}
ngOnInit(): void {
this.svgSelect = select(this.svgContainer.nativeElement);
this.zoomController = zoom()
.scaleExtent([this.nzMinZoom, this.nzMaxZoom])
.on('zoom', () => {
this.containerTransform = d3.event.transform;
this.zoom = this.containerTransform.k;
if (!isNaN(this.containerTransform.x)) {
this.transform = `translate(${this.containerTransform.x} ,${this.containerTransform.y})scale(${this.containerTransform.k})`;
}
this.zoomEvent.emit(this.zoom);
this.transformEvent.emit(this.containerTransform as SafeAny);
});
this.svgSelect.call(this.zoomController).on('wheel.zoom', null);
}
ngAfterContentInit(): void {
const hostElem = this.el.nativeElement;
if (hostElem.parentNode !== null) {
const dims = hostElem.parentNode.getBoundingClientRect();
this.width = dims.width;
this.height = dims.height;
this.zoomTo(this.zoom);
}
}
}
|
Java
|
/*
* Copyright © 2009 HotPads (admin@hotpads.com)
*
* 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.datarouter.instrumentation.trace;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
import java.util.Random;
import java.util.regex.Pattern;
public class Traceparent{
private static final Pattern TRACEPARENT_PATTERN = Pattern.compile(
"^[0-9a-f]{2}-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$");
private static final String TRACEPARENT_DELIMITER = "-";
private static final Integer MIN_CHARS_TRACEPARENT = 55;
private static final String CURRENT_VERSION = "00";
public static final int TRACE_ID_HEX_SIZE = 32;
public static final int PARENT_ID_HEX_SIZE = 16;
public final String version = CURRENT_VERSION;
public final String traceId;
public final String parentId;
private String traceFlags;
public Traceparent(String traceId, String parentId, String traceFlags){
this.traceId = traceId;
this.parentId = parentId;
this.traceFlags = traceFlags;
}
public Traceparent(String traceId){
this(traceId, createNewParentId());
}
public Traceparent(String traceId, String parentId){
this(traceId, parentId, createDefaultTraceFlag());
}
public static Traceparent generateNew(long createdTimestamp){
return new Traceparent(createNewTraceId(createdTimestamp), createNewParentId(),
createDefaultTraceFlag());
}
public static Traceparent generateNewWithCurrentTimeInNs(){
return new Traceparent(createNewTraceId(Trace2Dto.getCurrentTimeInNs()), createNewParentId(),
createDefaultTraceFlag());
}
public Traceparent updateParentId(){
return new Traceparent(traceId, createNewParentId(), traceFlags);
}
/*
* TraceId is a 32 hex digit String. We convert the root request created unix time into lowercase base16
* and append it with a randomly generated long lowercase base16 representation.
* */
private static String createNewTraceId(long createdTimestamp){
return String.format("%016x", createdTimestamp) + String.format("%016x", new Random().nextLong());
}
/*
* ParentId is a 16 hex digit String. We use a randomly generated long and convert it into lowercase base16
* representation.
* */
public static String createNewParentId(){
return String.format("%016x", new Random().nextLong());
}
public long getTimestampInMs(){
return Long.parseLong(traceId.substring(0, 16), 16);
}
public Instant getInstant(){
return Instant.ofEpochMilli(getTimestampInMs());
}
/*----------- trace flags ------------*/
private static String createDefaultTraceFlag(){
return TraceContextFlagMask.DEFAULT.toHexCode();
}
public void enableSample(){
this.traceFlags = TraceContextFlagMask.enableTrace(traceFlags);
}
public void enableLog(){
this.traceFlags = TraceContextFlagMask.enableLog(traceFlags);
}
public boolean shouldSample(){
return TraceContextFlagMask.isTraceEnabled(traceFlags);
}
public boolean shouldLog(){
return TraceContextFlagMask.isLogEnabled(traceFlags);
}
@Override
public String toString(){
return String.join(TRACEPARENT_DELIMITER, version, traceId, parentId, traceFlags);
}
@Override
public boolean equals(Object obj){
if(!(obj instanceof Traceparent)){
return false;
}
Traceparent other = (Traceparent)obj;
return Objects.equals(version, other.version)
&& Objects.equals(traceId, other.traceId)
&& Objects.equals(parentId, other.parentId)
&& Objects.equals(traceFlags, other.traceFlags);
}
@Override
public int hashCode(){
return Objects.hash(version, traceId, parentId, traceFlags);
}
public static Optional<Traceparent> parse(String traceparentStr){
if(traceparentStr == null || traceparentStr.isEmpty()){
return Optional.empty();
}else if(traceparentStr.length() < MIN_CHARS_TRACEPARENT){
return Optional.empty();
}else if(!TRACEPARENT_PATTERN.matcher(traceparentStr).matches()){
return Optional.empty();
}
String[] tokens = traceparentStr.split(Traceparent.TRACEPARENT_DELIMITER);
if(!Traceparent.CURRENT_VERSION.equals(tokens[0])){
return Optional.empty();
}
return Optional.of(new Traceparent(tokens[1], tokens[2], tokens[3]));
}
}
|
Java
|
package com.bzu.yhd.pocketcampus.bottomnav.user.view;
import android.content.Context;
import android.util.AttributeSet;
import com.facebook.rebound.SimpleSpringListener;
import com.facebook.rebound.Spring;
import com.facebook.rebound.SpringSystem;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* Created by xmuSistone.
*/
public class AnimateImageView extends CircleImageView {
private Spring springX, springY;
private SimpleSpringListener followerListenerX, followerListenerY; // 此为跟踪的回调,当前面一个view移动的时候,此为后面的view,需要更新endValue
public AnimateImageView(Context context) {
this(context, null);
}
public AnimateImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public AnimateImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
SpringSystem mSpringSystem = SpringSystem.create();
springX = mSpringSystem.createSpring();
springY = mSpringSystem.createSpring();
springX.addListener(new SimpleSpringListener() {
@Override
public void onSpringUpdate(Spring spring) {
int xPos = (int) spring.getCurrentValue();
setScreenX(xPos);
}
});
springY.addListener(new SimpleSpringListener() {
@Override
public void onSpringUpdate(Spring spring) {
int yPos = (int) spring.getCurrentValue();
setScreenY(yPos);
}
});
followerListenerX = new SimpleSpringListener() {
@Override
public void onSpringUpdate(Spring spring) {
int xPos = (int) spring.getCurrentValue();
springX.setEndValue(xPos);
}
};
followerListenerY = new SimpleSpringListener() {
@Override
public void onSpringUpdate(Spring spring) {
int yPos = (int) spring.getCurrentValue();
springY.setEndValue(yPos);
}
};
}
private void setScreenX(int screenX) {
this.offsetLeftAndRight(screenX - getLeft());
}
private void setScreenY(int screenY) {
this.offsetTopAndBottom(screenY - getTop());
}
public void animTo(int xPos, int yPos) {
springX.setEndValue(xPos);
springY.setEndValue(yPos);
}
/**
* 顶部ImageView强行停止动画
*/
public void stopAnimation() {
springX.setAtRest();
springY.setAtRest();
}
/**
* 只为最顶部的view调用,触点松开后,回归原点
*/
public void onRelease(int xPos, int yPos) {
setCurrentSpringPos(getLeft(), getTop());
animTo(xPos, yPos);
}
/**
* 设置当前spring位置
*/
public void setCurrentSpringPos(int xPos, int yPos) {
springX.setCurrentValue(xPos);
springY.setCurrentValue(yPos);
}
public Spring getSpringX() {
return springX;
}
public Spring getSpringY() {
return springY;
}
public SimpleSpringListener getFollowerListenerX() {
return followerListenerX;
}
public SimpleSpringListener getFollowerListenerY() {
return followerListenerY;
}
}
|
Java
|
import Vue from 'vue'
import { hasFetch, normalizeError, addLifecycleHook } from '../utils'
const isSsrHydration = (vm) => vm.$vnode && vm.$vnode.elm && vm.$vnode.elm.dataset && vm.$vnode.elm.dataset.fetchKey
const nuxtState = window.<%= globals.context %>
export default {
beforeCreate () {
if (!hasFetch(this)) {
return
}
this._fetchDelay = typeof this.$options.fetchDelay === 'number' ? this.$options.fetchDelay : 200
Vue.util.defineReactive(this, '$fetchState', {
pending: false,
error: null,
timestamp: Date.now()
})
this.$fetch = $fetch.bind(this)
addLifecycleHook(this, 'created', created)
addLifecycleHook(this, 'beforeMount', beforeMount)
}
}
function beforeMount() {
if (!this._hydrated) {
return this.$fetch()
}
}
function created() {
if (!isSsrHydration(this)) {
return
}
// Hydrate component
this._hydrated = true
this._fetchKey = +this.$vnode.elm.dataset.fetchKey
const data = nuxtState.fetch[this._fetchKey]
// If fetch error
if (data && data._error) {
this.$fetchState.error = data._error
return
}
// Merge data
for (const key in data) {
Vue.set(this.$data, key, data[key])
}
}
async function $fetch() {
this.$nuxt.nbFetching++
this.$fetchState.pending = true
this.$fetchState.error = null
this._hydrated = false
let error = null
const startTime = Date.now()
try {
await this.$options.fetch.call(this)
} catch (err) {
error = normalizeError(err)
}
const delayLeft = this._fetchDelay - (Date.now() - startTime)
if (delayLeft > 0) {
await new Promise(resolve => setTimeout(resolve, delayLeft))
}
this.$fetchState.error = error
this.$fetchState.pending = false
this.$fetchState.timestamp = Date.now()
this.$nextTick(() => this.$nuxt.nbFetching--)
}
|
Java
|
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simplesystemsmanagement.model.transform;
import static com.amazonaws.util.StringUtils.UTF8;
import static com.amazonaws.util.StringUtils.COMMA_SEPARATOR;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;
import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.simplesystemsmanagement.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;
/**
* DeleteAssociationRequest Marshaller
*/
public class DeleteAssociationRequestMarshaller implements
Marshaller<Request<DeleteAssociationRequest>, DeleteAssociationRequest> {
public Request<DeleteAssociationRequest> marshall(
DeleteAssociationRequest deleteAssociationRequest) {
if (deleteAssociationRequest == null) {
throw new AmazonClientException(
"Invalid argument passed to marshall(...)");
}
Request<DeleteAssociationRequest> request = new DefaultRequest<DeleteAssociationRequest>(
deleteAssociationRequest, "AWSSimpleSystemsManagement");
request.addHeader("X-Amz-Target", "AmazonSSM.DeleteAssociation");
request.setHttpMethod(HttpMethodName.POST);
request.setResourcePath("");
try {
StringWriter stringWriter = new StringWriter();
JSONWriter jsonWriter = new JSONWriter(stringWriter);
jsonWriter.object();
if (deleteAssociationRequest.getName() != null) {
jsonWriter.key("Name")
.value(deleteAssociationRequest.getName());
}
if (deleteAssociationRequest.getInstanceId() != null) {
jsonWriter.key("InstanceId").value(
deleteAssociationRequest.getInstanceId());
}
jsonWriter.endObject();
String snippet = stringWriter.toString();
byte[] content = snippet.getBytes(UTF8);
request.setContent(new StringInputStream(snippet));
request.addHeader("Content-Length",
Integer.toString(content.length));
request.addHeader("Content-Type", "application/x-amz-json-1.1");
} catch (Throwable t) {
throw new AmazonClientException(
"Unable to marshall request to JSON: " + t.getMessage(), t);
}
return request;
}
}
|
Java
|
# AUTOGENERATED FILE
FROM balenalib/zc702-zynq7-ubuntu:xenial-run
ENV NODE_VERSION 14.18.3
ENV YARN_VERSION 1.22.4
RUN buildDeps='curl libatomic1' \
&& set -x \
&& for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --keyserver keyserver.ubuntu.com --recv-keys "$key" ; \
done \
&& apt-get update && apt-get install -y $buildDeps --no-install-recommends \
&& rm -rf /var/lib/apt/lists/* \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& echo "6f19aa4d9c1b1706d44742218c8a7742d3fa62033d953156095bdde09f8375e5 node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \
&& echo "Running test-stack@node" \
&& chmod +x test-stack@node.sh \
&& bash test-stack@node.sh \
&& rm -rf test-stack@node.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu xenial \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v14.18.3, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
Java
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#ifndef KUDU_UTIL_FLAGS_H
#define KUDU_UTIL_FLAGS_H
#include <cstdint>
#include <string>
#include <unordered_map>
#include "kudu/util/status.h"
namespace google {
struct CommandLineFlagInfo;
}
namespace kudu {
// The umask of the process, set based on the --umask flag during
// HandleCommonFlags().
extern uint32_t g_parsed_umask;
// Looks for flags in argv and parses them. Rearranges argv to put
// flags first, or removes them entirely if remove_flags is true.
// If a flag is defined more than once in the command line or flag
// file, the last definition is used. Returns the index (into argv)
// of the first non-flag argument.
//
// This is a wrapper around google::ParseCommandLineFlags, but integrates
// with Kudu flag tags. For example, --helpxml will include the list of
// tags for each flag. This should be be used instead of
// google::ParseCommandLineFlags in any user-facing binary.
//
// See gflags.h for more information.
int ParseCommandLineFlags(int* argc, char*** argv, bool remove_flags);
// Handle common flags such as -version, -disable_core_dumps, etc.
// This includes the GFlags common flags such as "-help".
//
// Requires that flags have already been parsed using
// google::ParseCommandLineNonHelpFlags().
void HandleCommonFlags();
// Verifies that the flags are allowed to be set and valid.
// Should be called after logging is initialized. Otherwise
// logging will write to stderr.
void ValidateFlags();
enum class EscapeMode {
HTML,
NONE
};
// Stick the flags into a string. If redaction is enabled, the values of
// flags tagged as sensitive will be redacted. Otherwise, the values
// will be written to the string as-is. The values will be HTML escaped
// if EscapeMode is HTML.
std::string CommandlineFlagsIntoString(EscapeMode mode);
typedef std::unordered_map<std::string, google::CommandLineFlagInfo> GFlagsMap;
// Get all the flags different from their defaults. The output is a nicely
// formatted string with --flag=value pairs per line. Redact any flags that
// are tagged as sensitive, if redaction is enabled.
std::string GetNonDefaultFlags();
GFlagsMap GetFlagsMap();
enum class TriStateFlag {
DISABLED,
OPTIONAL,
REQUIRED,
};
Status ParseTriState(const char* flag_name, const std::string& flag_value,
TriStateFlag* tri_state);
std::string CheckFlagAndRedact(const google::CommandLineFlagInfo& flag, EscapeMode mode);
} // namespace kudu
#endif /* KUDU_UTIL_FLAGS_H */
|
Java
|
# Encoding: utf-8
#
# Author:: api.dklimkin@gmail.com (Danial Klimkin)
#
# Copyright:: Copyright 2012, Google Inc. All Rights Reserved.
#
# License:: 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.
#
# This class extracts data received from Savon and enriches it.
module AdsCommon
class ResultsExtractor
# Instance initializer.
#
# Args:
# - registry: a registry that defines service
#
def initialize(registry)
@registry = registry
end
# Extracts the finest results possible for the given result. Returns the
# response itself in worst case (contents unknown).
def extract_result(response, action_name)
method = @registry.get_method_signature(action_name)
action = method[:output][:name].to_sym
result = response.to_hash
result = result[action] if result.include?(action)
result = normalize_output(result, method)
return result[:rval] || result
end
# Extracts misc data from response header.
def extract_header_data(response)
header_type = get_full_type_signature(:SoapResponseHeader)
headers = response.header[:response_header].dup
process_attributes(headers, false)
headers = normalize_fields(headers, header_type[:fields])
return headers
end
# Extracts misc data from SOAP fault.
def extract_exception_data(soap_fault, exception_name)
exception_type = get_full_type_signature(exception_name)
process_attributes(soap_fault, false)
soap_fault = normalize_fields(soap_fault, exception_type[:fields])
return soap_fault
end
private
# Normalizes output starting with root output node.
def normalize_output(output_data, method_definition)
fields = method_definition[:output][:fields]
result = normalize_fields(output_data, fields)
end
# Normalizes all fields for the given data based on the fields list
# provided.
def normalize_fields(data, fields)
fields.each do |field|
field_name = field[:name]
if data.include?(field_name)
field_data = data[field_name]
field_data = normalize_output_field(field_data, field)
field_data = check_array_collapse(field_data, field)
data[field_name] = field_data unless field_data.nil?
end
end
return data
end
# Normalizes one field of a given data recursively.
#
# Args:
# - field_data: XML data to normalize
# - field_def: field type definition for the data
#
def normalize_output_field(field_data, field_def)
return case field_data
when Array
normalize_array_field(field_data, field_def)
when Hash
normalize_hash_field(field_data, field_def)
else
normalize_item(field_data, field_def)
end
end
# Normalizes every item of an Array.
def normalize_array_field(data, field_def)
return data.map {|item| normalize_output_field(item, field_def)}
end
# Normalizes every item of a Hash.
def normalize_hash_field(field, field_def)
process_attributes(field, true)
field_type = field_def[:type]
field_def = get_full_type_signature(field_type)
# First checking for xsi:type provided.
xsi_type_override = determine_xsi_type_override(field, field_def)
unless xsi_type_override.nil?
field_def = get_full_type_signature(xsi_type_override)
return (field_def.nil?) ? field :
normalize_fields(field, field_def[:fields])
end
# Now checking for choice options from wsdl.
choice_type_override = determine_choice_type_override(field, field_def)
unless choice_type_override.nil?
# For overrides we need to process sub-field and than return it
# in the original structure.
field_key = field.keys.first
field_data = field[field_key]
field_def = get_full_type_signature(choice_type_override)
if !field_def.nil? and field_data.kind_of?(Hash)
field_data = normalize_fields(field_data, field_def[:fields])
end
return {field_key => field_data}
end
# Otherwise using the best we have.
field = normalize_fields(field, field_def[:fields]) unless field_def.nil?
return field
end
# Determines an xsi:type override for for the field. Returns nil if no
# override found.
def determine_xsi_type_override(field_data, field_def)
result = nil
if field_data.kind_of?(Hash) and field_data.include?(:xsi_type)
result = field_data[:xsi_type]
end
return result
end
# Determines a choice type override for for the field. Returns nil if no
# override found.
def determine_choice_type_override(field_data, field_def)
result = nil
if field_data.kind_of?(Hash) and field_def.include?(:choices)
result = determine_choice(field_data, field_def[:choices])
end
return result
end
# Finds the choice option matching data provided.
def determine_choice(field_data, field_choices)
result = nil
key_name = field_data.keys.first
unless key_name.nil?
choice = find_named_entry(field_choices, key_name)
result = choice[:type] unless choice.nil?
end
return result
end
# Finds an item in an Array based on its ':name' field.
def find_named_entry(data_array, name)
index = data_array.index {|item| name.eql?(item[:name])}
return index.nil? ? nil : data_array[index]
end
# Converts one leaf item to a built-in type.
def normalize_item(item, field_def)
return case field_def[:type]
when 'long', 'int' then Integer(item)
when 'double', 'float' then Float(item)
when 'boolean' then item.kind_of?(String) ?
item.casecmp('true') == 0 : item
else item
end
end
# Checks if the field signature allows an array and forces array structure
# even for a signle item.
def check_array_collapse(data, field_def)
result = data
if !field_def[:min_occurs].nil? and
(field_def[:max_occurs] == :unbounded ||
(!field_def[:max_occurs].nil? and field_def[:max_occurs] > 1))
result = arrayize(result)
end
return result
end
# Makes sure object is an array.
def arrayize(object)
return [] if object.nil?
return object.is_a?(Array) ? object : [object]
end
# Returns all inherited fields of superclasses for given type.
def implode_parent(data_type)
result = []
if data_type[:base]
parent_type = @registry.get_type_signature(data_type[:base])
result += implode_parent(parent_type) unless parent_type.nil?
end
data_type[:fields].each do |field|
# If the parent type includes a field with the same name, overwrite it.
result.reject! {|parent_field| parent_field[:name].eql?(field[:name])}
result << field
end
return result
end
# Returns type signature with all inherited fields.
def get_full_type_signature(type_name)
result = (type_name.nil?) ? nil : @registry.get_type_signature(type_name)
result[:fields] = implode_parent(result) if result and result[:base]
return result
end
# Handles attributes received from Savon.
def process_attributes(data, keep_xsi_type = false)
if keep_xsi_type
xsi_type = data.delete(:"@xsi:type")
data[:xsi_type] = xsi_type if xsi_type
end
data.reject! {|key, value| key.to_s.start_with?('@')}
end
end
end
|
Java
|
# -----------------------------------------------------------------------------
# Copyright * 2014, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration. All
# rights reserved.
#
# The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache
# License, Version 2.0 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
# -----------------------------------------------------------------------------
import ee
import math
from cmt.mapclient_qt import addToMap
from cmt.util.miscUtilities import safe_get_info
import modis_utilities
'''
Contains implementations of several simple MODIS-based flood detection algorithms.
'''
#==============================================================
def dem_threshold(domain, b):
'''Just use a height threshold on the DEM!'''
heightLevel = float(domain.algorithm_params['dem_threshold'])
dem = domain.get_dem().image
return dem.lt(heightLevel).select(['elevation'], ['b1'])
#==============================================================
def evi(domain, b):
'''Simple EVI based classifier'''
#no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1'])
criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1'])
criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1'])
#return no_clouds.And(criteria1.Or(criteria2))
return criteria1.Or(criteria2)
def xiao(domain, b):
'''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using
multi-temporal MODIS images, Remote Sensing of Environment, 2006.
This method implements a very simple decision tree from several standard MODIS data products.
The default constants were tuned for (wet) rice paddy detection.
'''
return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']);
#==============================================================
def get_diff(b):
'''Just the internals of the difference method'''
return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1'])
def diff_learned(domain, b):
'''modis_diff but with the threshold calculation included (training image required)'''
if domain.unflooded_domain == None:
print('No unflooded training domain provided.')
return None
unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain)
water_mask = modis_utilities.get_permanent_water_mask()
threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds)
return modis_diff(domain, b, threshold)
def modis_diff(domain, b, threshold=None):
'''Compute (b2-b1) < threshold, a simple water detection index.
This method may be all that is needed in cases where the threshold can be hand tuned.
'''
if threshold == None: # If no threshold value passed in, load it based on the data set.
threshold = float(domain.algorithm_params['modis_diff_threshold'])
return get_diff(b).lte(threshold)
#==============================================================
def get_dartmouth(b):
A = 500
B = 2500
return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1'])
def dart_learned(domain, b):
'''The dartmouth method but with threshold calculation included (training image required)'''
if domain.unflooded_domain == None:
print('No unflooded training domain provided.')
return None
unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain)
water_mask = modis_utilities.get_permanent_water_mask()
threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds)
return dartmouth(domain, b, threshold)
def dartmouth(domain, b, threshold=None):
'''A flood detection method from the Dartmouth Flood Observatory.
This method is a refinement of the simple b2-b1 detection method.
'''
if threshold == None:
threshold = float(domain.algorithm_params['dartmouth_threshold'])
return get_dartmouth(b).lte(threshold)
#==============================================================
def get_mod_ndwi(b):
return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1'])
def mod_ndwi_learned(domain, b):
if domain.unflooded_domain == None:
print('No unflooded training domain provided.')
return None
unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain)
water_mask = modis_utilities.get_permanent_water_mask()
threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds)
return mod_ndwi(domain, b, threshold)
def mod_ndwi(domain, b, threshold=None):
if threshold == None:
threshold = float(domain.algorithm_params['mod_ndwi_threshold'])
return get_mod_ndwi(b).lte(threshold)
#==============================================================
def get_fai(b):
'''Just the internals of the FAI method'''
return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1'])
def fai_learned(domain, b):
if domain.unflooded_domain == None:
print('No unflooded training domain provided.')
return None
unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain)
water_mask = modis_utilities.get_permanent_water_mask()
threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds)
return fai(domain, b, threshold)
def fai(domain, b, threshold=None):
''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan,
Assessment of inundation changes of Poyang Lake using MODIS observations
between 2000 and 2010. Remote Sensing of Environment, 2012.
'''
if threshold == None:
threshold = float(domain.algorithm_params['fai_threshold'])
return get_fai(b).lte(threshold)
|
Java
|
# Urocystis poae (Liro) Padwick & A. Khan, 1944 SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Mycol. Pap. 10: 2 (1944)
#### Original name
Tuburcinia poae Liro, 1922
### Remarks
null
|
Java
|
package com.qmx.wxmp.common.web;
/**
* 带UTF-8 charset 定义的MediaType.
*
* Jax-RS和Spring的MediaType没有UTF-8的版本,
* Google的MediaType必须再调用toString()函数而不是常量,不能用于Restful方法的annotation。
*
* @author free lance
*/
public class MediaTypes {
public static final String APPLICATION_XML = "application/xml";
public static final String APPLICATION_XML_UTF_8 = "application/xml; charset=UTF-8";
public static final String JSON = "application/json";
public static final String JSON_UTF_8 = "application/json; charset=UTF-8";
public static final String JAVASCRIPT = "application/javascript";
public static final String JAVASCRIPT_UTF_8 = "application/javascript; charset=UTF-8";
public static final String APPLICATION_XHTML_XML = "application/xhtml+xml";
public static final String APPLICATION_XHTML_XML_UTF_8 = "application/xhtml+xml; charset=UTF-8";
public static final String TEXT_PLAIN = "text/plain";
public static final String TEXT_PLAIN_UTF_8 = "text/plain; charset=UTF-8";
public static final String TEXT_XML = "text/xml";
public static final String TEXT_XML_UTF_8 = "text/xml; charset=UTF-8";
public static final String TEXT_HTML = "text/html";
public static final String TEXT_HTML_UTF_8 = "text/html; charset=UTF-8";
}
|
Java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.fortress.core.samples;
import org.apache.directory.fortress.core.DelAdminMgr;
import org.apache.directory.fortress.core.DelAdminMgrFactory;
import org.apache.directory.fortress.core.SecurityException;
import org.apache.directory.fortress.core.model.OrgUnit;
import org.apache.directory.fortress.core.impl.TestUtils;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* CreateUserOrgHierarchySample JUnit Test. This test program will show how to build a simple User OrgUnit hierarchy which are
* used to enable administrators to group Users by organizational structure. This system supports multiple
* inheritance between OrgUnits and there are no limits on how deep a hierarchy can be. The OrgUnits require name and type. Optionally can
* include a description. The User OrgUnit must be associated with Users and are used to provide Administratrive RBAC control
* over who may perform User Role assigns and deassigns in directory.
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class CreateUserOrgHierarchySample extends TestCase
{
private static final String CLS_NM = CreateUserOrgHierarchySample.class.getName();
private static final Logger LOG = LoggerFactory.getLogger( CLS_NM );
// This constant will be added to index for creation of multiple nodes in directory.
public static final String TEST_HIER_USERORG_PREFIX = "sampleHierUserOrg";
public static final String TEST_HIER_BASE_USERORG = "sampleHierUserOrg1";
public static final int TEST_NUMBER = 6;
public static final String TEST_HIER_DESC_USERORG_PREFIX = "sampleHierUserOrgD";
public static final String TEST_HIER_ASC_USERORG_PREFIX = "sampleHierUserOrgA";
/**
* Simple constructor kicks off JUnit test suite.
* @param name
*/
public CreateUserOrgHierarchySample(String name)
{
super(name);
}
/**
* Run the User OrgUnit test cases.
*
* @return Test
*/
public static Test suite()
{
TestSuite suite = new TestSuite();
if(!AllSamplesJUnitTest.isFirstRun())
{
suite.addTest(new CreateUserOrgHierarchySample("testDeleteHierUserOrgs"));
suite.addTest(new CreateUserOrgHierarchySample("testDeleteDescendantUserOrgs"));
suite.addTest(new CreateUserOrgHierarchySample("testDeleteAscendantUserOrgs"));
}
suite.addTest(new CreateUserOrgHierarchySample("testCreateHierUserOrgs"));
suite.addTest(new CreateUserOrgHierarchySample("testCreateDescendantUserOrgs"));
suite.addTest(new CreateUserOrgHierarchySample("testCreateAscendantUserOrgs"));
/*
suite.addTest(new CreateUserOrgHierarchySample("testDeleteHierUserOrgs"));
suite.addTest(new CreateUserOrgHierarchySample("testCreateHierUserOrgs"));
suite.addTest(new CreateUserOrgHierarchySample("testDeleteDescendantUserOrgs"));
suite.addTest(new CreateUserOrgHierarchySample("testCreateDescendantUserOrgs"));
suite.addTest(new CreateUserOrgHierarchySample("testDeleteAscendantUserOrgs"));
suite.addTest(new CreateUserOrgHierarchySample("testCreateAscendantUserOrgs"));
*/
return suite;
}
/**
* Remove the simple hierarchical OrgUnits from the directory. Before removal call the API to move the relationship
* between the parent and child OrgUnits. Once the relationship is removed the parent OrgUnit can be removed.
* User OrgUnit removal is not allowed (SecurityException will be thrown) if ou is assigned to Users in ldap.
* <p>
* <img src="./doc-files/HierUserOrgSimple.png" alt="">
*/
public static void testDeleteHierUserOrgs()
{
String szLocation = ".testDeleteHierUserOrgs";
if(AllSamplesJUnitTest.isFirstRun())
{
return;
}
try
{
// Instantiate the DelAdminMgr implementation which is used to provision ARBAC policies.
DelAdminMgr delAdminMgr = DelAdminMgrFactory.createInstance(TestUtils.getContext());
for (int i = 1; i < TEST_NUMBER; i++)
{
// The key that must be set to locate any OrgUnit is simply the name and type.
OrgUnit parentOrgUnit = new OrgUnit(TEST_HIER_USERORG_PREFIX + i, OrgUnit.Type.USER);
OrgUnit childOrgUnit = new OrgUnit(TEST_HIER_USERORG_PREFIX + (i + 1), OrgUnit.Type.USER);
// Remove the relationship from the parent and child OrgUnit:
delAdminMgr.deleteInheritance(parentOrgUnit, childOrgUnit);
// Remove the parent OrgUnit from directory:
delAdminMgr.delete(parentOrgUnit);
}
// Remove the child OrgUnit from directory:
delAdminMgr.delete(new OrgUnit(TEST_HIER_USERORG_PREFIX + TEST_NUMBER, OrgUnit.Type.USER));
LOG.info(szLocation + " success");
}
catch (SecurityException ex)
{
LOG.error(szLocation + " caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex);
fail(ex.getMessage());
}
}
/**
* Add a simple OrgUnit hierarchy to ldap. The OrgUnits will named to include a name,'sampleHierUserOrg', appended with the
* sequence of 1 - 6. 'sampleHierUserOrg1' is the root or highest level OrgUnit in the structure while sampleHierUserOrg6 is the lowest
* most child. Fortress OrgUnits may have multiple parents which is demonstrated in testCreateAscendantUserOrgs sample.
* <p>
* <img src="./doc-files/HierUserOrgSimple.png" alt="">
*/
public static void testCreateHierUserOrgs()
{
String szLocation = ".testCreateHierUserOrgs";
try
{
// Instantiate the DelAdminMgr implementation which is used to provision ARBAC policies.
DelAdminMgr delAdminMgr = DelAdminMgrFactory.createInstance(TestUtils.getContext());
// Instantiate the root OrgUnit entity. OrgUnit requires name and type before addition.
OrgUnit baseOrgUnit = new OrgUnit(TEST_HIER_BASE_USERORG, OrgUnit.Type.USER);
// Add the root OrgUnit entity to the directory.
delAdminMgr.add(baseOrgUnit);
// Create User OrgUnits, 'sampleHierUserOrg2' - 'sampleHierUserOrg6'.
for (int i = 2; i < TEST_NUMBER + 1; i++)
{
// Instantiate the OrgUnit entity.
OrgUnit childOrgUnit = new OrgUnit(TEST_HIER_USERORG_PREFIX + i, OrgUnit.Type.USER);
// Add the OrgUnit entity to the directory.
delAdminMgr.add(childOrgUnit);
// Instantiate the parent OrgUnit. The key is the name and type.
OrgUnit parentOrgUnit = new OrgUnit(TEST_HIER_USERORG_PREFIX + (i - 1), OrgUnit.Type.USER);
// Add a relationship between the parent and child OrgUnits:
delAdminMgr.addInheritance(parentOrgUnit, childOrgUnit);
}
LOG.info(szLocation + " success");
}
catch (SecurityException ex)
{
LOG.error(szLocation + " caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex);
fail(ex.getMessage());
}
}
/**
* Demonstrate teardown of a parent to child relationship of one-to-many. Each child must first remove the inheritance
* relationship with parent before being removed from ldap. The parent OrgUnit will be removed from ldap last.
* User OrgUnit removal is not allowed (SecurityException will be thrown) if ou is assigned to Users in ldap.
* <p>
* <img src="./doc-files/HierUserOrgDescendants.png" alt="">
*/
public static void testDeleteDescendantUserOrgs()
{
String szLocation = ".testDeleteDescendantUserOrgs";
if(AllSamplesJUnitTest.isFirstRun())
{
return;
}
try
{
// Instantiate the DelAdminMgr implementation which is used to provision ARBAC policies.
DelAdminMgr delAdminMgr = DelAdminMgrFactory.createInstance(TestUtils.getContext());
// This parent has many children. They must be deleted before parent itself can.
OrgUnit parentOrgUnit = new OrgUnit(TEST_HIER_DESC_USERORG_PREFIX + 1, OrgUnit.Type.USER);
// There are N User OrgUnits to process:
for (int i = 2; i < TEST_NUMBER + 1; i++)
{
// Instantiate the child OrgUnit entity. The key is the name and type.
OrgUnit childOrgUnit = new OrgUnit(TEST_HIER_DESC_USERORG_PREFIX + i, OrgUnit.Type.USER);
// Remove the relationship from the parent and child OrgUnit:
delAdminMgr.deleteInheritance(parentOrgUnit, childOrgUnit);
// Remove the child OrgUnit from directory:
delAdminMgr.delete(childOrgUnit);
}
// Remove the parent OrgUnit from directory:
delAdminMgr.delete(parentOrgUnit);
LOG.info(szLocation + " success");
}
catch (SecurityException ex)
{
LOG.error(szLocation + " caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex);
fail(ex.getMessage());
}
}
/**
* Demonstrate a parent to child OrgUnit structure of one-to-many. The parent OrgUnit must be created before
* the call to addDescendant which will Add a new OrgUnit node and set a OrgUnit relationship with parent node.
* <p>
* <img src="./doc-files/HierUserOrgDescendants.png" alt="">
*/
public static void testCreateDescendantUserOrgs()
{
String szLocation = ".testCreateDescendantUserOrgs";
try
{
// Instantiate the DelAdminMgr implementation which is used to provision ARBAC policies.
DelAdminMgr delAdminMgr = DelAdminMgrFactory.createInstance(TestUtils.getContext());
// Instantiate the parent User OrgUnit entity. This needs a name and type before it can be added to ldap.
OrgUnit parentOrgUnit = new OrgUnit(TEST_HIER_DESC_USERORG_PREFIX + 1, OrgUnit.Type.USER);
// This parent will have many children:
delAdminMgr.add(parentOrgUnit);
// Create User OrgUnits, 'sampleHierUserOrgD2' - 'sampleHierUserOrgD6'.
for (int i = 1; i < TEST_NUMBER; i++)
{
// Now add relationship to the directory between parent and child User OrgUnits.
OrgUnit childOrgUnit = new OrgUnit(TEST_HIER_DESC_USERORG_PREFIX + (i + 1), OrgUnit.Type.USER);
// Now add child OrgUnit entity to directory and add relationship with existing parent OrgUnit.
delAdminMgr.addDescendant(parentOrgUnit, childOrgUnit);
}
LOG.info(szLocation + " success");
}
catch (SecurityException ex)
{
LOG.error(szLocation + " caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex);
fail(ex.getMessage());
}
}
/**
* This example demonstrates tear down of a child to parent represented as one-to-many. The parents must all
* be removed from the child before the child can be removed.
* User OrgUnit removal is not allowed (SecurityException will be thrown) if ou is assigned to Users in ldap.
* <p>
* <img src="./doc-files/HierUserOrgAscendants.png" alt="">
*/
public static void testDeleteAscendantUserOrgs()
{
String szLocation = ".testDeleteAscendantUserOrgs";
if(AllSamplesJUnitTest.isFirstRun())
{
return;
}
try
{
// Instantiate the DelAdminMgr implementation which is used to provision ARBAC policies.
DelAdminMgr delAdminMgr = DelAdminMgrFactory.createInstance(TestUtils.getContext());
// This child OrgUnit has many parents:
OrgUnit childOrgUnit = new OrgUnit(TEST_HIER_ASC_USERORG_PREFIX + 1, OrgUnit.Type.USER);
for (int i = 2; i < TEST_NUMBER + 1; i++)
{
// Instantiate the parent. This needs a name and type before it can be used in operation.
OrgUnit parentOrgUnit = new OrgUnit(TEST_HIER_ASC_USERORG_PREFIX + i, OrgUnit.Type.USER);
// Remove the relationship between parent and child OrgUnits:
delAdminMgr.deleteInheritance(parentOrgUnit, childOrgUnit);
// Remove the parent OrgUnit from directory:
delAdminMgr.delete(parentOrgUnit);
}
// Remove the child OrgUnit from directory:
delAdminMgr.delete(childOrgUnit);
LOG.info(szLocation + " success");
}
catch (SecurityException ex)
{
LOG.error(szLocation + " caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex);
fail(ex.getMessage());
}
}
/**
* Demonstrate a child to parent OrgUnit structure of one-to-many. To use this API, the child OrgUnit must be created before
* the call to addAscendant which will Add a new OrgUnit node and set a OrgUnit relationship with child node.
* <p>
* <img src="./doc-files/HierUserOrgAscendants.png" alt="">
*/
public static void testCreateAscendantUserOrgs()
{
String szLocation = ".testCreateAscendantUserOrgs";
try
{
// Instantiate the DelAdminMgr implementation which is used to provision ARBAC policies.
DelAdminMgr delAdminMgr = DelAdminMgrFactory.createInstance(TestUtils.getContext());
// Instantiate the child OrgUnit. This needs a name and type.
OrgUnit childOrgUnit = new OrgUnit(TEST_HIER_ASC_USERORG_PREFIX + 1, OrgUnit.Type.USER);
// This child will have many parents:
delAdminMgr.add(childOrgUnit);
// Create OrgUnits, 'sampleHierUserOrgA2' - 'sampleHierUserOrgA6'.
for (int i = 1; i < TEST_NUMBER; i++)
{
// Instantiate the parent OrgUnit. This needs a name and type before it can be added to ldap.
OrgUnit parentOrgUnit = new OrgUnit(TEST_HIER_ASC_USERORG_PREFIX + (i + 1), OrgUnit.Type.USER);
// Now add parent OrgUnit entity to directory and add relationship with existing child OrgUnit.
delAdminMgr.addAscendant(childOrgUnit, parentOrgUnit);
}
}
catch (SecurityException ex)
{
LOG.error(szLocation + " caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex);
fail(ex.getMessage());
}
}
}
|
Java
|
//
// Copyright (c) 2014 Limit Point Systems, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package tools.viewer.user;
import tools.viewer.common.*;
import tools.viewer.render.*;
import tools.common.gui.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.text.*;
import vtk.*;
/**
* Implementation of <code>G3DFieldActorPropertiesPanel</code> for editing the
* values of a <code>HedgeHogFieldActorDescriptor</code>.
*/
public class HedgeHogFieldActorPropertiesPanel
extends G3DFieldActorPropertiesPanel
{
// CONSTANTS FACET
protected static final String[] VECTOR_MODES =
{ ViewerConstants.VECTOR_MAGNITUDE,
ViewerConstants.VECTOR_NORMAL };
// GUI FACET
protected JPanel hedgeHogPanel;
protected JSpinner scaleFactorSpinner;
protected JComboBox vectorModeComboBox;
// CONSTRUCTORS
/**
* Constructor
*/
public HedgeHogFieldActorPropertiesPanel(G3DViewer xviewer,
FieldActorDescriptor[] xdescriptors)
{
super(xviewer, xdescriptors);
hedgeHogPanel = createHedgeHogPanel();
tabbedPane.addTab("Hedge Hog", hedgeHogPanel);
initValues();
}
// CREATE FACET
/**
* Create hedge hog panel
*/
protected JPanel createHedgeHogPanel()
{
JPanel result = new JPanel();
result.setLayout(new BoxLayout(result, BoxLayout.PAGE_AXIS));
result.setBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(6, 12, 6, 12),
BorderFactory.createTitledBorder("Hedge Hog:")));
//=====
result.add(Box.createVerticalGlue());
JPanel panel = new JPanel();
JLabel scaleFactorLabel = new JLabel("Scale Factor: ", JLabel.RIGHT);
scaleFactorLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
SpinnerModel scaleFactorModel = new SpinnerNumberModel(1.0, 0.0,
10000000.0, 0.01);
scaleFactorSpinner = new JSpinner(scaleFactorModel);
panel.add(scaleFactorLabel);
panel.add(scaleFactorSpinner);
result.add(panel);
result.add(Box.createVerticalGlue());
//=====
panel = new JPanel();
JLabel vectorModeLabel = new JLabel("Vector Mode:", JLabel.RIGHT);
vectorModeLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
vectorModeComboBox = new JComboBox(VECTOR_MODES);
panel.add(vectorModeLabel);
panel.add(vectorModeComboBox);
result.add(panel);
result.add(Box.createVerticalGlue());
//=====
return result;
}
// INITIALIZE FACET
/**
*
*/
public void initValues()
{
super.initValues();
// Use the first actor in the list to initialize the
// user interface.
HedgeHogFieldActorDescriptor actor =
(HedgeHogFieldActorDescriptor) descriptors[0];
initHedgeHogPanel(actor);
}
/**
*
*/
protected void initHedgeHogPanel(HedgeHogFieldActorDescriptor actor)
{
scaleFactorSpinner.setValue(actor.scaleFactor);
vectorModeComboBox.setSelectedItem(actor.vectorMode);
}
// APPLY FACET
/**
*
*/
public void doApply()
{
// Set the wait state to true, it is restored by
// UpdatePropertiesPanelEvent.
setWaitState(true);
synchronized (viewer.getScript())
{
synchronized (viewer.getScene())
{
// Apply the changed to the descriptors
HedgeHogFieldActorDescriptor actor;
for(int i=0; i<descriptors.length; i++)
{
actor = (HedgeHogFieldActorDescriptor) descriptors[i];
applyHedgeHog(actor);
}
}
}
super.doApply(false);
}
/**
*
*/
public void applyHedgeHog(HedgeHogFieldActorDescriptor actor)
{
actor.scaleFactor = ((SpinnerNumberModel)scaleFactorSpinner.getModel()).getNumber().doubleValue();
actor.vectorMode = (String) vectorModeComboBox.getSelectedItem();
}
}
|
Java
|
<p>
Even - {{ number }}
</p>
|
Java
|
<link rel="import" href="../../bower_components/polymer/polymer-element.html">
<dom-module id="balance-text-field">
<script>
class BalanceTextField extends Vaadin.TextFieldElement {
static get is() {
return 'balance-text-field';
}
static get properties() {
return {
max: Number,
min: Number,
message: {
type: String,
computed: '_computedMessage(errorMessage)',
}
}
}
_computedMessage(errorMessage) {
return errorMessage;
}
checkValidity() {
if (super.checkValidity()) {
if (this.max && Number(this.value) > this.max) {
this.errorMessage = ' You have insufficient Balance';
return false;
}
if(this.min && Number(this.value) < this.min){
this.errorMessage = ' must be bigger than ' + this.min;
return false;
}
return true;
} else {
this.errorMessage = this.message;
return false;
}
}
}
window.customElements.define(BalanceTextField.is, BalanceTextField);
</script>
</dom-module>
|
Java
|
/*!
* Copyright 2012 Sakai Foundation (SF) Licensed under the
* Educational Community 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.osedu.org/licenses/ECL-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.
*/
require(['jquery', 'oae.core'], function($, oae) {
// Get the group id from the URL. The expected URL is /group/<groupId>
var groupId = document.location.pathname.split('/')[2];
if (!groupId) {
oae.api.util.redirect().login();
}
// Variable used to cache the requested user's profile
var groupProfile = null;
// Variable used to cache the group's base URL
var baseUrl = '/group/' + groupId;
/**
* Get the group's basic profile and set up the screen. If the groups
* can't be found or is private to the current user, the appropriate
* error page will be shown
*/
var getGroupProfile = function() {
oae.api.group.getGroup(groupId, function(err, profile) {
if (err && err.code === 404) {
oae.api.util.redirect().notfound();
} else if (err && err.code === 401) {
oae.api.util.redirect().accessdenied();
}
groupProfile = profile;
setUpClip();
setUpNavigation();
// Set the browser title
oae.api.util.setBrowserTitle(groupProfile.displayName);
});
};
$(document).on('oae.context.get', function() {
$(document).trigger('oae.context.send', groupProfile);
});
$(document).trigger('oae.context.send', groupProfile);
/**
* Render the group's clip, containing the profile picture, display name as well as the
* group's admin options
*/
var setUpClip = function() {
oae.api.util.template().render($('#group-clip-template'), {'group': groupProfile}, $('#group-clip-container'));
// Only show the create and upload clips to managers
if (groupProfile.isManager) {
$('#group-actions').show();
}
};
/**
* Set up the left hand navigation with the me space page structure
*/
var setUpNavigation = function() {
// Structure that will be used to construct the left hand navigation
var lhNavigation = [
{
'id': 'activity',
'title': oae.api.i18n.translate('__MSG__RECENT_ACTIVITY__'),
'icon': 'icon-dashboard',
'layout': [
{
'width': 'span8',
'widgets': [
{
'id': 'activity',
'settings': {
'principalId': groupProfile.id,
'canManage': groupProfile.isManager
}
}
]
}
]
},
{
'id': 'library',
'title': oae.api.i18n.translate('__MSG__LIBRARY__'),
'icon': 'icon-briefcase',
'layout': [
{
'width': 'span12',
'widgets': [
{
'id': 'library',
'settings': {
'principalId': groupProfile.id,
'canManage': groupProfile.isManager
}
}
]
}
]
},
{
'id': 'members',
'title': oae.api.i18n.translate('__MSG__MEMBERS__'),
'icon': 'icon-user',
'layout': [
{
'width': 'span12',
'widgets': [
{
'id': 'participants',
'settings': {
'principalId': groupProfile.id,
'canManage': groupProfile.isManager
}
}
]
}
]
}
];
$(window).trigger('oae.trigger.lhnavigation', [lhNavigation, baseUrl]);
$(window).on('oae.ready.lhnavigation', function() {
$(window).trigger('oae.trigger.lhnavigation', [lhNavigation, baseUrl]);
});
};
getGroupProfile();
});
|
Java
|
package cn.oeaom.CoolWeather;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.media.Image;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import cn.oeaom.CoolWeather.GSON.Weather;
import cn.oeaom.CoolWeather.Util.Utility;
import okhttp3.Call;
import okhttp3.Callback;
import cn.oeaom.CoolWeather.Util.HttpUtil;
import okhttp3.Response;
public class WeatherActivity extends AppCompatActivity {
private static final String TAG = "WeatherActivity";
private static final String API_KEY = "bc0418b57b2d4918819d3974ac1285d9";
//鉴权码
//天气信息面板所要展现的东西
public DrawerLayout drawerLayout; //左侧滑动和点击小房子展现的界面
//public TextView tvTitle; //标题 *弃用
private TextView weatherTime; //天气信息的时间
private TextView weatherDegree; //天气信息的温度值
private TextView measure2; //天气信息的温度单位
private TextView weatherPlace; //天气信息的地点
private TextView weatherType; //天气信息的类型
private String mWeatherId; //城市的编号
private ImageView weatherStat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather);
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
// FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
// fab.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
// }
// });
Typeface fontFace = Typeface.createFromAsset(getAssets(), "fonts/AndroidClock.ttf");
// 字体文件必须是true type font的格式(ttf);
// 当使用外部字体却又发现字体没有变化的时候(以 Droid Sans代替),通常是因为
// 这个字体android没有支持,而非你的程序发生了错误
weatherTime = (TextView)findViewById(R.id.weather_info_time);
weatherTime.setTypeface(fontFace);
//
weatherDegree = (TextView)findViewById(R.id.degree_value);
weatherDegree.setTypeface(fontFace);
TextView measure = (TextView)findViewById(R.id.degree_measure);
// measure.setTypeface(fontFace);
measure2 = (TextView)findViewById(R.id.degree_measure2);
//measure2.setTypeface(fontFace);
weatherPlace = (TextView)findViewById(R.id.weather_info_place);
//weatherPlace.setTypeface(fontFace);
weatherType = (TextView)findViewById(R.id.weather_info_text);
//weatherType.setTypeface(fontFace);
weatherStat = (ImageView)findViewById(R.id.weatherIcon);
//
// TextView weatherInfo = (TextView)findViewById(R.id.weather_info_text);
//
// weatherInfo.setTypeface(fontFace);
//
//text.setTextSize(50);
Intent intent=getIntent();
//获取这个Intent对象的Extra中对应键的值
String weatherId=intent.getStringExtra("weather_id");
String CountryName = intent.getStringExtra("CountryName");
// tvTitle = (TextView)findViewById(R.id.title_text_weather);
// //tvTitle.setText(weatherId);
// tvTitle.setText(CountryName);
// // tvTitle.setTextSize(60);
// tvTitle.setTypeface(fontFace);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
Button btnBack = (Button)findViewById(R.id.btn_home);
btnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Intent intent = new Intent(WeatherActivity.this,MainActivity.class);
//startActivity(intent);
// WeatherActivity.this.finish();
drawerLayout.openDrawer(GravityCompat.START);
Log.v(TAG,"Clicked nav btn");
}
});
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String weatherString = prefs.getString("weather", null);
if (weatherString != null) {
// 有缓存时直接解析天气数据
Weather weather = Utility.handleWeatherResponse(weatherString);
mWeatherId = weather.basic.weatherId;
showWeatherInfo(weather);
} else {
// 无缓存时去服务器查询天气
mWeatherId = getIntent().getStringExtra("weather_id");
// weatherLayout.setVisibility(View.INVISIBLE);
requestWeather(mWeatherId);
}
// swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
// @Override
// public void onRefresh() {
// requestWeather(mWeatherId);
// }
// });
}
// public void requestWeather(final String weatherId){
// tvTitle.setText(weatherId);
// }
public void requestWeather(final String weatherId) {
String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key="+API_KEY;
HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseText = response.body().string();
Log.v(TAG,"=======================================================================");
Log.v(TAG,responseText);
Log.v(TAG,"=======================================================================");
final Weather weather = Utility.handleWeatherResponse(responseText);
runOnUiThread(new Runnable() {
@Override
public void run() {
if (weather != null && "ok".equals(weather.status)) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
editor.putString("weather", responseText);
editor.apply();
//mWeatherId = weather.basic.weatherId;
showWeatherInfo(weather);
} else {
Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
}
//swipeRefresh.setRefreshing(false);
}
});
}
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
//swipeRefresh.setRefreshing(false);
}
});
}
});
//loadBingPic();
}
private int findWeatherIconByName(String weatherName)
{
switch(weatherName)
{
case "晴":return R.drawable.a044;
case "多云":return R.drawable.a045;
case "少云":return R.drawable.a046;
case "晴间多云":return R.drawable.a047;
case "阴":return R.drawable.a048;
case "有风":return R.drawable.a049;
case "平静":return R.drawable.a050;
case "微风":return R.drawable.a000;
case "和风":return R.drawable.a001;
case "清风":return R.drawable.a002;
case "强风":return R.drawable.a003;
case "劲风":return R.drawable.a003;
case "大风":return R.drawable.a004;
case "烈风":return R.drawable.a005;
case "风暴":return R.drawable.a006;
case "狂爆风":return R.drawable.a007;
case "龙卷风":return R.drawable.a008;
case "热带风暴":return R.drawable.a009;
case "阵雨":return R.drawable.a012;
case "强阵雨":return R.drawable.a013;
case "雷阵雨":return R.drawable.a014;
case "强雷阵雨":return R.drawable.a015;
case "雷阵雨伴有冰雹":return R.drawable.a016;
case "小雨":return R.drawable.a017;
case "中雨":return R.drawable.a018;
case "大雨":return R.drawable.a019;
case "极端降雨":return R.drawable.a020;
case "毛毛雨":return R.drawable.a021;
case "细雨":return R.drawable.a021;
case "暴雨":return R.drawable.a022;
case "大暴雨":return R.drawable.a023;
case "特大暴雨":return R.drawable.a024;
case "冻雨":return R.drawable.a025;
case "小雪":return R.drawable.a026;
case "中雪":return R.drawable.a027;
case "大雪":return R.drawable.a028;
case "暴雪":return R.drawable.a029;
case "雨夹雪":return R.drawable.a030;
case "雨雪天气":return R.drawable.a031;
case "阵雨夹雪":return R.drawable.a032;
case "阵雪":return R.drawable.a033;
case "薄雾":return R.drawable.a034;
case "雾":return R.drawable.a035;
case "霾":return R.drawable.a036;
case "扬沙":return R.drawable.a037;
case "浮尘":return R.drawable.a038;
case "沙尘暴":return R.drawable.a039;
case "热":return R.drawable.a041;
case "冷":return R.drawable.a042;
case "强沙尘暴":return R.drawable.a040;
case "未知":return R.drawable.a043;
default:{
break;
}
}
return -1;
}
private void showWeatherInfo(Weather weather) {
String cityName = weather.basic.cityName;
String updateTime = weather.basic.update.updateTime.split(" ")[1];
String degree = weather.now.temperature;
String weatherInfo = weather.now.more.info;
weatherPlace.setText(cityName);
weatherTime.setText(updateTime);
weatherDegree.setText(degree);
weatherType.setText(weatherInfo);
weatherStat.setImageResource(findWeatherIconByName(weatherInfo));
// forecastLayout.removeAllViews();
// for (Forecast forecast : weather.forecastList) {
// View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false);
// TextView dateText = (TextView) view.findViewById(R.id.date_text);
// TextView infoText = (TextView) view.findViewById(R.id.info_text);
// TextView maxText = (TextView) view.findViewById(R.id.max_text);
// TextView minText = (TextView) view.findViewById(R.id.min_text);
// dateText.setText(forecast.date);
// infoText.setText(forecast.more.info);
// maxText.setText(forecast.temperature.max);
// minText.setText(forecast.temperature.min);
// forecastLayout.addView(view);
// }
// if (weather.aqi != null) {
// aqiText.setText(weather.aqi.city.aqi);
// pm25Text.setText(weather.aqi.city.pm25);
// }
// String comfort = "舒适度:" + weather.suggestion.comfort.info;
// String carWash = "洗车指数:" + weather.suggestion.carWash.info;
// String sport = "运行建议:" + weather.suggestion.sport.info;
// comfortText.setText(comfort);
// carWashText.setText(carWash);
// sportText.setText(sport);
// weatherLayout.setVisibility(View.VISIBLE);
// Intent intent = new Intent(this, AutoUpdateService.class);
// startService(intent);
}
}
|
Java
|
---
layout: "fluid/docs_base"
version: "3.9.2"
versionHref: "/docs/v3/3.9.2"
path: ""
category: api
id: "toastcontroller"
title: "ToastController"
header_sub_title: "Ionic API Documentation"
doc: "ToastController"
docType: "class"
show_preview_device: true
preview_device_url: "/docs/v3/demos/src/toast/www/"
angular_controller: APIDemoCtrl
---
<h1 class="api-title">
<a class="anchor" name="toast-controller" href="#toast-controller"></a>
ToastController
</h1>
<a class="improve-v2-docs" href="http://github.com/ionic-team/ionic/edit/v3/src/components/toast/toast-controller.ts#L5">
Improve this doc
</a>
<p>A Toast is a subtle notification commonly used in modern applications.
It can be used to provide feedback about an operation or to
display a system message. The toast appears on top of the app's content,
and can be dismissed by the app to resume user interaction with
the app.</p>
<h3><a class="anchor" name="creating" href="#creating">Creating</a></h3>
<p>All of the toast options should be passed in the first argument of
the create method: <code>create(opts)</code>. The message to display should be
passed in the <code>message</code> property. The <code>showCloseButton</code> option can be set to
true in order to display a close button on the toast. See the <a href="#create">create</a>
method below for all available options.</p>
<h3><a class="anchor" name="positioning" href="#positioning">Positioning</a></h3>
<p>Toasts can be positioned at the top, bottom or middle of the
view port. The position can be passed to the <code>Toast.create(opts)</code> method.
The position option is a string, and the values accepted are <code>top</code>, <code>bottom</code> and <code>middle</code>.
If the position is not specified, the toast will be displayed at the bottom of the view port.</p>
<h3><a class="anchor" name="dismissing" href="#dismissing">Dismissing</a></h3>
<p>The toast can be dismissed automatically after a specific amount of time
by passing the number of milliseconds to display it in the <code>duration</code> of
the toast options. If <code>showCloseButton</code> is set to true, then the close button
will dismiss the toast. To dismiss the toast after creation, call the <code>dismiss()</code>
method on the Toast instance. The <code>onDidDismiss</code> function can be called to perform an action after the toast
is dismissed.</p>
<!-- @usage tag -->
<h2><a class="anchor" name="usage" href="#usage">Usage</a></h2>
<pre><code class="lang-ts">import { ToastController } from 'ionic-angular';
constructor(private toastCtrl: ToastController) {
}
presentToast() {
let toast = this.toastCtrl.create({
message: 'User was added successfully',
duration: 3000,
position: 'top'
});
toast.onDidDismiss(() => {
console.log('Dismissed toast');
});
toast.present();
}
</code></pre>
<!-- @property tags -->
<!-- instance methods on the class -->
<h2><a class="anchor" name="instance-members" href="#instance-members">Instance Members</a></h2>
<div id="config"></div>
<h3>
<a class="anchor" name="config" href="#config">
<code>config</code>
</a>
</h3>
<div id="create"></div>
<h3>
<a class="anchor" name="create" href="#create">
<code>create(opts)</code>
</a>
</h3>
Create a new toast component. See options below
<table class="table param-table" style="margin:0;">
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>
opts
</td>
<td>
<code>ToastOptions</code>
</td>
<td>
<p>Toast options. See the below table for available options.</p>
</td>
</tr>
</tbody>
</table>
<h2><a class="anchor" name="advanced" href="#advanced">Advanced</a></h2>
<table>
<thead>
<tr>
<th>Property</th>
<th>Type</th>
<th>Default</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>message</td>
<td><code>string</code></td>
<td>-</td>
<td>The message for the toast. Long strings will wrap and the toast container will expand.</td>
</tr>
<tr>
<td>duration</td>
<td><code>number</code></td>
<td>-</td>
<td>How many milliseconds to wait before hiding the toast. By default, it will show until <code>dismiss()</code> is called.</td>
</tr>
<tr>
<td>position</td>
<td><code>string</code></td>
<td>"bottom"</td>
<td>The position of the toast on the screen. Accepted values: "top", "middle", "bottom".</td>
</tr>
<tr>
<td>cssClass</td>
<td><code>string</code></td>
<td>-</td>
<td>Additional classes for custom styles, separated by spaces.</td>
</tr>
<tr>
<td>showCloseButton</td>
<td><code>boolean</code></td>
<td>false</td>
<td>Whether or not to show a button to close the toast.</td>
</tr>
<tr>
<td>closeButtonText</td>
<td><code>string</code></td>
<td>"Close"</td>
<td>Text to display in the close button.</td>
</tr>
<tr>
<td>dismissOnPageChange</td>
<td><code>boolean</code></td>
<td>false</td>
<td>Whether to dismiss the toast when navigating to a new page.</td>
</tr>
</tbody>
</table>
<h2 id="sass-variable-header"><a class="anchor" name="sass-variables" href="#sass-variables">Sass Variables</a></h2>
<div id="sass-variables" ng-controller="SassToggleCtrl">
<div class="sass-platform-toggle">
<a ng-init="setSassPlatform('base')" ng-class="{ active: active === 'base' }" ng-click="setSassPlatform('base')" >All</a>
<a ng-class="{ active: active === 'ios' }" ng-click="setSassPlatform('ios')">iOS</a>
<a ng-class="{ active: active === 'md' }" ng-click="setSassPlatform('md')">Material Design</a>
<a ng-class="{ active: active === 'wp' }" ng-click="setSassPlatform('wp')">Windows Platform</a>
</div>
<table ng-show="active === 'base'" id="sass-base" class="table param-table" style="margin:0;">
<thead>
<tr>
<th>Property</th>
<th>Default</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>$toast-width</code></td>
<td><code>100%</code></td>
<td><p>Width of the toast</p>
</td>
</tr>
<tr>
<td><code>$toast-max-width</code></td>
<td><code>700px</code></td>
<td><p>Max width of the toast</p>
</td>
</tr>
</tbody>
</table>
<table ng-show="active === 'ios'" id="sass-ios" class="table param-table" style="margin:0;">
<thead>
<tr>
<th>Property</th>
<th>Default</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>$toast-ios-background</code></td>
<td><code>rgba(0, 0, 0, .9)</code></td>
<td><p>Background of the toast wrapper</p>
</td>
</tr>
<tr>
<td><code>$toast-ios-border-radius</code></td>
<td><code>.65rem</code></td>
<td><p>Border radius of the toast wrapper</p>
</td>
</tr>
<tr>
<td><code>$toast-ios-title-color</code></td>
<td><code>#fff</code></td>
<td><p>Color of the toast title</p>
</td>
</tr>
<tr>
<td><code>$toast-ios-title-font-size</code></td>
<td><code>1.4rem</code></td>
<td><p>Font size of the toast title</p>
</td>
</tr>
<tr>
<td><code>$toast-ios-title-padding-top</code></td>
<td><code>1.5rem</code></td>
<td><p>Padding top of the toast title</p>
</td>
</tr>
<tr>
<td><code>$toast-ios-title-padding-end</code></td>
<td><code>$toast-ios-title-padding-top</code></td>
<td><p>Padding end of the toast title</p>
</td>
</tr>
<tr>
<td><code>$toast-ios-title-padding-bottom</code></td>
<td><code>$toast-ios-title-padding-top</code></td>
<td><p>Padding bottom of the toast title</p>
</td>
</tr>
<tr>
<td><code>$toast-ios-title-padding-start</code></td>
<td><code>$toast-ios-title-padding-end</code></td>
<td><p>Padding start of the toast title</p>
</td>
</tr>
</tbody>
</table>
<table ng-show="active === 'md'" id="sass-md" class="table param-table" style="margin:0;">
<thead>
<tr>
<th>Property</th>
<th>Default</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>$toast-md-background</code></td>
<td><code>#333</code></td>
<td><p>Background of the toast wrapper</p>
</td>
</tr>
<tr>
<td><code>$toast-md-title-color</code></td>
<td><code>#fff</code></td>
<td><p>Color of the toast title</p>
</td>
</tr>
<tr>
<td><code>$toast-md-title-font-size</code></td>
<td><code>1.5rem</code></td>
<td><p>Font size of the toast title</p>
</td>
</tr>
<tr>
<td><code>$toast-md-title-padding-top</code></td>
<td><code>19px</code></td>
<td><p>Padding top of the toast title</p>
</td>
</tr>
<tr>
<td><code>$toast-md-title-padding-end</code></td>
<td><code>16px</code></td>
<td><p>Padding end of the toast title</p>
</td>
</tr>
<tr>
<td><code>$toast-md-title-padding-bottom</code></td>
<td><code>17px</code></td>
<td><p>Padding bottom of the toast title</p>
</td>
</tr>
<tr>
<td><code>$toast-md-title-padding-start</code></td>
<td><code>$toast-md-title-padding-end</code></td>
<td><p>Padding start of the toast title</p>
</td>
</tr>
</tbody>
</table>
<table ng-show="active === 'wp'" id="sass-wp" class="table param-table" style="margin:0;">
<thead>
<tr>
<th>Property</th>
<th>Default</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>$toast-wp-background</code></td>
<td><code>rgba(0, 0, 0, 1)</code></td>
<td><p>Background of the toast wrapper</p>
</td>
</tr>
<tr>
<td><code>$toast-wp-border-radius</code></td>
<td><code>0</code></td>
<td><p>Border radius of the toast wrapper</p>
</td>
</tr>
<tr>
<td><code>$toast-wp-button-color</code></td>
<td><code>#fff</code></td>
<td><p>Color of the toast button</p>
</td>
</tr>
<tr>
<td><code>$toast-wp-title-color</code></td>
<td><code>#fff</code></td>
<td><p>Color of the toast title</p>
</td>
</tr>
<tr>
<td><code>$toast-wp-title-font-size</code></td>
<td><code>1.4rem</code></td>
<td><p>Font size of the toast title</p>
</td>
</tr>
<tr>
<td><code>$toast-wp-title-padding-top</code></td>
<td><code>1.5rem</code></td>
<td><p>Padding top of the toast title</p>
</td>
</tr>
<tr>
<td><code>$toast-wp-title-padding-end</code></td>
<td><code>$toast-wp-title-padding-top</code></td>
<td><p>Padding end of the toast title</p>
</td>
</tr>
<tr>
<td><code>$toast-wp-title-padding-bottom</code></td>
<td><code>$toast-wp-title-padding-top</code></td>
<td><p>Padding bottom of the toast title</p>
</td>
</tr>
<tr>
<td><code>$toast-wp-title-padding-start</code></td>
<td><code>$toast-wp-title-padding-end</code></td>
<td><p>Padding start of the toast title</p>
</td>
</tr>
</tbody>
</table>
</div>
<!-- related link --><!-- end content block -->
<!-- end body block -->
|
Java
|
#include <Wire.h>
#include "lis331dlh.h"
#include "l3g4200d.h"
#include "lis3mdl.h"
#include "LPS331.h"
#include "MadgwickAHRS.h"
// Accelerometer
#define ACCEL_ADDRESS_V1 LIS331DLH_TWI_ADDRESS
#define ACCEL_ADDRESS_V2 LIS331DLH_TWI_ADDRESS_V2
// Gyroscope
#define GYRO_ADDRESS_V1 L3G4200D_TWI_ADDRESS
#define GYRO_ADDRESS_V2 L3G4200D_TWI_ADDRESS_V2
// Compass
#define COMPASS_ADDRESS_V1 LIS3MDL_TWI_ADDRESS
#define COMPASS_ADDRESS_V2 LIS3MDL_TWI_ADDRESS_V2
// Barometer
#define BARO_ADDRESS_V1 LPS331AP_TWI_ADDRESS
#define BARO_ADDRESS_V2 LPS331AP_TWI_ADDRESS_V2
class Accelerometer : public LIS331DLH_TWI
{
public:
Accelerometer(uint8_t addr = ACCEL_ADDRESS_V1) :
LIS331DLH_TWI(addr) {}
};
class Gyroscope : public L3G4200D_TWI
{
public:
Gyroscope(uint8_t addr = GYRO_ADDRESS_V1) :
L3G4200D_TWI(addr) {}
};
class Compass : public LIS3MDL_TWI
{
public:
Compass(uint8_t addr = COMPASS_ADDRESS_V1) :
LIS3MDL_TWI(addr) {}
};
class Barometer : public LPS331
{
public:
Barometer(uint8_t addr = BARO_ADDRESS_V1) :
LPS331(addr) {}
};
|
Java
|
# -*- coding:utf-8 -*-
__author__ = 'q00222219@huawei'
import time
from heat.openstack.common import log as logging
import heat.engine.resources.cloudmanager.commonutils as commonutils
import heat.engine.resources.cloudmanager.constant as constant
import heat.engine.resources.cloudmanager.exception as exception
import pdb
LOG = logging.getLogger(__name__)
class CascadedConfiger(object):
def __init__(self, public_ip_api, api_ip, domain, user, password,
cascading_domain, cascading_api_ip, cascaded_domain,
cascaded_api_ip, cascaded_api_subnet_gateway):
self.public_ip_api = public_ip_api
self.api_ip = api_ip
self.domain = domain
self.user = user
self.password = password
self.cascading_domain = cascading_domain
self.cascading_api_ip = cascading_api_ip
self.cascaded_domain = cascaded_domain
self.cascaded_ip = cascaded_api_ip
self.gateway = cascaded_api_subnet_gateway
def do_config(self):
start_time = time.time()
#pdb.set_trace()
LOG.info("start config cascaded, cascaded: %s" % self.domain)
# wait cascaded tunnel can visit
commonutils.check_host_status(host=self.public_ip_api,
user=self.user,
password=self.password,
retry_time=500, interval=1)
# config cascaded host
self._config_az_cascaded()
cost_time = time.time() - start_time
LOG.info("first config success, cascaded: %s, cost time: %d"
% (self.domain, cost_time))
# check config result
for i in range(3):
try:
# check 90s
commonutils.check_host_status(
host=self.public_ip_api,
user=constant.VcloudConstant.ROOT,
password=constant.VcloudConstant.ROOT_PWD,
retry_time=15,
interval=1)
LOG.info("cascaded api is ready..")
break
except exception.CheckHostStatusFailure:
if i == 2:
LOG.error("check cascaded api failed ...")
break
LOG.error("check cascaded api error, "
"retry config cascaded ...")
self._config_az_cascaded()
cost_time = time.time() - start_time
LOG.info("config cascaded success, cascaded: %s, cost_time: %d"
% (self.domain, cost_time))
def _config_az_cascaded(self):
LOG.info("start config cascaded host, host: %s" % self.api_ip)
# modify dns server address
address = "/%(cascading_domain)s/%(cascading_ip)s,/%(cascaded_domain)s/%(cascaded_ip)s" \
% {"cascading_domain": self.cascading_domain,
"cascading_ip": self.cascading_api_ip,
"cascaded_domain":self.cascaded_domain,
"cascaded_ip":self.cascaded_ip}
for i in range(30):
try:
commonutils.execute_cmd_without_stdout(
host=self.public_ip_api,
user=self.user,
password=self.password,
cmd='cd %(dir)s; source /root/adminrc; sh %(script)s replace %(address)s'
% {"dir": constant.PublicConstant.SCRIPTS_DIR,
"script": constant.PublicConstant.
MODIFY_DNS_SERVER_ADDRESS,
"address": address})
break
except exception.SSHCommandFailure as e:
LOG.error("modify cascaded dns address error, cascaded: "
"%s, error: %s"
% (self.domain, e.format_message()))
time.sleep(1)
LOG.info(
"config cascaded dns address success, cascaded: %s"
% self.public_ip_api)
return True
|
Java
|
#ifdef WINDOWS_PLATFORM
#include "WindowsInputService.hpp"
#include "WindowsMouseInterface.hpp"
#include "WindowsKeyboardInterface.hpp"
namespace MPACK
{
namespace Input
{
WindowsInputService::WindowsInputService()
{
m_pMouse = new WindowsMouseInterface;
m_pKeyboard = new WindowsKeyboardInterface;
Reset();
}
WindowsInputService::~WindowsInputService()
{
}
void WindowsInputService::Update()
{
m_pMouse->Update();
m_pKeyboard->Update();
}
void WindowsInputService::Reset()
{
m_pMouse->Reset();
m_pKeyboard->Reset();
}
MouseInterface* WindowsInputService::GetMouse() const
{
return m_pMouse;
}
KeyboardInterface* WindowsInputService::GetKeyboard() const
{
return m_pKeyboard;
}
}
}
#endif
|
Java
|
angular.module('app.services', [
'app.services.actions',
'app.services.connection',
'app.services.coverart',
'app.services.locale',
'app.services.logging',
'app.services.mopidy',
'app.services.paging',
'app.services.platform',
'app.services.router',
'app.services.servers',
'app.services.settings'
]);
|
Java
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class LocalRewriter
Private Function WrapInNullable(expr As BoundExpression, nullableType As TypeSymbol) As BoundExpression
Debug.Assert(nullableType.GetNullableUnderlyingType.IsSameTypeIgnoringAll(expr.Type))
Dim ctor = GetNullableMethod(expr.Syntax, nullableType, SpecialMember.System_Nullable_T__ctor)
If ctor IsNot Nothing Then
Return New BoundObjectCreationExpression(expr.Syntax,
ctor,
ImmutableArray.Create(expr),
Nothing,
nullableType)
End If
Return New BoundBadExpression(expr.Syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(expr), nullableType, hasErrors:=True)
End Function
''' <summary>
''' Splits nullable operand into a hasValueExpression and an expression that represents underlying value (returned).
'''
''' Underlying value can be called after calling hasValueExpr without duplicated side-effects.
''' Note that hasValueExpr is guaranteed to have NO SIDE-EFFECTS, while result value is
''' expected to be called exactly ONCE. That is the normal pattern in operator lifting.
'''
''' All necessary temps and side-effecting initializations are appended to temps and inits
''' </summary>
Private Function ProcessNullableOperand(operand As BoundExpression,
<Out> ByRef hasValueExpr As BoundExpression,
ByRef temps As ArrayBuilder(Of LocalSymbol),
ByRef inits As ArrayBuilder(Of BoundExpression),
doNotCaptureLocals As Boolean) As BoundExpression
Return ProcessNullableOperand(operand, hasValueExpr, temps, inits, doNotCaptureLocals, HasValue(operand))
End Function
Private Function ProcessNullableOperand(operand As BoundExpression,
<Out> ByRef hasValueExpr As BoundExpression,
ByRef temps As ArrayBuilder(Of LocalSymbol),
ByRef inits As ArrayBuilder(Of BoundExpression),
doNotCaptureLocals As Boolean,
operandHasValue As Boolean) As BoundExpression
Debug.Assert(Not HasNoValue(operand), "processing nullable operand when it is known to be null")
If operandHasValue Then
operand = NullableValueOrDefault(operand)
End If
Dim captured = CaptureNullableIfNeeded(operand, temps, inits, doNotCaptureLocals)
If operandHasValue Then
hasValueExpr = New BoundLiteral(operand.Syntax, ConstantValue.True, Me.GetSpecialType(SpecialType.System_Boolean))
Return captured
End If
hasValueExpr = NullableHasValue(captured)
Return NullableValueOrDefault(captured)
End Function
' Right operand could be a method that takes Left operand byref. Ex: " local And TakesArgByref(local) "
' So in general we must capture Left even if it is a local.
' however in many case we do not need that.
Private Function RightCanChangeLeftLocal(left As BoundExpression, right As BoundExpression) As Boolean
' TODO: in most cases right operand does not change value of the left one
' we could be smarter than this.
Return right.Kind = BoundKind.Local OrElse
right.Kind = BoundKind.Parameter
End Function
''' <summary>
''' Returns a NOT-SIDE-EFFECTING expression that represents results of the operand
''' If such transformation requires a temp, the temp and its initializing expression
''' are returned in temp/init
''' </summary>
Private Function CaptureNullableIfNeeded(operand As BoundExpression,
<Out> ByRef temp As SynthesizedLocal,
<Out> ByRef init As BoundExpression,
doNotCaptureLocals As Boolean) As BoundExpression
temp = Nothing
init = Nothing
If operand.IsConstant Then
Return operand
End If
If doNotCaptureLocals Then
If operand.Kind = BoundKind.Local AndAlso Not DirectCast(operand, BoundLocal).LocalSymbol.IsByRef Then
Return operand
End If
If operand.Kind = BoundKind.Parameter AndAlso Not DirectCast(operand, BoundParameter).ParameterSymbol.IsByRef Then
Return operand
End If
End If
' capture into local.
Return CaptureOperand(operand, temp, init)
End Function
Private Function CaptureOperand(operand As BoundExpression, <Out> ByRef temp As SynthesizedLocal, <Out> ByRef init As BoundExpression) As BoundExpression
temp = New SynthesizedLocal(Me._currentMethodOrLambda, operand.Type, SynthesizedLocalKind.LoweringTemp)
Dim localAccess = New BoundLocal(operand.Syntax, temp, True, temp.Type)
init = New BoundAssignmentOperator(operand.Syntax, localAccess, operand, True, operand.Type)
Return localAccess.MakeRValue
End Function
Private Function CaptureNullableIfNeeded(
operand As BoundExpression,
<[In], Out> ByRef temps As ArrayBuilder(Of LocalSymbol),
<[In], Out> ByRef inits As ArrayBuilder(Of BoundExpression),
doNotCaptureLocals As Boolean
) As BoundExpression
Dim temp As SynthesizedLocal = Nothing
Dim init As BoundExpression = Nothing
Dim captured = CaptureNullableIfNeeded(operand, temp, init, doNotCaptureLocals)
If temp IsNot Nothing Then
temps = If(temps, ArrayBuilder(Of LocalSymbol).GetInstance)
temps.Add(temp)
Debug.Assert(init IsNot Nothing)
inits = If(inits, ArrayBuilder(Of BoundExpression).GetInstance)
inits.Add(init)
Else
Debug.Assert(captured Is operand)
End If
Return captured
End Function
''' <summary>
''' Returns expression that -
''' a) evaluates the operand if needed
''' b) produces it's ValueOrDefault.
''' The helper is familiar with wrapping expressions and will go directly after the value
''' skipping wrap/unwrap steps.
''' </summary>
Private Function NullableValueOrDefault(expr As BoundExpression) As BoundExpression
Debug.Assert(expr.Type.IsNullableType)
' check if we are not getting value from freshly constructed nullable
' no need to wrap/unwrap it then.
If expr.Kind = BoundKind.ObjectCreationExpression Then
Dim objectCreation = DirectCast(expr, BoundObjectCreationExpression)
' passing one argument means we are calling New Nullable<T>(arg)
If objectCreation.Arguments.Length = 1 Then
Return objectCreation.Arguments(0)
End If
End If
Dim getValueOrDefaultMethod = GetNullableMethod(expr.Syntax, expr.Type, SpecialMember.System_Nullable_T_GetValueOrDefault)
If getValueOrDefaultMethod IsNot Nothing Then
Return New BoundCall(expr.Syntax,
getValueOrDefaultMethod,
Nothing,
expr,
ImmutableArray(Of BoundExpression).Empty,
Nothing,
isLValue:=False,
suppressObjectClone:=True,
type:=getValueOrDefaultMethod.ReturnType)
End If
Return New BoundBadExpression(expr.Syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(expr), expr.Type.GetNullableUnderlyingType(), hasErrors:=True)
End Function
Private Function NullableValue(expr As BoundExpression) As BoundExpression
Debug.Assert(expr.Type.IsNullableType)
If HasValue(expr) Then
Return NullableValueOrDefault(expr)
End If
Dim getValueMethod As MethodSymbol = GetNullableMethod(expr.Syntax, expr.Type, SpecialMember.System_Nullable_T_get_Value)
If getValueMethod IsNot Nothing Then
Return New BoundCall(expr.Syntax,
getValueMethod,
Nothing,
expr,
ImmutableArray(Of BoundExpression).Empty,
Nothing,
isLValue:=False,
suppressObjectClone:=True,
type:=getValueMethod.ReturnType)
End If
Return New BoundBadExpression(expr.Syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(expr), expr.Type.GetNullableUnderlyingType(), hasErrors:=True)
End Function
''' <summary>
''' Evaluates expr and calls HasValue on it.
''' </summary>
Private Function NullableHasValue(expr As BoundExpression) As BoundExpression
Debug.Assert(expr.Type.IsNullableType)
' when we statically know if expr HasValue we may skip
' evaluation depending on context.
Debug.Assert(Not HasValue(expr))
Debug.Assert(Not HasNoValue(expr))
Dim hasValueMethod As MethodSymbol = GetNullableMethod(expr.Syntax, expr.Type, SpecialMember.System_Nullable_T_get_HasValue)
If hasValueMethod IsNot Nothing Then
Return New BoundCall(expr.Syntax,
hasValueMethod,
Nothing,
expr,
ImmutableArray(Of BoundExpression).Empty,
Nothing,
isLValue:=False,
suppressObjectClone:=True,
type:=hasValueMethod.ReturnType)
End If
Return New BoundBadExpression(expr.Syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(expr),
Me.Compilation.GetSpecialType(SpecialType.System_Boolean), hasErrors:=True)
End Function
Private Shared Function NullableNull(syntax As SyntaxNode, nullableType As TypeSymbol) As BoundExpression
Debug.Assert(nullableType.IsNullableType)
Return New BoundObjectCreationExpression(syntax,
Nothing,
ImmutableArray(Of BoundExpression).Empty,
Nothing,
nullableType)
End Function
''' <summary>
''' Checks that candidate Null expression is a simple expression that produces Null of the desired type
''' (not a conversion or anything like that) and returns it.
''' Otherwise creates "New T?()" expression.
''' </summary>
Private Shared Function NullableNull(candidateNullExpression As BoundExpression,
type As TypeSymbol) As BoundExpression
Debug.Assert(HasNoValue(candidateNullExpression))
' in case if the expression is any more complicated than just creating a Null
' simplify it. This may happen if HasNoValue gets smarter and can
' detect situations other than "New T?()"
If (Not type.IsSameTypeIgnoringAll(candidateNullExpression.Type)) OrElse
candidateNullExpression.Kind <> BoundKind.ObjectCreationExpression Then
Return NullableNull(candidateNullExpression.Syntax, type)
End If
Return candidateNullExpression
End Function
Private Function NullableFalse(syntax As SyntaxNode, nullableOfBoolean As TypeSymbol) As BoundExpression
Debug.Assert(nullableOfBoolean.IsNullableOfBoolean)
Dim booleanType = nullableOfBoolean.GetNullableUnderlyingType
Return WrapInNullable(New BoundLiteral(syntax, ConstantValue.False, booleanType), nullableOfBoolean)
End Function
Private Function NullableTrue(syntax As SyntaxNode, nullableOfBoolean As TypeSymbol) As BoundExpression
Debug.Assert(nullableOfBoolean.IsNullableOfBoolean)
Dim booleanType = nullableOfBoolean.GetNullableUnderlyingType
Return WrapInNullable(New BoundLiteral(syntax, ConstantValue.True, booleanType), nullableOfBoolean)
End Function
Private Function GetNullableMethod(syntax As SyntaxNode, nullableType As TypeSymbol, member As SpecialMember) As MethodSymbol
Dim method As MethodSymbol = Nothing
If TryGetSpecialMember(method, member, syntax) Then
Dim substitutedType = DirectCast(nullableType, SubstitutedNamedType)
Return DirectCast(substitutedType.GetMemberForDefinition(method), MethodSymbol)
End If
Return Nothing
End Function
Private Function NullableOfBooleanValue(syntax As SyntaxNode, isTrue As Boolean, nullableOfBoolean As TypeSymbol) As BoundExpression
If isTrue Then
Return NullableTrue(syntax, nullableOfBoolean)
Else
Return NullableFalse(syntax, nullableOfBoolean)
End If
End Function
''' <summary>
''' returns true when expression has NO SIDE-EFFECTS and is known to produce nullable NULL
''' </summary>
Private Shared Function HasNoValue(expr As BoundExpression) As Boolean
Debug.Assert(expr.Type.IsNullableType)
If expr.Kind = BoundKind.ObjectCreationExpression Then
Dim objCreation = DirectCast(expr, BoundObjectCreationExpression)
' Nullable<T> has only one ctor with parameters and only that one sets hasValue = true
Return objCreation.Arguments.Length = 0
End If
' by default we do not know
Return False
End Function
''' <summary>
''' Returns true when expression is known to produce nullable NOT-NULL
''' NOTE: unlike HasNoValue case, HasValue expressions may have side-effects.
''' </summary>
Private Shared Function HasValue(expr As BoundExpression) As Boolean
Debug.Assert(expr.Type.IsNullableType)
If expr.Kind = BoundKind.ObjectCreationExpression Then
Dim objCreation = DirectCast(expr, BoundObjectCreationExpression)
' Nullable<T> has only one ctor with parameters and only that one sets hasValue = true
Return objCreation.Arguments.Length <> 0
End If
' by default we do not know
Return False
End Function
''' <summary>
''' Helper to generate binary expressions.
''' Performs some trivial constant folding.
''' TODO: Perhaps belong to a different file
''' </summary>
Private Function MakeBinaryExpression(syntax As SyntaxNode,
binaryOpKind As BinaryOperatorKind,
left As BoundExpression,
right As BoundExpression,
isChecked As Boolean,
resultType As TypeSymbol) As BoundExpression
Debug.Assert(Not left.Type.IsNullableType)
Debug.Assert(Not right.Type.IsNullableType)
Dim intOverflow As Boolean = False
Dim divideByZero As Boolean = False
Dim lengthOutOfLimit As Boolean = False
Dim constant = OverloadResolution.TryFoldConstantBinaryOperator(binaryOpKind, left, right, resultType, intOverflow, divideByZero, lengthOutOfLimit)
If constant IsNot Nothing AndAlso
Not divideByZero AndAlso
Not (intOverflow And isChecked) AndAlso
Not lengthOutOfLimit Then
Debug.Assert(Not constant.IsBad)
Return New BoundLiteral(syntax, constant, resultType)
End If
Select Case binaryOpKind
Case BinaryOperatorKind.Subtract
If right.IsDefaultValueConstant Then
Return left
End If
Case BinaryOperatorKind.Add,
BinaryOperatorKind.Or,
BinaryOperatorKind.OrElse
' if one of operands is trivial, return the other one
If left.IsDefaultValueConstant Then
Return right
End If
If right.IsDefaultValueConstant Then
Return left
End If
' if one of operands is True, evaluate the other and return the True one
If left.IsTrueConstant Then
Return MakeSequence(right, left)
End If
If right.IsTrueConstant Then
Return MakeSequence(left, right)
End If
Case BinaryOperatorKind.And,
BinaryOperatorKind.AndAlso,
BinaryOperatorKind.Multiply
' if one of operands is trivial, evaluate the other and return the trivial one
If left.IsDefaultValueConstant Then
Return MakeSequence(right, left)
End If
If right.IsDefaultValueConstant Then
Return MakeSequence(left, right)
End If
' if one of operands is True, return the other one
If left.IsTrueConstant Then
Return right
End If
If right.IsTrueConstant Then
Return left
End If
Case BinaryOperatorKind.Equals
If left.IsTrueConstant Then
Return right
End If
If right.IsTrueConstant Then
Return left
End If
Case BinaryOperatorKind.NotEquals
If left.IsFalseConstant Then
Return right
End If
If right.IsFalseConstant Then
Return left
End If
End Select
Return TransformRewrittenBinaryOperator(New BoundBinaryOperator(syntax, binaryOpKind, left, right, isChecked, resultType))
End Function
''' <summary>
''' Simpler helper for binary expressions.
''' When operand are boolean, the result type is same as operand's and is never checked
''' so do not need to pass that in.
''' </summary>
Private Function MakeBooleanBinaryExpression(syntax As SyntaxNode,
binaryOpKind As BinaryOperatorKind,
left As BoundExpression,
right As BoundExpression) As BoundExpression
Debug.Assert(TypeSymbol.Equals(left.Type, right.Type, TypeCompareKind.ConsiderEverything))
Debug.Assert(left.Type.IsBooleanType)
Return MakeBinaryExpression(syntax, binaryOpKind, left, right, False, left.Type)
End Function
Private Shared Function MakeNullLiteral(syntax As SyntaxNode, type As TypeSymbol) As BoundLiteral
Return New BoundLiteral(syntax, ConstantValue.Nothing, type)
End Function
''' <summary>
''' Takes two expressions and makes sequence.
''' </summary>
Private Shared Function MakeSequence(first As BoundExpression, second As BoundExpression) As BoundExpression
Return MakeSequence(second.Syntax, first, second)
End Function
''' <summary>
''' Takes two expressions and makes sequence.
''' </summary>
Private Shared Function MakeSequence(syntax As SyntaxNode,
first As BoundExpression,
second As BoundExpression) As BoundExpression
Dim sideeffects = GetSideeffects(first)
If sideeffects Is Nothing Then
Return second
End If
Return New BoundSequence(syntax,
ImmutableArray(Of LocalSymbol).Empty,
ImmutableArray.Create(sideeffects),
second,
second.Type)
End Function
''' <summary>
''' Takes two expressions and makes sequence.
''' </summary>
Private Function MakeTernaryConditionalExpression(syntax As SyntaxNode,
condition As BoundExpression,
whenTrue As BoundExpression,
whenFalse As BoundExpression) As BoundExpression
Debug.Assert(condition.Type.IsBooleanType, "ternary condition must be boolean")
Debug.Assert(whenTrue.Type.IsSameTypeIgnoringAll(whenFalse.Type), "ternary branches must have same types")
Dim ifConditionConst = condition.ConstantValueOpt
If ifConditionConst IsNot Nothing Then
Return MakeSequence(syntax, condition, If(ifConditionConst Is ConstantValue.True, whenTrue, whenFalse))
End If
Return TransformRewrittenTernaryConditionalExpression(New BoundTernaryConditionalExpression(syntax, condition, whenTrue, whenFalse, Nothing, whenTrue.Type))
End Function
''' <summary>
''' Returns an expression that can be used instead of the original one when
''' we want to run the expression for side-effects only (i.e. we intend to ignore result).
''' </summary>
Private Shared Function GetSideeffects(operand As BoundExpression) As BoundExpression
If operand.IsConstant Then
Return Nothing
End If
Select Case operand.Kind
Case BoundKind.Local,
BoundKind.Parameter
Return Nothing
Case BoundKind.ObjectCreationExpression
If operand.Type.IsNullableType Then
Dim objCreation = DirectCast(operand, BoundObjectCreationExpression)
Dim args = objCreation.Arguments
If args.Length = 0 Then
Return Nothing
Else
Return GetSideeffects(args(0))
End If
End If
End Select
Return operand
End Function
End Class
End Namespace
|
Java
|
//-----------------------------------------------------------------------
// <copyright file="FilterTreeDragDropArgs.cs" company="Development In Progress Ltd">
// Copyright © Development In Progress Ltd 2015. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace DevelopmentInProgress.WPFControls.FilterTree
{
/// <summary>
/// Arguments for a drag and drop operation in the <see cref="XamlFilterTree"/>.
/// </summary>
public class FilterTreeDragDropArgs
{
/// <summary>
/// Initialises a new instance of the FilterTreeDragDropArgs class.
/// </summary>
/// <param name="dragItem">The item being dragged.</param>
/// <param name="dropTarget">The target where the dragged item will be dropped.</param>
public FilterTreeDragDropArgs(object dragItem, object dropTarget)
{
DragItem = dragItem;
DropTarget = dropTarget;
}
/// <summary>
/// Gets the object being dragged.
/// </summary>
public object DragItem { get; private set; }
/// <summary>
/// Gets the drop target for the object being dragged.
/// </summary>
public object DropTarget { get; private set; }
}
}
|
Java
|
package com.structurizr.view;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.structurizr.model.*;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.stream.Collectors;
@JsonIgnoreProperties(ignoreUnknown=true)
public abstract class View implements Comparable<View> {
private SoftwareSystem softwareSystem;
private String softwareSystemId;
private String description = "";
private PaperSize paperSize = PaperSize.A4_Portrait;
private Set<ElementView> elementViews = new LinkedHashSet<>();
View() {
}
public View(SoftwareSystem softwareSystem) {
this.softwareSystem = softwareSystem;
}
@JsonIgnore
public Model getModel() {
return softwareSystem.getModel();
}
@JsonIgnore
public SoftwareSystem getSoftwareSystem() {
return softwareSystem;
}
public void setSoftwareSystem(SoftwareSystem softwareSystem) {
this.softwareSystem = softwareSystem;
}
public String getSoftwareSystemId() {
if (this.softwareSystem != null) {
return this.softwareSystem.getId();
} else {
return this.softwareSystemId;
}
}
void setSoftwareSystemId(String softwareSystemId) {
this.softwareSystemId = softwareSystemId;
}
public abstract ViewType getType();
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public PaperSize getPaperSize() {
return paperSize;
}
public void setPaperSize(PaperSize paperSize) {
this.paperSize = paperSize;
}
/**
* Adds all software systems in the model to this view.
*/
public void addAllSoftwareSystems() {
getModel().getSoftwareSystems().forEach(this::addElement);
}
/**
* Adds the given software system to this view.
*
* @param softwareSystem the SoftwareSystem to add
*/
public void addSoftwareSystem(SoftwareSystem softwareSystem) {
addElement(softwareSystem);
}
/**
* Adds all software systems in the model to this view.
*/
public void addAllPeople() {
getModel().getPeople().forEach(this::addElement);
}
/**
* Adds the given person to this view.
*
* @param person the Person to add
*/
public void addPerson(Person person) {
addElement(person);
}
protected void addElement(Element element) {
if (softwareSystem.getModel().contains(element)) {
elementViews.add(new ElementView(element));
}
}
protected void removeElement(Element element) {
ElementView elementView = new ElementView(element);
elementViews.remove(elementView);
}
/**
* Gets the set of elements in this view.
*
* @return a Set of ElementView objects
*/
public Set<ElementView> getElements() {
return elementViews;
}
public Set<RelationshipView> getRelationships() {
Set<Relationship> relationships = new HashSet<>();
Set<Element> elements = getElements().stream()
.map(ElementView::getElement)
.collect(Collectors.toSet());
elements.forEach(b -> relationships.addAll(b.getRelationships()));
return relationships.stream()
.filter(r -> elements.contains(r.getSource()) && elements.contains(r.getDestination()))
.map(RelationshipView::new)
.collect(Collectors.toSet());
}
public void setRelationships(Set<RelationshipView> relationships) {
// do nothing ... this are determined automatically
}
/**
* Removes all elements that have no relationships
* to other elements in this view.
*/
public void removeElementsWithNoRelationships() {
Set<RelationshipView> relationships = getRelationships();
Set<String> elementIds = new HashSet<>();
relationships.forEach(rv -> elementIds.add(rv.getRelationship().getSourceId()));
relationships.forEach(rv -> elementIds.add(rv.getRelationship().getDestinationId()));
elementViews.removeIf(ev -> !elementIds.contains(ev.getId()));
}
public void removeElementsThatCantBeReachedFrom(Element element) {
Set<String> elementIdsToShow = new HashSet<>();
findElementsToShow(element, elementIdsToShow, 1);
elementViews.removeIf(ev -> !elementIdsToShow.contains(ev.getId()));
}
private void findElementsToShow(Element element, Set<String> elementIds, int depth) {
if (elementViews.contains(new ElementView(element))) {
elementIds.add(element.getId());
if (depth < 100) {
element.getRelationships().forEach(r -> findElementsToShow(r.getDestination(), elementIds, depth + 1));
}
}
}
public abstract String getName();
@Override
public int compareTo(View view) {
return getTitle().compareTo(view.getTitle());
}
private String getTitle() {
return getName() + " - " + getDescription();
}
ElementView findElementView(Element element) {
for (ElementView elementView : getElements()) {
if (elementView.getElement().equals(element)) {
return elementView;
}
}
return null;
}
public void copyLayoutInformationFrom(View source) {
this.setPaperSize(source.getPaperSize());
for (ElementView sourceElementView : source.getElements()) {
ElementView destinationElementView = findElementView(sourceElementView.getElement());
if (destinationElementView != null) {
destinationElementView.copyLayoutInformationFrom(sourceElementView);
}
}
}
}
|
Java
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Text.Json;
using Azure.Core;
namespace Azure.Management.Network.Models
{
internal partial class ErrorDetails
{
internal static ErrorDetails DeserializeErrorDetails(JsonElement element)
{
string code = default;
string target = default;
string message = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("code"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
code = property.Value.GetString();
continue;
}
if (property.NameEquals("target"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
target = property.Value.GetString();
continue;
}
if (property.NameEquals("message"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
message = property.Value.GetString();
continue;
}
}
return new ErrorDetails(code, target, message);
}
}
}
|
Java
|
/*
* Copyright (c) 2016 The original author or authors
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.ext.consul;
import io.vertx.codegen.annotations.DataObject;
import io.vertx.core.json.JsonObject;
import java.util.List;
/**
* Holds network coordinates of node
*
* @author <a href="mailto:ruslan.sennov@gmail.com">Ruslan Sennov</a>
* @see <a href="https://www.consul.io/docs/internals/coordinates.html">Network coordinates</a>
*/
@DataObject(generateConverter = true)
public class Coordinate {
private String node;
private float adj;
private float err;
private float height;
private List<Float> vec;
/**
* Default constructor
*/
public Coordinate() {}
/**
* Copy constructor
*
* @param coordinate the one to copy
*/
public Coordinate(Coordinate coordinate) {
this.node = coordinate.node;
this.adj = coordinate.adj;
this.err = coordinate.err;
this.height = coordinate.height;
this.vec = coordinate.vec;
}
/**
* Constructor from JSON
*
* @param coordinate the JSON
*/
public Coordinate(JsonObject coordinate) {
CoordinateConverter.fromJson(coordinate, this);
}
/**
* Convert to JSON
*
* @return the JSON
*/
public JsonObject toJson() {
JsonObject jsonObject = new JsonObject();
CoordinateConverter.toJson(this, jsonObject);
return jsonObject;
}
/**
* Get name of node
*
* @return name of node
*/
public String getNode() {
return node;
}
/**
* Get adjustment
*
* @return adjustment
*/
public float getAdj() {
return adj;
}
/**
* Get error
*
* @return error
*/
public float getErr() {
return err;
}
/**
* Get height
*
* @return height
*/
public float getHeight() {
return height;
}
/**
* Get vector
*
* @return vector
*/
public List<Float> getVec() {
return vec;
}
/**
* Set name of node
*
* @param node name of node
* @return reference to this, for fluency
*/
public Coordinate setNode(String node) {
this.node = node;
return this;
}
/**
* Set adjustment
*
* @param adj adjustment
* @return reference to this, for fluency
*/
public Coordinate setAdj(float adj) {
this.adj = adj;
return this;
}
/**
* Set error
*
* @param err error
* @return reference to this, for fluency
*/
public Coordinate setErr(float err) {
this.err = err;
return this;
}
/**
* Set height
*
* @param height height
* @return reference to this, for fluency
*/
public Coordinate setHeight(float height) {
this.height = height;
return this;
}
/**
* Set vector
*
* @param vec vector
* @return reference to this, for fluency
*/
public Coordinate setVec(List<Float> vec) {
this.vec = vec;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Coordinate that = (Coordinate) o;
if (Float.compare(that.adj, adj) != 0) return false;
if (Float.compare(that.err, err) != 0) return false;
if (Float.compare(that.height, height) != 0) return false;
if (node != null ? !node.equals(that.node) : that.node != null) return false;
return vec != null ? vec.equals(that.vec) : that.vec == null;
}
@Override
public int hashCode() {
int result = node != null ? node.hashCode() : 0;
result = 31 * result + (adj != +0.0f ? Float.floatToIntBits(adj) : 0);
result = 31 * result + (err != +0.0f ? Float.floatToIntBits(err) : 0);
result = 31 * result + (height != +0.0f ? Float.floatToIntBits(height) : 0);
result = 31 * result + (vec != null ? vec.hashCode() : 0);
return result;
}
}
|
Java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.xml.security.test.dom.transforms.implementations;
import java.io.ByteArrayInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.apache.xml.security.signature.XMLSignatureInput;
import org.apache.xml.security.test.dom.DSNamespaceContext;
import org.apache.xml.security.transforms.Transforms;
import org.apache.xml.security.transforms.implementations.TransformBase64Decode;
import org.apache.xml.security.utils.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/**
* Unit test for {@link org.apache.xml.security.transforms.implementations.TransformBase64Decode}
*
* @author Christian Geuer-Pollmann
*/
public class TransformBase64DecodeTest extends org.junit.Assert {
static org.slf4j.Logger log =
org.slf4j.LoggerFactory.getLogger(TransformBase64DecodeTest.class);
static {
org.apache.xml.security.Init.init();
}
@org.junit.Test
public void test1() throws Exception {
// base64 encoded
String s1 =
"VGhlIFVSSSBvZiB0aGUgdHJhbnNmb3JtIGlzIGh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1s\n"
+ "ZHNpZyNiYXNlNjQ=";
Document doc = TransformBase64DecodeTest.createDocument();
Transforms t = new Transforms(doc);
doc.appendChild(t.getElement());
t.addTransform(TransformBase64Decode.implementedTransformURI);
XMLSignatureInput in =
new XMLSignatureInput(new ByteArrayInputStream(s1.getBytes()));
XMLSignatureInput out = t.performTransforms(in);
String result = new String(out.getBytes());
assertTrue(
result.equals("The URI of the transform is http://www.w3.org/2000/09/xmldsig#base64")
);
}
@org.junit.Test
public void test2() throws Exception {
// base64 encoded twice
String s2 =
"VkdobElGVlNTU0J2WmlCMGFHVWdkSEpoYm5ObWIzSnRJR2x6SUdoMGRIQTZMeTkzZDNjdWR6TXVi\n"
+ "M0puTHpJd01EQXZNRGt2ZUcxcwpaSE5wWnlOaVlYTmxOalE9";
Document doc = TransformBase64DecodeTest.createDocument();
Transforms t = new Transforms(doc);
doc.appendChild(t.getElement());
t.addTransform(TransformBase64Decode.implementedTransformURI);
XMLSignatureInput in =
new XMLSignatureInput(new ByteArrayInputStream(s2.getBytes()));
XMLSignatureInput out = t.performTransforms(t.performTransforms(in));
String result = new String(out.getBytes());
assertTrue(
result.equals("The URI of the transform is http://www.w3.org/2000/09/xmldsig#base64")
);
}
@org.junit.Test
public void test3() throws Exception {
//J-
String input = ""
+ "<Object xmlns:signature='http://www.w3.org/2000/09/xmldsig#'>\n"
+ "<signature:Base64>\n"
+ "VGhlIFVSSSBvZiB0aGU gdHJhbn<RealText>Nmb 3JtIGlzIG<test/>h0dHA6</RealText>Ly93d3cudzMub3JnLzIwMDAvMDkveG1s\n"
+ "ZHNpZyNiYXNlNjQ=\n"
+ "</signature:Base64>\n"
+ "</Object>\n"
;
//J+
DocumentBuilder db = XMLUtils.createDocumentBuilder(false);
db.setErrorHandler(new org.apache.xml.security.utils.IgnoreAllErrorHandler());
Document doc = db.parse(new ByteArrayInputStream(input.getBytes()));
//XMLUtils.circumventBug2650(doc);
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
xpath.setNamespaceContext(new DSNamespaceContext());
String expression = "//ds:Base64";
Node base64Node =
(Node) xpath.evaluate(expression, doc, XPathConstants.NODE);
XMLSignatureInput xmlinput = new XMLSignatureInput(base64Node);
Document doc2 = TransformBase64DecodeTest.createDocument();
Transforms t = new Transforms(doc2);
doc2.appendChild(t.getElement());
t.addTransform(Transforms.TRANSFORM_BASE64_DECODE);
XMLSignatureInput out = t.performTransforms(xmlinput);
String result = new String(out.getBytes());
assertTrue(
"\"" + result + "\"",
result.equals("The URI of the transform is http://www.w3.org/2000/09/xmldsig#base64")
);
}
private static Document createDocument() throws ParserConfigurationException {
DocumentBuilder db = XMLUtils.createDocumentBuilder(false);
Document doc = db.newDocument();
if (doc == null) {
throw new RuntimeException("Could not create a Document");
} else {
log.debug("I could create the Document");
}
return doc;
}
}
|
Java
|
/*
* Copyright (C) 2010 ZXing 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 com.zzn.aeassistant.zxing.decoding;
import android.app.Activity;
import android.content.DialogInterface;
/**
* Simple listener used to exit the app in a few cases.
*
* @author Sean Owen
*/
public final class FinishListener
implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener, Runnable {
private final Activity activityToFinish;
public FinishListener(Activity activityToFinish) {
this.activityToFinish = activityToFinish;
}
@Override
public void onCancel(DialogInterface dialogInterface) {
run();
}
@Override
public void onClick(DialogInterface dialogInterface, int i) {
run();
}
@Override
public void run() {
activityToFinish.finish();
}
}
|
Java
|
import { Component, Input, EventEmitter, SimpleChanges, OnChanges } from '@angular/core';
import { ToasterService } from 'angular2-toaster';
import { TranslateService } from 'ng2-translate';
import { Notification } from '../notification.model';
import { NotificationService } from '../notification.service';
import { PaginationComponent } from '../../shared/pagination/pagination.component';
@Component({
moduleId: module.id,
selector: 'hip-notifications-list',
templateUrl: 'notifications-list.component.html',
styleUrls: ['notifications-list.component.css']
})
export class NotificationsListComponent {
@Input() notifications: Notification[];
// @Input() selectedStatus: String;
// @Input() selectedNotificationType: String;
translatedResponse: any;
// pagination parameters
currentPage = 1;
pageSize = 10;
totalItems: number;
// will contain the notification satisfying the selected status and type
filteredNotifications: Notification[] = [];
constructor(private notificationService: NotificationService,
private toasterService: ToasterService,
private translateService: TranslateService) {}
private markAsRead(notificationId: number) {
this.notificationService.markNotificationAsRead(notificationId)
.then(
(response: any) => {
let readNotification = this.notifications.filter(
function (notification) {
return notification.id === notificationId;
}
)[0];
readNotification.read = true;
// notify change to the service which notifies the toolbar
this.notificationService.announceUnreadNotificationCountDecrease(1);
}
).catch(
(error: any) => {
this.toasterService.pop('error', this.getTranslatedString('Could not mark notification as read'));
}
);
}
getTranslatedString(data: any) {
this.translateService.get(data).subscribe(
(value: any) => {
this.translatedResponse = value;
}
);
return this.translatedResponse;
}
getPage(page: number) {
this.currentPage = page;
}
}
|
Java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* $Header:$
*/
package org.apache.beehive.netui.util;
import java.util.Map;
import java.util.List;
import java.lang.reflect.Array;
import org.apache.beehive.netui.util.logging.Logger;
/**
* This class is used by NetUI tags that use parameters.
*/
public class ParamHelper
{
private static final Logger logger = Logger.getInstance(ParamHelper.class);
/**
* Add a new parameter or update an existing parameter's list of values.
* <p/>
* <em>Implementation Note:</em> in the case that a Map was provided for
* the <code>value</code> parameter, the this returns without doing
* anything; in any other case, params is updated (even in
* <code>value</code> is null).
* </p>
* <p/>
* If value is some object (not an array or list), the string
* representation of that object is added as a value for name. If the
* value is a list (or array) of objects, then the string representation
* of each element is added as a value for name. When there are multiple
* values for a name, then an array of Strings is used in Map.
* </p>
*
* @param params an existing Map of names and values to update
* @param name the name of the parameter to add or update
* @param value an item or list of items to put into the map
* @throws IllegalArgumentException in the case that either the params
* <p/>
* or name given was null
*/
public static void addParam(Map params, String name, Object value)
{
if (params == null)
throw new IllegalArgumentException("Parameter map cannot be null");
if (name == null)
throw new IllegalArgumentException("Parameter name cannot be null");
if (value instanceof Map) {
logger.warn(Bundle.getString("Tags_BadParameterType", name));
return;
}
if (value == null)
value = "";
// check to see if we are adding a new element
// or if this is an existing element
Object o = params.get(name);
int length = 0;
if (o != null) {
assert (o instanceof String ||
o instanceof String[]);
if (o.getClass().isArray()) {
length = Array.getLength(o);
}
else {
length++;
}
}
// check how much size the output needs to be
if (value.getClass().isArray()) {
length += Array.getLength(value);
}
else if (value instanceof List) {
length += ((List) value).size();
}
else {
length++;
}
if (length == 0)
return;
//System.err.println("Number of vaues:" + length);
// if there is only a single value push it to the parameter table
if (length == 1) {
if (value.getClass().isArray()) {
Object val = Array.get(value, 0);
if (val != null)
params.put(name,val.toString());
else
params.put(name,"");
}
else if (value instanceof List) {
List list = (List) value;
Object val = list.get(0);
if (val != null)
params.put(name,val.toString());
else
params.put(name,"");
}
else
params.put(name,value.toString());
return;
}
// allocate the string for the multiple values
String[] values = new String[length];
int offset = 0;
// if we had old values, push them to the new array
if (o != null) {
if (o.getClass().isArray()) {
String[] obs = (String[]) o;
for (;offset<obs.length;offset++) {
values[offset] = obs[offset];
}
}
else {
values[0] = o.toString();
offset = 1;
}
}
// now move the new values to the array starting at the offset
// position
if (value.getClass().isArray())
{
//need to convert this array into a String[]
int size = Array.getLength(value);
for (int i=0; i < size; i++)
{
Object val = Array.get(value, i);
if (val != null)
values[i+offset] = val.toString();
else
values[i+offset] = "";
}
}
else if (value instanceof List)
{
List list = (List) value;
int size = list.size();
for (int i=0; i < size; i++)
{
if (list.get(i) != null)
values[i+offset] = list.get(i).toString();
else
values[i+offset] = "";
}
}
else {
values[offset] = value.toString();
}
// store the new values array
params.put(name, values);
}
}
|
Java
|
package org.jboss.resteasy.spi;
import org.jboss.resteasy.specimpl.MultivaluedMapImpl;
import org.jboss.resteasy.specimpl.PathSegmentImpl;
import org.jboss.resteasy.specimpl.ResteasyUriBuilder;
import org.jboss.resteasy.util.Encode;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.PathSegment;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
/**
* UriInfo implementation with some added extra methods to help process requests
*
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class ResteasyUriInfo implements UriInfo
{
private String path;
private String encodedPath;
private String matchingPath;
private MultivaluedMap<String, String> queryParameters;
private MultivaluedMap<String, String> encodedQueryParameters;
private MultivaluedMap<String, String> pathParameters;
private MultivaluedMap<String, String> encodedPathParameters;
private MultivaluedMap<String, PathSegment[]> pathParameterPathSegments;
private MultivaluedMap<String, PathSegment[]> encodedPathParameterPathSegments;
private List<PathSegment> pathSegments;
private List<PathSegment> encodedPathSegments;
private URI absolutePath;
private URI requestURI;
private URI baseURI;
private List<String> matchedUris;
private List<String> encodedMatchedUris;
private List<String> encodedMatchedPaths = new ArrayList<String>();
private List<Object> ancestors;
public ResteasyUriInfo(URI base, URI relative)
{
String b = base.toString();
if (!b.endsWith("/")) b += "/";
String r = relative.getRawPath();
if (r.startsWith("/"))
{
encodedPath = r;
path = relative.getPath();
}
else
{
encodedPath = "/" + r;
path = "/" + relative.getPath();
}
requestURI = UriBuilder.fromUri(base).path(relative.getRawPath()).replaceQuery(relative.getRawQuery()).build();
baseURI = base;
encodedPathSegments = PathSegmentImpl.parseSegments(encodedPath, false);
this.pathSegments = new ArrayList<PathSegment>(encodedPathSegments.size());
for (PathSegment segment : encodedPathSegments)
{
pathSegments.add(new PathSegmentImpl(((PathSegmentImpl) segment).getOriginal(), true));
}
extractParameters(requestURI.getRawQuery());
extractMatchingPath(encodedPathSegments);
absolutePath = UriBuilder.fromUri(requestURI).replaceQuery(null).build();
}
public ResteasyUriInfo(URI requestURI)
{
String r = requestURI.getRawPath();
if (r.startsWith("/"))
{
encodedPath = r;
path = requestURI.getPath();
}
else
{
encodedPath = "/" + r;
path = "/" + requestURI.getPath();
}
this.requestURI = requestURI;
baseURI = UriBuilder.fromUri(requestURI).replacePath("").build();
encodedPathSegments = PathSegmentImpl.parseSegments(encodedPath, false);
this.pathSegments = new ArrayList<PathSegment>(encodedPathSegments.size());
for (PathSegment segment : encodedPathSegments)
{
pathSegments.add(new PathSegmentImpl(((PathSegmentImpl) segment).getOriginal(), true));
}
extractParameters(requestURI.getRawQuery());
extractMatchingPath(encodedPathSegments);
absolutePath = UriBuilder.fromUri(requestURI).replaceQuery(null).build();
}
/**
* matching path without matrix parameters
*
* @param encodedPathSegments
*/
protected void extractMatchingPath(List<PathSegment> encodedPathSegments)
{
StringBuilder preprocessedPath = new StringBuilder();
for (PathSegment pathSegment : encodedPathSegments)
{
preprocessedPath.append("/").append(pathSegment.getPath());
}
matchingPath = preprocessedPath.toString();
}
/**
* Encoded path without matrix parameters
*
* @return
*/
public String getMatchingPath()
{
return matchingPath;
}
/**
* Create a UriInfo from the baseURI
*
* @param relative
* @return
*/
public ResteasyUriInfo setRequestUri(URI relative)
{
String rel = relative.toString();
if (rel.startsWith(baseURI.toString()))
{
relative = URI.create(rel.substring(baseURI.toString().length()));
}
return new ResteasyUriInfo(baseURI, relative);
}
public String getPath()
{
return path;
}
public String getPath(boolean decode)
{
if (decode) return getPath();
return encodedPath;
}
public List<PathSegment> getPathSegments()
{
return pathSegments;
}
public List<PathSegment> getPathSegments(boolean decode)
{
if (decode) return getPathSegments();
return encodedPathSegments;
}
public URI getRequestUri()
{
return requestURI;
}
public UriBuilder getRequestUriBuilder()
{
return UriBuilder.fromUri(requestURI);
}
public URI getAbsolutePath()
{
return absolutePath;
}
public UriBuilder getAbsolutePathBuilder()
{
return UriBuilder.fromUri(absolutePath);
}
public URI getBaseUri()
{
return baseURI;
}
public UriBuilder getBaseUriBuilder()
{
return UriBuilder.fromUri(baseURI);
}
public MultivaluedMap<String, String> getPathParameters()
{
if (pathParameters == null)
{
pathParameters = new MultivaluedMapImpl<String, String>();
}
return pathParameters;
}
public void addEncodedPathParameter(String name, String value)
{
getEncodedPathParameters().add(name, value);
String value1 = Encode.decodePath(value);
getPathParameters().add(name, value1);
}
private MultivaluedMap<String, String> getEncodedPathParameters()
{
if (encodedPathParameters == null)
{
encodedPathParameters = new MultivaluedMapImpl<String, String>();
}
return encodedPathParameters;
}
public MultivaluedMap<String, PathSegment[]> getEncodedPathParameterPathSegments()
{
if (encodedPathParameterPathSegments == null)
{
encodedPathParameterPathSegments = new MultivaluedMapImpl<String, PathSegment[]>();
}
return encodedPathParameterPathSegments;
}
public MultivaluedMap<String, PathSegment[]> getPathParameterPathSegments()
{
if (pathParameterPathSegments == null)
{
pathParameterPathSegments = new MultivaluedMapImpl<String, PathSegment[]>();
}
return pathParameterPathSegments;
}
public MultivaluedMap<String, String> getPathParameters(boolean decode)
{
if (decode) return getPathParameters();
return getEncodedPathParameters();
}
public MultivaluedMap<String, String> getQueryParameters()
{
if (queryParameters == null)
{
queryParameters = new MultivaluedMapImpl<String, String>();
}
return queryParameters;
}
protected MultivaluedMap<String, String> getEncodedQueryParameters()
{
if (encodedQueryParameters == null)
{
this.encodedQueryParameters = new MultivaluedMapImpl<String, String>();
}
return encodedQueryParameters;
}
public MultivaluedMap<String, String> getQueryParameters(boolean decode)
{
if (decode) return getQueryParameters();
else return getEncodedQueryParameters();
}
protected void extractParameters(String queryString)
{
if (queryString == null || queryString.equals("")) return;
String[] params = queryString.split("&");
for (String param : params)
{
if (param.indexOf('=') >= 0)
{
String[] nv = param.split("=", 2);
try
{
String name = URLDecoder.decode(nv[0], "UTF-8");
String val = nv.length > 1 ? nv[1] : "";
getEncodedQueryParameters().add(name, val);
getQueryParameters().add(name, URLDecoder.decode(val, "UTF-8"));
}
catch (UnsupportedEncodingException e)
{
throw new RuntimeException(e);
}
}
else
{
try
{
String name = URLDecoder.decode(param, "UTF-8");
getEncodedQueryParameters().add(name, "");
getQueryParameters().add(name, "");
}
catch (UnsupportedEncodingException e)
{
throw new RuntimeException(e);
}
}
}
}
public List<String> getMatchedURIs(boolean decode)
{
if (decode)
{
if (matchedUris == null) matchedUris = new ArrayList<String>();
return matchedUris;
}
else
{
if (encodedMatchedUris == null) encodedMatchedUris = new ArrayList<String>();
return encodedMatchedUris;
}
}
public List<String> getMatchedURIs()
{
return getMatchedURIs(true);
}
public List<Object> getMatchedResources()
{
if (ancestors == null) ancestors = new ArrayList<Object>();
return ancestors;
}
public void pushCurrentResource(Object resource)
{
if (ancestors == null) ancestors = new ArrayList<Object>();
ancestors.add(0, resource);
}
public void pushMatchedPath(String encoded)
{
encodedMatchedPaths.add(0, encoded);
}
public List<String> getEncodedMatchedPaths()
{
return encodedMatchedPaths;
}
public void popMatchedPath()
{
encodedMatchedPaths.remove(0);
}
public void pushMatchedURI(String encoded)
{
if (encoded.endsWith("/")) encoded = encoded.substring(0, encoded.length() - 1);
if (encoded.startsWith("/")) encoded = encoded.substring(1);
String decoded = Encode.decode(encoded);
if (encodedMatchedUris == null) encodedMatchedUris = new ArrayList<String>();
encodedMatchedUris.add(0, encoded);
if (matchedUris == null) matchedUris = new ArrayList<String>();
matchedUris.add(0, decoded);
}
@Override
public URI resolve(URI uri)
{
return getBaseUri().resolve(uri);
}
@Override
public URI relativize(URI uri)
{
URI from = getRequestUri();
URI to = uri;
if (uri.getScheme() == null && uri.getHost() == null)
{
to = getBaseUriBuilder().replaceQuery(null).path(uri.getPath()).replaceQuery(uri.getQuery()).fragment(uri.getFragment()).build();
}
return ResteasyUriBuilder.relativize(from, to);
}
}
|
Java
|
package com.cabinetms.client;
import java.util.List;
import com.google.common.collect.Lists;
public class TacticMediaCommand {
private String command; // 指令
private String clientIp; // 终端IP地址
private String destination; // 终端队列地址
private Integer startDate;// 策略开始日期
private Integer endDate;// 策略结束日期
private List<TacticDetailMediaCommand> detailList = Lists.newLinkedList();
public List<TacticDetailMediaCommand> getDetailList() {
return detailList;
}
public void setDetailList(List<TacticDetailMediaCommand> detailList) {
this.detailList = detailList;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
public String getClientIp() {
return clientIp;
}
public void setClientIp(String clientIp) {
this.clientIp = clientIp;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public Integer getStartDate() {
return startDate;
}
public void setStartDate(Integer startDate) {
this.startDate = startDate;
}
public Integer getEndDate() {
return endDate;
}
public void setEndDate(Integer endDate) {
this.endDate = endDate;
}
}
|
Java
|
# Leckenbya A.C. Seward, 1894 GENUS
#### Status
ACCEPTED
#### According to
Interim Register of Marine and Nonmarine Genera
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
# Uromyces ciceris-soongaricae S. Ahmad SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Uromyces ciceris-soongaricae S. Ahmad
### Remarks
null
|
Java
|
/**
* @license Highcharts JS v7.1.1 (2019-04-09)
*
* (c) 2014-2019 Highsoft AS
* Authors: Jon Arild Nygard / Oystein Moseng
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define('highcharts/modules/treemap', ['highcharts'], function (Highcharts) {
factory(Highcharts);
factory.Highcharts = Highcharts;
return factory;
});
} else {
factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
}
}(function (Highcharts) {
var _modules = Highcharts ? Highcharts._modules : {};
function _registerModule(obj, path, args, fn) {
if (!obj.hasOwnProperty(path)) {
obj[path] = fn.apply(null, args);
}
}
_registerModule(_modules, 'mixins/tree-series.js', [_modules['parts/Globals.js']], function (H) {
var extend = H.extend,
isArray = H.isArray,
isBoolean = function (x) {
return typeof x === 'boolean';
},
isFn = function (x) {
return typeof x === 'function';
},
isObject = H.isObject,
isNumber = H.isNumber,
merge = H.merge,
pick = H.pick;
// TODO Combine buildTree and buildNode with setTreeValues
// TODO Remove logic from Treemap and make it utilize this mixin.
var setTreeValues = function setTreeValues(tree, options) {
var before = options.before,
idRoot = options.idRoot,
mapIdToNode = options.mapIdToNode,
nodeRoot = mapIdToNode[idRoot],
levelIsConstant = (
isBoolean(options.levelIsConstant) ?
options.levelIsConstant :
true
),
points = options.points,
point = points[tree.i],
optionsPoint = point && point.options || {},
childrenTotal = 0,
children = [],
value;
extend(tree, {
levelDynamic: tree.level - (levelIsConstant ? 0 : nodeRoot.level),
name: pick(point && point.name, ''),
visible: (
idRoot === tree.id ||
(isBoolean(options.visible) ? options.visible : false)
)
});
if (isFn(before)) {
tree = before(tree, options);
}
// First give the children some values
tree.children.forEach(function (child, i) {
var newOptions = extend({}, options);
extend(newOptions, {
index: i,
siblings: tree.children.length,
visible: tree.visible
});
child = setTreeValues(child, newOptions);
children.push(child);
if (child.visible) {
childrenTotal += child.val;
}
});
tree.visible = childrenTotal > 0 || tree.visible;
// Set the values
value = pick(optionsPoint.value, childrenTotal);
extend(tree, {
children: children,
childrenTotal: childrenTotal,
isLeaf: tree.visible && !childrenTotal,
val: value
});
return tree;
};
var getColor = function getColor(node, options) {
var index = options.index,
mapOptionsToLevel = options.mapOptionsToLevel,
parentColor = options.parentColor,
parentColorIndex = options.parentColorIndex,
series = options.series,
colors = options.colors,
siblings = options.siblings,
points = series.points,
getColorByPoint,
chartOptionsChart = series.chart.options.chart,
point,
level,
colorByPoint,
colorIndexByPoint,
color,
colorIndex;
function variation(color) {
var colorVariation = level && level.colorVariation;
if (colorVariation) {
if (colorVariation.key === 'brightness') {
return H.color(color).brighten(
colorVariation.to * (index / siblings)
).get();
}
}
return color;
}
if (node) {
point = points[node.i];
level = mapOptionsToLevel[node.level] || {};
getColorByPoint = point && level.colorByPoint;
if (getColorByPoint) {
colorIndexByPoint = point.index % (colors ?
colors.length :
chartOptionsChart.colorCount
);
colorByPoint = colors && colors[colorIndexByPoint];
}
// Select either point color, level color or inherited color.
if (!series.chart.styledMode) {
color = pick(
point && point.options.color,
level && level.color,
colorByPoint,
parentColor && variation(parentColor),
series.color
);
}
colorIndex = pick(
point && point.options.colorIndex,
level && level.colorIndex,
colorIndexByPoint,
parentColorIndex,
options.colorIndex
);
}
return {
color: color,
colorIndex: colorIndex
};
};
/**
* Creates a map from level number to its given options.
*
* @private
* @function getLevelOptions
*
* @param {object} params
* Object containing parameters.
* - `defaults` Object containing default options. The default options
* are merged with the userOptions to get the final options for a
* specific level.
* - `from` The lowest level number.
* - `levels` User options from series.levels.
* - `to` The highest level number.
*
* @return {Highcharts.Dictionary<object>}
* Returns a map from level number to its given options.
*/
var getLevelOptions = function getLevelOptions(params) {
var result = null,
defaults,
converted,
i,
from,
to,
levels;
if (isObject(params)) {
result = {};
from = isNumber(params.from) ? params.from : 1;
levels = params.levels;
converted = {};
defaults = isObject(params.defaults) ? params.defaults : {};
if (isArray(levels)) {
converted = levels.reduce(function (obj, item) {
var level,
levelIsConstant,
options;
if (isObject(item) && isNumber(item.level)) {
options = merge({}, item);
levelIsConstant = (
isBoolean(options.levelIsConstant) ?
options.levelIsConstant :
defaults.levelIsConstant
);
// Delete redundant properties.
delete options.levelIsConstant;
delete options.level;
// Calculate which level these options apply to.
level = item.level + (levelIsConstant ? 0 : from - 1);
if (isObject(obj[level])) {
extend(obj[level], options);
} else {
obj[level] = options;
}
}
return obj;
}, {});
}
to = isNumber(params.to) ? params.to : 1;
for (i = 0; i <= to; i++) {
result[i] = merge(
{},
defaults,
isObject(converted[i]) ? converted[i] : {}
);
}
}
return result;
};
/**
* Update the rootId property on the series. Also makes sure that it is
* accessible to exporting.
*
* @private
* @function updateRootId
*
* @param {object} series
* The series to operate on.
*
* @return {string}
* Returns the resulting rootId after update.
*/
var updateRootId = function (series) {
var rootId,
options;
if (isObject(series)) {
// Get the series options.
options = isObject(series.options) ? series.options : {};
// Calculate the rootId.
rootId = pick(series.rootNode, options.rootId, '');
// Set rootId on series.userOptions to pick it up in exporting.
if (isObject(series.userOptions)) {
series.userOptions.rootId = rootId;
}
// Set rootId on series to pick it up on next update.
series.rootNode = rootId;
}
return rootId;
};
var result = {
getColor: getColor,
getLevelOptions: getLevelOptions,
setTreeValues: setTreeValues,
updateRootId: updateRootId
};
return result;
});
_registerModule(_modules, 'mixins/draw-point.js', [], function () {
var isFn = function (x) {
return typeof x === 'function';
};
/**
* Handles the drawing of a component.
* Can be used for any type of component that reserves the graphic property, and
* provides a shouldDraw on its context.
*
* @private
* @function draw
*
* @param {object} params
* Parameters.
*
* TODO: add type checking.
* TODO: export this function to enable usage
*/
var draw = function draw(params) {
var component = this,
graphic = component.graphic,
animatableAttribs = params.animatableAttribs,
onComplete = params.onComplete,
css = params.css,
renderer = params.renderer;
if (component.shouldDraw()) {
if (!graphic) {
component.graphic = graphic =
renderer[params.shapeType](params.shapeArgs).add(params.group);
}
graphic
.css(css)
.attr(params.attribs)
.animate(
animatableAttribs,
params.isNew ? false : undefined,
onComplete
);
} else if (graphic) {
var destroy = function () {
component.graphic = graphic = graphic.destroy();
if (isFn(onComplete)) {
onComplete();
}
};
// animate only runs complete callback if something was animated.
if (Object.keys(animatableAttribs).length) {
graphic.animate(animatableAttribs, undefined, function () {
destroy();
});
} else {
destroy();
}
}
};
/**
* An extended version of draw customized for points.
* It calls additional methods that is expected when rendering a point.
*
* @param {object} params Parameters
*/
var drawPoint = function drawPoint(params) {
var point = this,
attribs = params.attribs = params.attribs || {};
// Assigning class in dot notation does go well in IE8
// eslint-disable-next-line dot-notation
attribs['class'] = point.getClassName();
// Call draw to render component
draw.call(point, params);
};
return drawPoint;
});
_registerModule(_modules, 'modules/treemap.src.js', [_modules['parts/Globals.js'], _modules['mixins/tree-series.js'], _modules['mixins/draw-point.js']], function (H, mixinTreeSeries, drawPoint) {
/* *
* (c) 2014-2019 Highsoft AS
*
* Authors: Jon Arild Nygard / Oystein Moseng
*
* License: www.highcharts.com/license
*/
var seriesType = H.seriesType,
seriesTypes = H.seriesTypes,
addEvent = H.addEvent,
merge = H.merge,
extend = H.extend,
error = H.error,
defined = H.defined,
noop = H.noop,
fireEvent = H.fireEvent,
getColor = mixinTreeSeries.getColor,
getLevelOptions = mixinTreeSeries.getLevelOptions,
isArray = H.isArray,
isBoolean = function (x) {
return typeof x === 'boolean';
},
isNumber = H.isNumber,
isObject = H.isObject,
isString = H.isString,
pick = H.pick,
Series = H.Series,
stableSort = H.stableSort,
color = H.Color,
eachObject = function (list, func, context) {
context = context || this;
H.objectEach(list, function (val, key) {
func.call(context, val, key, list);
});
},
// @todo find correct name for this function.
// @todo Similar to reduce, this function is likely redundant
recursive = function (item, func, context) {
var next;
context = context || this;
next = func.call(context, item);
if (next !== false) {
recursive(next, func, context);
}
},
updateRootId = mixinTreeSeries.updateRootId;
/**
* @private
* @class
* @name Highcharts.seriesTypes.treemap
*
* @augments Highcharts.Series
*/
seriesType(
'treemap',
'scatter'
/**
* A treemap displays hierarchical data using nested rectangles. The data
* can be laid out in varying ways depending on options.
*
* @sample highcharts/demo/treemap-large-dataset/
* Treemap
*
* @extends plotOptions.scatter
* @excluding marker, jitter
* @product highcharts
* @optionparent plotOptions.treemap
*/
, {
/**
* When enabled the user can click on a point which is a parent and
* zoom in on its children. Deprecated and replaced by
* [allowTraversingTree](#plotOptions.treemap.allowTraversingTree).
*
* @sample {highcharts} highcharts/plotoptions/treemap-allowdrilltonode/
* Enabled
*
* @deprecated
* @type {boolean}
* @default false
* @since 4.1.0
* @product highcharts
* @apioption plotOptions.treemap.allowDrillToNode
*/
/**
* When enabled the user can click on a point which is a parent and
* zoom in on its children.
*
* @sample {highcharts} highcharts/plotoptions/treemap-allowtraversingtree/
* Enabled
*
* @since 7.0.3
* @product highcharts
*/
allowTraversingTree: false,
animationLimit: 250,
/**
* When the series contains less points than the crop threshold, all
* points are drawn, event if the points fall outside the visible plot
* area at the current zoom. The advantage of drawing all points
* (including markers and columns), is that animation is performed on
* updates. On the other hand, when the series contains more points than
* the crop threshold, the series data is cropped to only contain points
* that fall within the plot area. The advantage of cropping away
* invisible points is to increase performance on large series.
*
* @type {number}
* @default 300
* @since 4.1.0
* @product highcharts
* @apioption plotOptions.treemap.cropThreshold
*/
/**
* Fires on a request for change of root node for the tree, before the
* update is made. An event object is passed to the function, containing
* additional properties `newRootId`, `previousRootId`, `redraw` and
* `trigger`.
*
* @type {function}
* @default undefined
* @sample {highcharts} highcharts/plotoptions/treemap-events-setrootnode/
* Alert update information on setRootNode event.
* @since 7.0.3
* @product highcharts
* @apioption plotOptions.treemap.events.setRootNode
*/
/**
* This option decides if the user can interact with the parent nodes
* or just the leaf nodes. When this option is undefined, it will be
* true by default. However when allowTraversingTree is true, then it
* will be false by default.
*
* @sample {highcharts} highcharts/plotoptions/treemap-interactbyleaf-false/
* False
* @sample {highcharts} highcharts/plotoptions/treemap-interactbyleaf-true-and-allowtraversingtree/
* InteractByLeaf and allowTraversingTree is true
*
* @type {boolean}
* @since 4.1.2
* @product highcharts
* @apioption plotOptions.treemap.interactByLeaf
*/
/**
* The sort index of the point inside the treemap level.
*
* @sample {highcharts} highcharts/plotoptions/treemap-sortindex/
* Sort by years
*
* @type {number}
* @since 4.1.10
* @product highcharts
* @apioption plotOptions.treemap.sortIndex
*/
/**
* When using automatic point colors pulled from the `options.colors`
* collection, this option determines whether the chart should receive
* one color per series or one color per point.
*
* @see [series colors](#plotOptions.treemap.colors)
*
* @type {boolean}
* @default false
* @since 2.0
* @product highcharts
* @apioption plotOptions.treemap.colorByPoint
*/
/**
* A series specific or series type specific color set to apply instead
* of the global [colors](#colors) when
* [colorByPoint](#plotOptions.treemap.colorByPoint) is true.
*
* @type {Array<Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject>}
* @since 3.0
* @product highcharts
* @apioption plotOptions.treemap.colors
*/
/**
* Whether to display this series type or specific series item in the
* legend.
*/
showInLegend: false,
/**
* @ignore-option
*/
marker: false,
colorByPoint: false,
/**
* @since 4.1.0
*/
dataLabels: {
/** @ignore-option */
defer: false,
/** @ignore-option */
enabled: true,
/** @ignore-option */
formatter: function () {
var point = this && this.point ? this.point : {},
name = isString(point.name) ? point.name : '';
return name;
},
/** @ignore-option */
inside: true,
/** @ignore-option */
verticalAlign: 'middle'
},
tooltip: {
headerFormat: '',
pointFormat: '<b>{point.name}</b>: {point.value}<br/>'
},
/**
* Whether to ignore hidden points when the layout algorithm runs.
* If `false`, hidden points will leave open spaces.
*
* @since 5.0.8
*/
ignoreHiddenPoint: true,
/**
* This option decides which algorithm is used for setting position
* and dimensions of the points.
*
* @see [How to write your own algorithm](https://www.highcharts.com/docs/chart-and-series-types/treemap)
*
* @sample {highcharts} highcharts/plotoptions/treemap-layoutalgorithm-sliceanddice/
* SliceAndDice by default
* @sample {highcharts} highcharts/plotoptions/treemap-layoutalgorithm-stripes/
* Stripes
* @sample {highcharts} highcharts/plotoptions/treemap-layoutalgorithm-squarified/
* Squarified
* @sample {highcharts} highcharts/plotoptions/treemap-layoutalgorithm-strip/
* Strip
*
* @since 4.1.0
* @validvalue ["sliceAndDice", "stripes", "squarified", "strip"]
*/
layoutAlgorithm: 'sliceAndDice',
/**
* Defines which direction the layout algorithm will start drawing.
*
* @since 4.1.0
* @validvalue ["vertical", "horizontal"]
*/
layoutStartingDirection: 'vertical',
/**
* Enabling this option will make the treemap alternate the drawing
* direction between vertical and horizontal. The next levels starting
* direction will always be the opposite of the previous.
*
* @sample {highcharts} highcharts/plotoptions/treemap-alternatestartingdirection-true/
* Enabled
*
* @since 4.1.0
*/
alternateStartingDirection: false,
/**
* Used together with the levels and allowTraversingTree options. When
* set to false the first level visible to be level one, which is
* dynamic when traversing the tree. Otherwise the level will be the
* same as the tree structure.
*
* @since 4.1.0
*/
levelIsConstant: true,
/**
* Options for the button appearing when drilling down in a treemap.
* Deprecated and replaced by
* [traverseUpButton](#plotOptions.treemap.traverseUpButton).
*
* @deprecated
*/
drillUpButton: {
/**
* The position of the button.
*
* @deprecated
*/
position: {
/**
* Vertical alignment of the button.
*
* @deprecated
* @type {Highcharts.VerticalAlignValue}
* @default top
* @product highcharts
* @apioption plotOptions.treemap.drillUpButton.position.verticalAlign
*/
/**
* Horizontal alignment of the button.
*
* @deprecated
* @type {Highcharts.AlignValue}
*/
align: 'right',
/**
* Horizontal offset of the button.
*
* @deprecated
*/
x: -10,
/**
* Vertical offset of the button.
*
* @deprecated
*/
y: 10
}
},
/**
* Options for the button appearing when traversing down in a treemap.
*/
traverseUpButton: {
/**
* The position of the button.
*/
position: {
/**
* Vertical alignment of the button.
*
* @type {Highcharts.VerticalAlignValue}
* @default top
* @product highcharts
* @apioption plotOptions.treemap.traverseUpButton.position.verticalAlign
*/
/**
* Horizontal alignment of the button.
*
* @type {Highcharts.AlignValue}
*/
align: 'right',
/**
* Horizontal offset of the button.
*/
x: -10,
/**
* Vertical offset of the button.
*/
y: 10
}
},
/**
* Set options on specific levels. Takes precedence over series options,
* but not point options.
*
* @sample {highcharts} highcharts/plotoptions/treemap-levels/
* Styling dataLabels and borders
* @sample {highcharts} highcharts/demo/treemap-with-levels/
* Different layoutAlgorithm
*
* @type {Array<*>}
* @since 4.1.0
* @product highcharts
* @apioption plotOptions.treemap.levels
*/
/**
* Can set a `borderColor` on all points which lies on the same level.
*
* @type {Highcharts.ColorString}
* @since 4.1.0
* @product highcharts
* @apioption plotOptions.treemap.levels.borderColor
*/
/**
* Set the dash style of the border of all the point which lies on the
* level. See <a href"#plotoptions.scatter.dashstyle">
* plotOptions.scatter.dashStyle</a> for possible options.
*
* @type {string}
* @since 4.1.0
* @product highcharts
* @apioption plotOptions.treemap.levels.borderDashStyle
*/
/**
* Can set the borderWidth on all points which lies on the same level.
*
* @type {number}
* @since 4.1.0
* @product highcharts
* @apioption plotOptions.treemap.levels.borderWidth
*/
/**
* Can set a color on all points which lies on the same level.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @since 4.1.0
* @product highcharts
* @apioption plotOptions.treemap.levels.color
*/
/**
* A configuration object to define how the color of a child varies from
* the parent's color. The variation is distributed among the children
* of node. For example when setting brightness, the brightness change
* will range from the parent's original brightness on the first child,
* to the amount set in the `to` setting on the last node. This allows a
* gradient-like color scheme that sets children out from each other
* while highlighting the grouping on treemaps and sectors on sunburst
* charts.
*
* @sample highcharts/demo/sunburst/
* Sunburst with color variation
*
* @since 6.0.0
* @product highcharts
* @apioption plotOptions.treemap.levels.colorVariation
*/
/**
* The key of a color variation. Currently supports `brightness` only.
*
* @type {string}
* @since 6.0.0
* @product highcharts
* @validvalue ["brightness"]
* @apioption plotOptions.treemap.levels.colorVariation.key
*/
/**
* The ending value of a color variation. The last sibling will receive
* this value.
*
* @type {number}
* @since 6.0.0
* @product highcharts
* @apioption plotOptions.treemap.levels.colorVariation.to
*/
/**
* Can set the options of dataLabels on each point which lies on the
* level.
* [plotOptions.treemap.dataLabels](#plotOptions.treemap.dataLabels) for
* possible values.
*
* @type {object}
* @since 4.1.0
* @product highcharts
* @apioption plotOptions.treemap.levels.dataLabels
*/
/**
* Can set the layoutAlgorithm option on a specific level.
*
* @type {string}
* @since 4.1.0
* @product highcharts
* @validvalue ["sliceAndDice", "stripes", "squarified", "strip"]
* @apioption plotOptions.treemap.levels.layoutAlgorithm
*/
/**
* Can set the layoutStartingDirection option on a specific level.
*
* @type {string}
* @since 4.1.0
* @product highcharts
* @validvalue ["vertical", "horizontal"]
* @apioption plotOptions.treemap.levels.layoutStartingDirection
*/
/**
* Decides which level takes effect from the options set in the levels
* object.
*
* @sample {highcharts} highcharts/plotoptions/treemap-levels/
* Styling of both levels
*
* @type {number}
* @since 4.1.0
* @product highcharts
* @apioption plotOptions.treemap.levels.level
*/
// Presentational options
/**
* The color of the border surrounding each tree map item.
*
* @type {Highcharts.ColorString}
*/
borderColor: '#e6e6e6',
/**
* The width of the border surrounding each tree map item.
*/
borderWidth: 1,
/**
* The opacity of a point in treemap. When a point has children, the
* visibility of the children is determined by the opacity.
*
* @since 4.2.4
*/
opacity: 0.15,
/**
* A wrapper object for all the series options in specific states.
*
* @extends plotOptions.heatmap.states
*/
states: {
/**
* Options for the hovered series
*
* @extends plotOptions.heatmap.states.hover
* @excluding halo
*/
hover: {
/**
* The border color for the hovered state.
*/
borderColor: '#999999',
/**
* Brightness for the hovered point. Defaults to 0 if the
* heatmap series is loaded first, otherwise 0.1.
*
* @type {number}
* @default undefined
*/
brightness: seriesTypes.heatmap ? 0 : 0.1,
/**
* @extends plotOptions.heatmap.states.hover.halo
*/
halo: false,
/**
* The opacity of a point in treemap. When a point has children,
* the visibility of the children is determined by the opacity.
*
* @since 4.2.4
*/
opacity: 0.75,
/**
* The shadow option for hovered state.
*/
shadow: false
}
}
// Prototype members
}, {
pointArrayMap: ['value'],
directTouch: true,
optionalAxis: 'colorAxis',
getSymbol: noop,
parallelArrays: ['x', 'y', 'value', 'colorValue'],
colorKey: 'colorValue', // Point color option key
trackerGroups: ['group', 'dataLabelsGroup'],
/**
* Creates an object map from parent id to childrens index.
*
* @private
* @function Highcharts.Series#getListOfParents
*
* @param {Highcharts.SeriesTreemapDataOptions} data
* List of points set in options.
*
* @param {Array<string>} existingIds
* List of all point ids.
*
* @return {object}
* Map from parent id to children index in data.
*/
getListOfParents: function (data, existingIds) {
var arr = isArray(data) ? data : [],
ids = isArray(existingIds) ? existingIds : [],
listOfParents = arr.reduce(function (prev, curr, i) {
var parent = pick(curr.parent, '');
if (prev[parent] === undefined) {
prev[parent] = [];
}
prev[parent].push(i);
return prev;
}, {
'': [] // Root of tree
});
// If parent does not exist, hoist parent to root of tree.
eachObject(listOfParents, function (children, parent, list) {
if ((parent !== '') && (ids.indexOf(parent) === -1)) {
children.forEach(function (child) {
list[''].push(child);
});
delete list[parent];
}
});
return listOfParents;
},
// Creates a tree structured object from the series points
getTree: function () {
var series = this,
allIds = this.data.map(function (d) {
return d.id;
}),
parentList = series.getListOfParents(this.data, allIds);
series.nodeMap = [];
return series.buildNode('', -1, 0, parentList, null);
},
// Define hasData function for non-cartesian series.
// Returns true if the series has points at all.
hasData: function () {
return !!this.processedXData.length; // != 0
},
init: function (chart, options) {
var series = this,
colorSeriesMixin = H.colorSeriesMixin;
// If color series logic is loaded, add some properties
if (H.colorSeriesMixin) {
this.translateColors = colorSeriesMixin.translateColors;
this.colorAttribs = colorSeriesMixin.colorAttribs;
this.axisTypes = colorSeriesMixin.axisTypes;
}
// Handle deprecated options.
addEvent(series, 'setOptions', function (event) {
var options = event.userOptions;
if (
defined(options.allowDrillToNode) &&
!defined(options.allowTraversingTree)
) {
options.allowTraversingTree = options.allowDrillToNode;
delete options.allowDrillToNode;
}
if (
defined(options.drillUpButton) &&
!defined(options.traverseUpButton)
) {
options.traverseUpButton = options.drillUpButton;
delete options.drillUpButton;
}
});
Series.prototype.init.call(series, chart, options);
if (series.options.allowTraversingTree) {
addEvent(series, 'click', series.onClickDrillToNode);
}
},
buildNode: function (id, i, level, list, parent) {
var series = this,
children = [],
point = series.points[i],
height = 0,
node,
child;
// Actions
((list[id] || [])).forEach(function (i) {
child = series.buildNode(
series.points[i].id,
i,
(level + 1),
list,
id
);
height = Math.max(child.height + 1, height);
children.push(child);
});
node = {
id: id,
i: i,
children: children,
height: height,
level: level,
parent: parent,
visible: false // @todo move this to better location
};
series.nodeMap[node.id] = node;
if (point) {
point.node = node;
}
return node;
},
setTreeValues: function (tree) {
var series = this,
options = series.options,
idRoot = series.rootNode,
mapIdToNode = series.nodeMap,
nodeRoot = mapIdToNode[idRoot],
levelIsConstant = (
isBoolean(options.levelIsConstant) ?
options.levelIsConstant :
true
),
childrenTotal = 0,
children = [],
val,
point = series.points[tree.i];
// First give the children some values
tree.children.forEach(function (child) {
child = series.setTreeValues(child);
children.push(child);
if (!child.ignore) {
childrenTotal += child.val;
}
});
// Sort the children
stableSort(children, function (a, b) {
return a.sortIndex - b.sortIndex;
});
// Set the values
val = pick(point && point.options.value, childrenTotal);
if (point) {
point.value = val;
}
extend(tree, {
children: children,
childrenTotal: childrenTotal,
// Ignore this node if point is not visible
ignore: !(pick(point && point.visible, true) && (val > 0)),
isLeaf: tree.visible && !childrenTotal,
levelDynamic: (
tree.level - (levelIsConstant ? 0 : nodeRoot.level)
),
name: pick(point && point.name, ''),
sortIndex: pick(point && point.sortIndex, -val),
val: val
});
return tree;
},
/**
* Recursive function which calculates the area for all children of a
* node.
*
* @private
* @function Highcharts.Series#calculateChildrenAreas
*
* @param {object} node
* The node which is parent to the children.
*
* @param {object} area
* The rectangular area of the parent.
*/
calculateChildrenAreas: function (parent, area) {
var series = this,
options = series.options,
mapOptionsToLevel = series.mapOptionsToLevel,
level = mapOptionsToLevel[parent.level + 1],
algorithm = pick(
(
series[level &&
level.layoutAlgorithm] &&
level.layoutAlgorithm
),
options.layoutAlgorithm
),
alternate = options.alternateStartingDirection,
childrenValues = [],
children;
// Collect all children which should be included
children = parent.children.filter(function (n) {
return !n.ignore;
});
if (level && level.layoutStartingDirection) {
area.direction = level.layoutStartingDirection === 'vertical' ?
0 :
1;
}
childrenValues = series[algorithm](area, children);
children.forEach(function (child, index) {
var values = childrenValues[index];
child.values = merge(values, {
val: child.childrenTotal,
direction: (alternate ? 1 - area.direction : area.direction)
});
child.pointValues = merge(values, {
x: (values.x / series.axisRatio),
width: (values.width / series.axisRatio)
});
// If node has children, then call method recursively
if (child.children.length) {
series.calculateChildrenAreas(child, child.values);
}
});
},
setPointValues: function () {
var series = this,
xAxis = series.xAxis,
yAxis = series.yAxis;
series.points.forEach(function (point) {
var node = point.node,
values = node.pointValues,
x1,
x2,
y1,
y2,
crispCorr = 0;
// Get the crisp correction in classic mode. For this to work in
// styled mode, we would need to first add the shape (without x,
// y, width and height), then read the rendered stroke width
// using point.graphic.strokeWidth(), then modify and apply the
// shapeArgs. This applies also to column series, but the
// downside is performance and code complexity.
if (!series.chart.styledMode) {
crispCorr = (
(series.pointAttribs(point)['stroke-width'] || 0) % 2
) / 2;
}
// Points which is ignored, have no values.
if (values && node.visible) {
x1 = Math.round(
xAxis.translate(values.x, 0, 0, 0, 1)
) - crispCorr;
x2 = Math.round(
xAxis.translate(values.x + values.width, 0, 0, 0, 1)
) - crispCorr;
y1 = Math.round(
yAxis.translate(values.y, 0, 0, 0, 1)
) - crispCorr;
y2 = Math.round(
yAxis.translate(values.y + values.height, 0, 0, 0, 1)
) - crispCorr;
// Set point values
point.shapeArgs = {
x: Math.min(x1, x2),
y: Math.min(y1, y2),
width: Math.abs(x2 - x1),
height: Math.abs(y2 - y1)
};
point.plotX =
point.shapeArgs.x + (point.shapeArgs.width / 2);
point.plotY =
point.shapeArgs.y + (point.shapeArgs.height / 2);
} else {
// Reset visibility
delete point.plotX;
delete point.plotY;
}
});
},
// Set the node's color recursively, from the parent down.
setColorRecursive: function (
node,
parentColor,
colorIndex,
index,
siblings
) {
var series = this,
chart = series && series.chart,
colors = chart && chart.options && chart.options.colors,
colorInfo,
point;
if (node) {
colorInfo = getColor(node, {
colors: colors,
index: index,
mapOptionsToLevel: series.mapOptionsToLevel,
parentColor: parentColor,
parentColorIndex: colorIndex,
series: series,
siblings: siblings
});
point = series.points[node.i];
if (point) {
point.color = colorInfo.color;
point.colorIndex = colorInfo.colorIndex;
}
// Do it all again with the children
(node.children || []).forEach(function (child, i) {
series.setColorRecursive(
child,
colorInfo.color,
colorInfo.colorIndex,
i,
node.children.length
);
});
}
},
algorithmGroup: function (h, w, d, p) {
this.height = h;
this.width = w;
this.plot = p;
this.direction = d;
this.startDirection = d;
this.total = 0;
this.nW = 0;
this.lW = 0;
this.nH = 0;
this.lH = 0;
this.elArr = [];
this.lP = {
total: 0,
lH: 0,
nH: 0,
lW: 0,
nW: 0,
nR: 0,
lR: 0,
aspectRatio: function (w, h) {
return Math.max((w / h), (h / w));
}
};
this.addElement = function (el) {
this.lP.total = this.elArr[this.elArr.length - 1];
this.total = this.total + el;
if (this.direction === 0) {
// Calculate last point old aspect ratio
this.lW = this.nW;
this.lP.lH = this.lP.total / this.lW;
this.lP.lR = this.lP.aspectRatio(this.lW, this.lP.lH);
// Calculate last point new aspect ratio
this.nW = this.total / this.height;
this.lP.nH = this.lP.total / this.nW;
this.lP.nR = this.lP.aspectRatio(this.nW, this.lP.nH);
} else {
// Calculate last point old aspect ratio
this.lH = this.nH;
this.lP.lW = this.lP.total / this.lH;
this.lP.lR = this.lP.aspectRatio(this.lP.lW, this.lH);
// Calculate last point new aspect ratio
this.nH = this.total / this.width;
this.lP.nW = this.lP.total / this.nH;
this.lP.nR = this.lP.aspectRatio(this.lP.nW, this.nH);
}
this.elArr.push(el);
};
this.reset = function () {
this.nW = 0;
this.lW = 0;
this.elArr = [];
this.total = 0;
};
},
algorithmCalcPoints: function (
directionChange, last, group, childrenArea
) {
var pX,
pY,
pW,
pH,
gW = group.lW,
gH = group.lH,
plot = group.plot,
keep,
i = 0,
end = group.elArr.length - 1;
if (last) {
gW = group.nW;
gH = group.nH;
} else {
keep = group.elArr[group.elArr.length - 1];
}
group.elArr.forEach(function (p) {
if (last || (i < end)) {
if (group.direction === 0) {
pX = plot.x;
pY = plot.y;
pW = gW;
pH = p / pW;
} else {
pX = plot.x;
pY = plot.y;
pH = gH;
pW = p / pH;
}
childrenArea.push({
x: pX,
y: pY,
width: pW,
height: H.correctFloat(pH)
});
if (group.direction === 0) {
plot.y = plot.y + pH;
} else {
plot.x = plot.x + pW;
}
}
i = i + 1;
});
// Reset variables
group.reset();
if (group.direction === 0) {
group.width = group.width - gW;
} else {
group.height = group.height - gH;
}
plot.y = plot.parent.y + (plot.parent.height - group.height);
plot.x = plot.parent.x + (plot.parent.width - group.width);
if (directionChange) {
group.direction = 1 - group.direction;
}
// If not last, then add uncalculated element
if (!last) {
group.addElement(keep);
}
},
algorithmLowAspectRatio: function (directionChange, parent, children) {
var childrenArea = [],
series = this,
pTot,
plot = {
x: parent.x,
y: parent.y,
parent: parent
},
direction = parent.direction,
i = 0,
end = children.length - 1,
group = new this.algorithmGroup( // eslint-disable-line new-cap
parent.height,
parent.width,
direction,
plot
);
// Loop through and calculate all areas
children.forEach(function (child) {
pTot =
(parent.width * parent.height) * (child.val / parent.val);
group.addElement(pTot);
if (group.lP.nR > group.lP.lR) {
series.algorithmCalcPoints(
directionChange,
false,
group,
childrenArea,
plot
);
}
// If last child, then calculate all remaining areas
if (i === end) {
series.algorithmCalcPoints(
directionChange,
true,
group,
childrenArea,
plot
);
}
i = i + 1;
});
return childrenArea;
},
algorithmFill: function (directionChange, parent, children) {
var childrenArea = [],
pTot,
direction = parent.direction,
x = parent.x,
y = parent.y,
width = parent.width,
height = parent.height,
pX,
pY,
pW,
pH;
children.forEach(function (child) {
pTot =
(parent.width * parent.height) * (child.val / parent.val);
pX = x;
pY = y;
if (direction === 0) {
pH = height;
pW = pTot / pH;
width = width - pW;
x = x + pW;
} else {
pW = width;
pH = pTot / pW;
height = height - pH;
y = y + pH;
}
childrenArea.push({
x: pX,
y: pY,
width: pW,
height: pH
});
if (directionChange) {
direction = 1 - direction;
}
});
return childrenArea;
},
strip: function (parent, children) {
return this.algorithmLowAspectRatio(false, parent, children);
},
squarified: function (parent, children) {
return this.algorithmLowAspectRatio(true, parent, children);
},
sliceAndDice: function (parent, children) {
return this.algorithmFill(true, parent, children);
},
stripes: function (parent, children) {
return this.algorithmFill(false, parent, children);
},
translate: function () {
var series = this,
options = series.options,
// NOTE: updateRootId modifies series.
rootId = updateRootId(series),
rootNode,
pointValues,
seriesArea,
tree,
val;
// Call prototype function
Series.prototype.translate.call(series);
// @todo Only if series.isDirtyData is true
tree = series.tree = series.getTree();
rootNode = series.nodeMap[rootId];
series.renderTraverseUpButton(rootId);
series.mapOptionsToLevel = getLevelOptions({
from: rootNode.level + 1,
levels: options.levels,
to: tree.height,
defaults: {
levelIsConstant: series.options.levelIsConstant,
colorByPoint: options.colorByPoint
}
});
if (
rootId !== '' &&
(!rootNode || !rootNode.children.length)
) {
series.setRootNode('', false);
rootId = series.rootNode;
rootNode = series.nodeMap[rootId];
}
// Parents of the root node is by default visible
recursive(series.nodeMap[series.rootNode], function (node) {
var next = false,
p = node.parent;
node.visible = true;
if (p || p === '') {
next = series.nodeMap[p];
}
return next;
});
// Children of the root node is by default visible
recursive(
series.nodeMap[series.rootNode].children,
function (children) {
var next = false;
children.forEach(function (child) {
child.visible = true;
if (child.children.length) {
next = (next || []).concat(child.children);
}
});
return next;
}
);
series.setTreeValues(tree);
// Calculate plotting values.
series.axisRatio = (series.xAxis.len / series.yAxis.len);
series.nodeMap[''].pointValues = pointValues =
{ x: 0, y: 0, width: 100, height: 100 };
series.nodeMap[''].values = seriesArea = merge(pointValues, {
width: (pointValues.width * series.axisRatio),
direction: (
options.layoutStartingDirection === 'vertical' ? 0 : 1
),
val: tree.val
});
series.calculateChildrenAreas(tree, seriesArea);
// Logic for point colors
if (series.colorAxis) {
series.translateColors();
} else if (!options.colorByPoint) {
series.setColorRecursive(series.tree);
}
// Update axis extremes according to the root node.
if (options.allowTraversingTree) {
val = rootNode.pointValues;
series.xAxis.setExtremes(val.x, val.x + val.width, false);
series.yAxis.setExtremes(val.y, val.y + val.height, false);
series.xAxis.setScale();
series.yAxis.setScale();
}
// Assign values to points.
series.setPointValues();
},
/**
* Extend drawDataLabels with logic to handle custom options related to
* the treemap series:
*
* - Points which is not a leaf node, has dataLabels disabled by
* default.
*
* - Options set on series.levels is merged in.
*
* - Width of the dataLabel is set to match the width of the point
* shape.
*
* @private
* @function Highcharts.Series#drawDataLabels
*/
drawDataLabels: function () {
var series = this,
mapOptionsToLevel = series.mapOptionsToLevel,
points = series.points.filter(function (n) {
return n.node.visible;
}),
options,
level;
points.forEach(function (point) {
level = mapOptionsToLevel[point.node.level];
// Set options to new object to avoid problems with scope
options = { style: {} };
// If not a leaf, then label should be disabled as default
if (!point.node.isLeaf) {
options.enabled = false;
}
// If options for level exists, include them as well
if (level && level.dataLabels) {
options = merge(options, level.dataLabels);
series._hasPointLabels = true;
}
// Set dataLabel width to the width of the point shape.
if (point.shapeArgs) {
options.style.width = point.shapeArgs.width;
if (point.dataLabel) {
point.dataLabel.css({
width: point.shapeArgs.width + 'px'
});
}
}
// Merge custom options with point options
point.dlOptions = merge(options, point.options.dataLabels);
});
Series.prototype.drawDataLabels.call(this);
},
// Over the alignment method by setting z index
alignDataLabel: function (point, dataLabel, labelOptions) {
var style = labelOptions.style;
// #8160: Prevent the label from exceeding the point's
// boundaries in treemaps by applying ellipsis overflow.
// The issue was happening when datalabel's text contained a
// long sequence of characters without a whitespace.
if (
!H.defined(style.textOverflow) &&
dataLabel.text &&
dataLabel.getBBox().width > dataLabel.text.textWidth
) {
dataLabel.css({
textOverflow: 'ellipsis',
// unit (px) is required when useHTML is true
width: style.width += 'px'
});
}
seriesTypes.column.prototype.alignDataLabel.apply(this, arguments);
if (point.dataLabel) {
// point.node.zIndex could be undefined (#6956)
point.dataLabel.attr({ zIndex: (point.node.zIndex || 0) + 1 });
}
},
// Get presentational attributes
pointAttribs: function (point, state) {
var series = this,
mapOptionsToLevel = (
isObject(series.mapOptionsToLevel) ?
series.mapOptionsToLevel :
{}
),
level = point && mapOptionsToLevel[point.node.level] || {},
options = this.options,
attr,
stateOptions = (state && options.states[state]) || {},
className = (point && point.getClassName()) || '',
opacity;
// Set attributes by precedence. Point trumps level trumps series.
// Stroke width uses pick because it can be 0.
attr = {
'stroke':
(point && point.borderColor) ||
level.borderColor ||
stateOptions.borderColor ||
options.borderColor,
'stroke-width': pick(
point && point.borderWidth,
level.borderWidth,
stateOptions.borderWidth,
options.borderWidth
),
'dashstyle':
(point && point.borderDashStyle) ||
level.borderDashStyle ||
stateOptions.borderDashStyle ||
options.borderDashStyle,
'fill': (point && point.color) || this.color
};
// Hide levels above the current view
if (className.indexOf('highcharts-above-level') !== -1) {
attr.fill = 'none';
attr['stroke-width'] = 0;
// Nodes with children that accept interaction
} else if (
className.indexOf('highcharts-internal-node-interactive') !== -1
) {
opacity = pick(stateOptions.opacity, options.opacity);
attr.fill = color(attr.fill).setOpacity(opacity).get();
attr.cursor = 'pointer';
// Hide nodes that have children
} else if (className.indexOf('highcharts-internal-node') !== -1) {
attr.fill = 'none';
} else if (state) {
// Brighten and hoist the hover nodes
attr.fill = color(attr.fill)
.brighten(stateOptions.brightness)
.get();
}
return attr;
},
// Override drawPoints
drawPoints: function () {
var series = this,
chart = series.chart,
renderer = chart.renderer,
points = series.points,
styledMode = chart.styledMode,
options = series.options,
shadow = styledMode ? {} : options.shadow,
borderRadius = options.borderRadius,
withinAnimationLimit =
chart.pointCount < options.animationLimit,
allowTraversingTree = options.allowTraversingTree;
points.forEach(function (point) {
var levelDynamic = point.node.levelDynamic,
animate = {},
attr = {},
css = {},
groupKey = 'level-group-' + levelDynamic,
hasGraphic = !!point.graphic,
shouldAnimate = withinAnimationLimit && hasGraphic,
shapeArgs = point.shapeArgs;
// Don't bother with calculate styling if the point is not drawn
if (point.shouldDraw()) {
if (borderRadius) {
attr.r = borderRadius;
}
merge(
true, // Extend object
// Which object to extend
shouldAnimate ? animate : attr,
// Add shapeArgs to animate/attr if graphic exists
hasGraphic ? shapeArgs : {},
// Add style attribs if !styleMode
styledMode ?
{} :
series.pointAttribs(
point, point.selected && 'select'
)
);
// In styled mode apply point.color. Use CSS, otherwise the
// fill used in the style sheet will take precedence over
// the fill attribute.
if (series.colorAttribs && styledMode) {
// Heatmap is loaded
extend(css, series.colorAttribs(point));
}
if (!series[groupKey]) {
series[groupKey] = renderer.g(groupKey)
.attr({
// @todo Set the zIndex based upon the number of
// levels, instead of using 1000
zIndex: 1000 - levelDynamic
})
.add(series.group);
}
}
// Draw the point
point.draw({
animatableAttribs: animate,
attribs: attr,
css: css,
group: series[groupKey],
renderer: renderer,
shadow: shadow,
shapeArgs: shapeArgs,
shapeType: 'rect'
});
// If setRootNode is allowed, set a point cursor on clickables &
// add drillId to point
if (allowTraversingTree && point.graphic) {
point.drillId = options.interactByLeaf ?
series.drillToByLeaf(point) :
series.drillToByGroup(point);
}
});
},
// Add drilling on the suitable points
onClickDrillToNode: function (event) {
var series = this,
point = event.point,
drillId = point && point.drillId;
// If a drill id is returned, add click event and cursor.
if (isString(drillId)) {
point.setState(''); // Remove hover
series.setRootNode(drillId, true, { trigger: 'click' });
}
},
/**
* Finds the drill id for a parent node. Returns false if point should
* not have a click event.
*
* @private
* @function Highcharts.Series#drillToByGroup
*
* @param {object} point
*
* @return {boolean|string}
* Drill to id or false when point should not have a click
* event.
*/
drillToByGroup: function (point) {
var series = this,
drillId = false;
if ((point.node.level - series.nodeMap[series.rootNode].level) ===
1 &&
!point.node.isLeaf
) {
drillId = point.id;
}
return drillId;
},
/**
* Finds the drill id for a leaf node. Returns false if point should not
* have a click event
*
* @private
* @function Highcharts.Series#drillToByLeaf
*
* @param {object} point
*
* @return {boolean|string}
* Drill to id or false when point should not have a click
* event.
*/
drillToByLeaf: function (point) {
var series = this,
drillId = false,
nodeParent;
if ((point.node.parent !== series.rootNode) &&
point.node.isLeaf
) {
nodeParent = point.node;
while (!drillId) {
nodeParent = series.nodeMap[nodeParent.parent];
if (nodeParent.parent === series.rootNode) {
drillId = nodeParent.id;
}
}
}
return drillId;
},
drillUp: function () {
var series = this,
node = series.nodeMap[series.rootNode];
if (node && isString(node.parent)) {
series.setRootNode(
node.parent,
true,
{ trigger: 'traverseUpButton' }
);
}
},
// TODO remove this function at a suitable version.
drillToNode: function (id, redraw) {
error(
'WARNING: treemap.drillToNode has been renamed to treemap.' +
'setRootNode, and will be removed in the next major version.'
);
this.setRootNode(id, redraw);
},
/**
* Sets a new root node for the series.
*
* @private
* @function Highcharts.Series#setRootNode
*
* @param {string} id The id of the new root node.
* @param {boolean} [redraw=true] Wether to redraw the chart or not.
* @param {object} [eventArguments] Arguments to be accessed in
* event handler.
* @param {string} [eventArguments.newRootId] Id of the new root.
* @param {string} [eventArguments.previousRootId] Id of the previous
* root.
* @param {boolean} [eventArguments.redraw] Wether to redraw the
* chart after.
* @param {object} [eventArguments.series] The series to update the root
* of.
* @param {string} [eventArguments.trigger] The action which
* triggered the event. Undefined if the setRootNode is called
* directly.
*/
setRootNode: function (id, redraw, eventArguments) {
var series = this,
eventArgs = extend({
newRootId: id,
previousRootId: series.rootNode,
redraw: pick(redraw, true),
series: series
}, eventArguments);
/**
* The default functionality of the setRootNode event.
*
* @private
* @param {object} args The event arguments.
* @param {string} args.newRootId Id of the new root.
* @param {string} args.previousRootId Id of the previous root.
* @param {boolean} args.redraw Wether to redraw the chart after.
* @param {object} args.series The series to update the root of.
* @param {string} [args.trigger=undefined] The action which
* triggered the event. Undefined if the setRootNode is called
* directly.
*/
var defaultFn = function (args) {
var series = args.series;
// Store previous and new root ids on the series.
series.idPreviousRoot = args.previousRootId;
series.rootNode = args.newRootId;
// Redraw the chart
series.isDirty = true; // Force redraw
if (args.redraw) {
series.chart.redraw();
}
};
// Fire setRootNode event.
fireEvent(series, 'setRootNode', eventArgs, defaultFn);
},
renderTraverseUpButton: function (rootId) {
var series = this,
nodeMap = series.nodeMap,
node = nodeMap[rootId],
name = node.name,
buttonOptions = series.options.traverseUpButton,
backText = pick(buttonOptions.text, name, '< Back'),
attr,
states;
if (rootId === '') {
if (series.drillUpButton) {
series.drillUpButton = series.drillUpButton.destroy();
}
} else if (!this.drillUpButton) {
attr = buttonOptions.theme;
states = attr && attr.states;
this.drillUpButton = this.chart.renderer.button(
backText,
null,
null,
function () {
series.drillUp();
},
attr,
states && states.hover,
states && states.select
)
.addClass('highcharts-drillup-button')
.attr({
align: buttonOptions.position.align,
zIndex: 7
})
.add()
.align(
buttonOptions.position,
false,
buttonOptions.relativeTo || 'plotBox'
);
} else {
this.drillUpButton.placed = false;
this.drillUpButton.attr({
text: backText
})
.align();
}
},
buildKDTree: noop,
drawLegendSymbol: H.LegendSymbolMixin.drawRectangle,
getExtremes: function () {
// Get the extremes from the value data
Series.prototype.getExtremes.call(this, this.colorValueData);
this.valueMin = this.dataMin;
this.valueMax = this.dataMax;
// Get the extremes from the y data
Series.prototype.getExtremes.call(this);
},
getExtremesFromAll: true,
bindAxes: function () {
var treeAxis = {
endOnTick: false,
gridLineWidth: 0,
lineWidth: 0,
min: 0,
dataMin: 0,
minPadding: 0,
max: 100,
dataMax: 100,
maxPadding: 0,
startOnTick: false,
title: null,
tickPositions: []
};
Series.prototype.bindAxes.call(this);
H.extend(this.yAxis.options, treeAxis);
H.extend(this.xAxis.options, treeAxis);
},
/**
* Workaround for `inactive` state. Since `series.opacity` option is
* already reserved, don't use that state at all by disabling
* `inactiveOtherPoints` and not inheriting states by points.
*
* @private
*/
setState: function (state) {
this.options.inactiveOtherPoints = true;
Series.prototype.setState.call(this, state, false);
this.options.inactiveOtherPoints = false;
},
utils: {
recursive: recursive
}
// Point class
}, {
draw: drawPoint,
getClassName: function () {
var className = H.Point.prototype.getClassName.call(this),
series = this.series,
options = series.options;
// Above the current level
if (this.node.level <= series.nodeMap[series.rootNode].level) {
className += ' highcharts-above-level';
} else if (
!this.node.isLeaf &&
!pick(options.interactByLeaf, !options.allowTraversingTree)
) {
className += ' highcharts-internal-node-interactive';
} else if (!this.node.isLeaf) {
className += ' highcharts-internal-node';
}
return className;
},
/**
* A tree point is valid if it has han id too, assume it may be a parent
* item.
*
* @private
* @function Highcharts.Point#isValid
*/
isValid: function () {
return this.id || isNumber(this.value);
},
setState: function (state) {
H.Point.prototype.setState.call(this, state);
// Graphic does not exist when point is not visible.
if (this.graphic) {
this.graphic.attr({
zIndex: state === 'hover' ? 1 : 0
});
}
},
setVisible: seriesTypes.pie.prototype.pointClass.prototype.setVisible,
shouldDraw: function () {
var point = this;
return isNumber(point.plotY) && point.y !== null;
}
}
);
/**
* A `treemap` series. If the [type](#series.treemap.type) option is
* not specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.treemap
* @excluding dataParser, dataURL, stack
* @product highcharts
* @apioption series.treemap
*/
/**
* An array of data points for the series. For the `treemap` series
* type, points can be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values will be
* interpreted as `value` options. Example:
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.treemap.turboThreshold),
* this option is not available.
* ```js
* data: [{
* value: 9,
* name: "Point2",
* color: "#00FF00"
* }, {
* value: 6,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/chart/reflow-true/
* Numerical values
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<number|null|*>}
* @extends series.heatmap.data
* @excluding x, y
* @product highcharts
* @apioption series.treemap.data
*/
/**
* The value of the point, resulting in a relative area of the point
* in the treemap.
*
* @type {number|null}
* @product highcharts
* @apioption series.treemap.data.value
*/
/**
* Serves a purpose only if a `colorAxis` object is defined in the chart
* options. This value will decide which color the point gets from the
* scale of the colorAxis.
*
* @type {number}
* @since 4.1.0
* @product highcharts
* @apioption series.treemap.data.colorValue
*/
/**
* Only for treemap. Use this option to build a tree structure. The
* value should be the id of the point which is the parent. If no points
* has a matching id, or this option is undefined, then the parent will
* be set to the root.
*
* @sample {highcharts} highcharts/point/parent/
* Point parent
* @sample {highcharts} highcharts/demo/treemap-with-levels/
* Example where parent id is not matching
*
* @type {string}
* @since 4.1.0
* @product highcharts
* @apioption series.treemap.data.parent
*/
});
_registerModule(_modules, 'masters/modules/treemap.src.js', [], function () {
});
}));
|
Java
|
"""Neural network operations."""
from __future__ import absolute_import as _abs
from . import _make
def conv2d(data,
weight,
strides=(1, 1),
padding=(0, 0),
dilation=(1, 1),
groups=1,
channels=None,
kernel_size=None,
data_layout="NCHW",
weight_layout="OIHW",
out_layout="",
out_dtype=""):
r"""2D convolution.
This operator takes the weight as the convolution kernel
and convolves it with data to produce an output.
In the default case, where the data_layout is `NCHW`
and weight_layout is `OIHW`, conv2d takes in
a data Tensor with shape `(batch_size, in_channels, height, width)`,
and a weight Tensor with shape `(channels, in_channels, kernel_size[0], kernel_size[1])`
to produce an output Tensor with the following rule:
.. math::
\mbox{out}[b, c, y, x] = \sum_{dy, dx, k}
\mbox{data}[b, k, \mbox{strides}[0] * y + dy, \mbox{strides}[1] * x + dx] *
\mbox{weight}[c, k, dy, dx]
Padding and dilation are applied to data and weight respectively before the computation.
This operator accepts data layout specification.
Semantically, the operator will convert the layout to the canonical layout
(`NCHW` for data and `OIHW` for weight), perform the computation,
then convert to the out_layout.
Parameters
----------
data : relay.Expr
The input data to the operator.
weight : relay.Expr
The weight expressions.
strides : tuple of int, optional
The strides of convoltution.
padding : tuple of int, optional
The padding of convolution on both sides of inputs before convolution.
dilation : tuple of int, optional
Specifies the dilation rate to be used for dilated convolution.
groups : int, optional
Number of groups for grouped convolution.
channels : int, optional
Number of output channels of this convolution.
kernel_size : tuple of int, optional
The spatial of the convolution kernel.
data_layout : str, optional
Layout of the input.
weight_layout : str, optional
Layout of the weight.
out_layout : str, optional
Layout of the output, by default, out_layout is the same as data_layout
out_dtype : str, optional
Specifies the output data type for mixed precision conv2d.
Returns
-------
result : relay.Expr
The computed result.
"""
return _make.conv2d(data, weight, strides, padding, dilation,
groups, channels, kernel_size, data_layout,
weight_layout, out_layout, out_dtype)
def softmax(data, axis):
r"""Computes softmax.
.. math:: \text{softmax}(x)_i = \frac{exp(x_i)}{\sum_j exp(x_j)}
.. note::
This operator can be optimized away for inference.
Parameters
----------
data: relay.Expr
The input data to the operator.
axis: int
The axis to sum over when computing softmax
"""
return _make.softmax(data, axis)
def log_softmax(data, axis):
r"""Computes log softmax.
.. math::
\text{log_softmax}(x)_i = \log \frac{exp(x_i)}{\sum_j exp(x_j)}
.. note::
This operator can be optimized away for inference.
Parameters
----------
data: relay.Expr
The input data to the operator.
axis: int
The axis to sum over when computing softmax
"""
return _make.log_softmax(data, axis)
def max_pool2d(data,
pool_size=(1, 1),
strides=(1, 1),
padding=(0, 0),
layout="NCHW",
ceil_mode=False):
r"""2D maximum pooling operator.
This operator takes data as input and does 2D max value calculation
with in pool_size sized window by striding defined by stride
In the default case, where the data_layout is `NCHW`
a data Tensor with shape `(batch_size, in_channels, height, width)`,
to produce an output Tensor with the following rule:
with data of shape (b, c, h, w) and pool_size (kh, kw)
.. math::
\mbox{out}(b, c, y, x) = \max_{m=0, \ldots, kh-1} \max_{n=0, \ldots, kw-1}
\mbox{data}(b, c, \mbox{stride}[0] * y + m, \mbox{stride}[1] * x + n)
Padding is applied to data before the computation.
ceil_mode is used to take ceil or floor while computing out shape.
This operator accepts data layout specification.
Parameters
----------
data : relay.Expr
The input data to the operator.
strides : tuple of int, optional
The strides of pooling.
padding : tuple of int, optional
The padding for pooling.
layout : str, optional
Layout of the input.
ceil_mode : bool, optional
To enable or disable ceil while pooling.
Returns
-------
result : relay.Expr
The computed result.
"""
return _make.max_pool2d(data, pool_size, strides, padding,
layout, ceil_mode)
def avg_pool2d(data,
pool_size=(1, 1),
strides=(1, 1),
padding=(0, 0),
layout="NCHW",
ceil_mode=False,
count_include_pad=False):
r"""2D average pooling operator.
This operator takes data as input and does 2D average value calculation
with in pool_size sized window by striding defined by stride
In the default case, where the data_layout is `NCHW`
a data Tensor with shape `(batch_size, in_channels, height, width)`,
to produce an output Tensor with the following rule:
with data of shape (b, c, h, w), pool_size (kh, kw)
.. math::
\mbox{out}(b, c, y, x) = \frac{1}{kh * kw} \sum_{m=0}^{kh-1} \sum_{n=0}^{kw-1}
\mbox{data}(b, c, \mbox{stride}[0] * y + m, \mbox{stride}[1] * x + n)
Padding is applied to data before the computation.
ceil_mode is used to take ceil or floor while computing out shape.
count_include_pad indicates including or excluding padded input values in computation.
This operator accepts data layout specification.
Parameters
----------
data : relay.Expr
The input data to the operator.
strides : tuple of int, optional
The strides of pooling.
padding : tuple of int, optional
The padding for pooling.
layout : str, optional
Layout of the input.
ceil_mode : bool, optional
To enable or disable ceil while pooling.
count_include_pad : bool, optional
To include padding to compute the average.
Returns
-------
result : relay.Expr
The computed result.
"""
return _make.avg_pool2d(data, pool_size, strides, padding,
layout, ceil_mode, count_include_pad)
def global_max_pool2d(data,
layout="NCHW"):
r"""2D global maximum pooling operator.
This operator takes data as input and does 2D max value calculation
across each window represented by WxH.
In the default case, where the data_layout is `NCHW`
a data Tensor with shape `(batch_size, in_channels, height, width)`,
to produce an output Tensor with the following rule:
with data of shape (b, c, h, w)
.. math::
\mbox{out}(b, c, 1, 1) = \max_{m=0, \ldots, h} \max_{n=0, \ldots, w}
\mbox{data}(b, c, m, n)
Parameters
----------
data : relay.Expr
The input data to the operator.
layout : str, optional
Layout of the input.
Returns
-------
result : relay.Expr
The computed result.
"""
return _make.global_max_pool2d(data, layout)
def global_avg_pool2d(data,
layout="NCHW"):
r"""2D global average pooling operator.
This operator takes data as input and does 2D average value calculation
across each window represented by WxH.
In the default case, where the data_layout is `NCHW`
a data Tensor with shape `(batch_size, in_channels, height, width)`,
to produce an output Tensor with the following rule:
with data of shape (b, c, h, w)
.. math::
\mbox{out}(b, c, 1, 1) = \frac{1}{h * w} \sum_{m=0}^{h-1} \sum_{n=0}^{w-1}
\mbox{data}(b, c, m, n)
Parameters
----------
data : relay.Expr
The input data to the operator.
layout : str, optional
Layout of the input.
Returns
-------
result : relay.Expr
The computed result.
"""
return _make.global_avg_pool2d(data, layout)
def upsampling(data,
scale=1,
layout="NCHW",
method="NEAREST_NEIGHBOR"):
"""Upsampling.
This operator takes data as input and does 2D scaling to the given scale factor.
In the default case, where the data_layout is `NCHW`
with data of shape (n, c, h, w)
out will have a shape (n, c, h*scale, w*scale)
method indicates the algorithm to be used while calculating ghe out value
and method can be one of ("BILINEAR", "NEAREST_NEIGHBOR")
Parameters
----------
data : relay.Expr
The input data to the operator.
scale : relay.Expr
The scale factor for upsampling.
layout : str, optional
Layout of the input.
method : str, optional
Scale method to used [NEAREST_NEIGHBOR, BILINEAR].
Returns
-------
result : relay.Expr
The computed result.
"""
return _make.upsampling(data, scale, layout, method)
def batch_flatten(data):
"""BatchFlatten.
This operator flattens all the dimensions except for the batch dimension.
which results a 2D output.
For data with shape ``(d1, d2, ..., dk)``
batch_flatten(data) returns reshaped output of shape ``(d1, d2*...*dk)``.
Parameters
----------
data : relay.Expr
The input data to the operator.
Returns
-------
result: relay.Expr
The Flattened result.
"""
return _make.batch_flatten(data)
|
Java
|
<?php
/**
* Project Name: map-board
* File Name: create_benchmark_fixture.php
* Last modified: 2017/11/20 12:51
* Author: Hiroaki Goto
*
* Copyright (c) 2017 Hiroaki Goto. All rights reserved.
*/
require_once __DIR__.'/../vendor/autoload.php';
$db = connectDB();
$redis = connectRedis();
const USER_SIZE = 1000;
const THREAD_NUM = 200;
const MIN_POST = 0;
const MAX_POST = 10000;
const CONTENT_MIN = 3;
const CONTENT_MAX = 1000;
function unichr( $unicode , $encoding = 'UTF-8' ) {
return mb_convert_encoding("&#{$unicode};", $encoding, 'HTML-ENTITIES');
}
class RandomStringGenerator {
private $seed;
private $strtmp;
private $seedSize;
private $cnt = 0;
public function __construct(bool $only_ascii = false, bool $multi_line = true) {
$this->seed = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
if(!$only_ascii) {
// ひらがな
for ($i = 12353; $i <= 12435; $i++) {
$this->seed .= unichr($i);
}
// カタカナ
for ($i = 12449; $i <= 12534; $i++) {
$this->seed .= unichr($i);
}
// 常用漢字
$file_content = file_get_contents('joyo.csv');
$unicode_list = preg_split('/(\r\n)|[\r\n]/', $file_content);
foreach ($unicode_list as $code_point) {
$this->seed .= unichr(hexdec($code_point));
}
}
// 改行文字
if($multi_line) {
$this->seed .= '\n';
}
$this->seedSize = mb_strlen($this->seed);
$this->shuffle();
}
private function shuffle() {
$this->strtmp = '';
for($i = 0; $i < $this->seedSize; $i++) {
$this->strtmp .= mb_substr($this->seed, mt_rand(0, $this->seedSize - 1), 1);
}
}
public function pseudo(int $length) {
if(++$this->cnt > 1000) {
$this->cnt = 0;
$this->shuffle();
}
$offset_max = $this->seedSize - $length;
return mb_substr($this->strtmp, mt_rand(0, $offset_max), $length);
}
public function generate(int $length) {
$str = '';
for($i = 0; $i < $length; $i++) {
$str .= mb_substr($this->seed, mt_rand(0, $this->seedSize - 1), 1);
}
return $str;
}
}
$single_gen = new RandomStringGenerator(true, false);
$content_gen = new RandomStringGenerator();
$gen_content = function() use($content_gen) {
return $content_gen->pseudo(mt_rand(CONTENT_MIN, CONTENT_MAX));
};
echo "Creating users...\n";
$user_ids = [];
for($i = 0; $i < USER_SIZE; $i++) {
$password = $single_gen->pseudo(mt_rand(7, 40));
$user_name = $single_gen->generate(mt_rand(4, 8));
$user = new mb\models\User($user_name, $user_name.'@example.com', $password, $password);
if($user->create($db)) {
$user_ids[] = $user->id;
}
}
$user_count = count($user_ids);
$gen_user_id = function() use($user_ids, $user_count) {
return $user_ids[mt_rand(0, $user_count - 1)];
};
echo "End creating users.\n";
echo "Creating threads...\n";
for($i = 0; $i < THREAD_NUM; $i++) {
$thread_owner = $gen_user_id();
$thread = new mb\models\Thread($db, $single_gen->generate(mt_rand(5, 80)), $thread_owner);
$thread->create($db, $redis);
$post_first = new mb\models\Post($db, $thread->id, $thread_owner, $gen_content());
$post_first->create($db);
$post_num = mt_rand(MIN_POST, MAX_POST);
for($j = 0; $j < $post_num; $j++) {
$post = new mb\models\Post($db, $thread->id, $gen_user_id(), $gen_content());
$post->create($db);
}
}
echo "End creating thread.\n";
|
Java
|
package com.jason.showcase.lambdas;
/**
* Created by Qinjianf on 2016/7/19.
*/
public class Lambda {
public void execute(Action action) {
action.run("Hello Lambda!");
}
public void test() {
execute(System.out::println);
}
public static void main(String[] args) {
new Lambda().test();
}
}
|
Java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.oozie.action.hadoop;
import com.google.common.annotations.VisibleForTesting;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.apache.commons.lang.StringUtils;
import org.apache.directory.api.util.Strings;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.Path;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Pattern;
import static org.apache.oozie.action.hadoop.SparkActionExecutor.SPARK_DEFAULT_OPTS;
@SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "Properties file should be specified by user")
class SparkArgsExtractor {
private static final Pattern SPARK_DEFAULTS_FILE_PATTERN = Pattern.compile("spark-defaults.conf");
private static final String FILES_OPTION = "--files";
private static final String ARCHIVES_OPTION = "--archives";
private static final String LOG4J_CONFIGURATION_JAVA_OPTION = "-Dlog4j.configuration=";
private static final String SECURITY_TOKENS_HADOOPFS = "spark.yarn.security.tokens.hadoopfs.enabled";
private static final String SECURITY_TOKENS_HIVE = "spark.yarn.security.tokens.hive.enabled";
private static final String SECURITY_TOKENS_HBASE = "spark.yarn.security.tokens.hbase.enabled";
private static final String SECURITY_CREDENTIALS_HADOOPFS = "spark.yarn.security.credentials.hadoopfs.enabled";
private static final String SECURITY_CREDENTIALS_HIVE = "spark.yarn.security.credentials.hive.enabled";
private static final String SECURITY_CREDENTIALS_HBASE = "spark.yarn.security.credentials.hbase.enabled";
private static final String PWD = "$PWD" + File.separator + "*";
private static final String MASTER_OPTION = "--master";
private static final String MODE_OPTION = "--deploy-mode";
private static final String JOB_NAME_OPTION = "--name";
private static final String CLASS_NAME_OPTION = "--class";
private static final String VERBOSE_OPTION = "--verbose";
private static final String DRIVER_CLASSPATH_OPTION = "--driver-class-path";
private static final String EXECUTOR_CLASSPATH = "spark.executor.extraClassPath=";
private static final String DRIVER_CLASSPATH = "spark.driver.extraClassPath=";
private static final String EXECUTOR_EXTRA_JAVA_OPTIONS = "spark.executor.extraJavaOptions=";
private static final String DRIVER_EXTRA_JAVA_OPTIONS = "spark.driver.extraJavaOptions=";
private static final Pattern SPARK_VERSION_1 = Pattern.compile("^1.*");
private static final String SPARK_YARN_JAR = "spark.yarn.jar";
private static final String SPARK_YARN_JARS = "spark.yarn.jars";
private static final String OPT_SEPARATOR = "=";
private static final String OPT_VALUE_SEPARATOR = ",";
private static final String CONF_OPTION = "--conf";
private static final String MASTER_OPTION_YARN_CLUSTER = "yarn-cluster";
private static final String MASTER_OPTION_YARN_CLIENT = "yarn-client";
private static final String MASTER_OPTION_YARN = "yarn";
private static final String DEPLOY_MODE_CLUSTER = "cluster";
private static final String DEPLOY_MODE_CLIENT = "client";
private static final String SPARK_YARN_TAGS = "spark.yarn.tags";
private static final String OPT_PROPERTIES_FILE = "--properties-file";
public static final String SPARK_DEFAULTS_GENERATED_PROPERTIES = "spark-defaults-oozie-generated.properties";
private boolean pySpark = false;
private final Configuration actionConf;
SparkArgsExtractor(final Configuration actionConf) {
this.actionConf = actionConf;
}
boolean isPySpark() {
return pySpark;
}
List<String> extract(final String[] mainArgs) throws OozieActionConfiguratorException, IOException, URISyntaxException {
final List<String> sparkArgs = new ArrayList<>();
sparkArgs.add(MASTER_OPTION);
final String master = actionConf.get(SparkActionExecutor.SPARK_MASTER);
sparkArgs.add(master);
// In local mode, everything runs here in the Launcher Job.
// In yarn-client mode, the driver runs here in the Launcher Job and the
// executor in Yarn.
// In yarn-cluster mode, the driver and executor run in Yarn.
final String sparkDeployMode = actionConf.get(SparkActionExecutor.SPARK_MODE);
if (sparkDeployMode != null) {
sparkArgs.add(MODE_OPTION);
sparkArgs.add(sparkDeployMode);
}
final boolean yarnClusterMode = master.equals(MASTER_OPTION_YARN_CLUSTER)
|| (master.equals(MASTER_OPTION_YARN) && sparkDeployMode != null && sparkDeployMode.equals(DEPLOY_MODE_CLUSTER));
final boolean yarnClientMode = master.equals(MASTER_OPTION_YARN_CLIENT)
|| (master.equals(MASTER_OPTION_YARN) && sparkDeployMode != null && sparkDeployMode.equals(DEPLOY_MODE_CLIENT));
sparkArgs.add(JOB_NAME_OPTION);
sparkArgs.add(actionConf.get(SparkActionExecutor.SPARK_JOB_NAME));
final String className = actionConf.get(SparkActionExecutor.SPARK_CLASS);
if (className != null) {
sparkArgs.add(CLASS_NAME_OPTION);
sparkArgs.add(className);
}
appendOoziePropertiesToSparkConf(sparkArgs);
String jarPath = actionConf.get(SparkActionExecutor.SPARK_JAR);
if (jarPath != null && jarPath.endsWith(".py")) {
pySpark = true;
}
boolean addedSecurityTokensHadoopFS = false;
boolean addedSecurityTokensHive = false;
boolean addedSecurityTokensHBase = false;
boolean addedSecurityCredentialsHadoopFS = false;
boolean addedSecurityCredentialsHive = false;
boolean addedSecurityCredentialsHBase = false;
boolean addedLog4jDriverSettings = false;
boolean addedLog4jExecutorSettings = false;
final StringBuilder driverClassPath = new StringBuilder();
final StringBuilder executorClassPath = new StringBuilder();
final StringBuilder userFiles = new StringBuilder();
final StringBuilder userArchives = new StringBuilder();
final String sparkOpts = actionConf.get(SparkActionExecutor.SPARK_OPTS);
String propertiesFile = null;
if (StringUtils.isNotEmpty(sparkOpts)) {
final List<String> sparkOptions = SparkOptionsSplitter.splitSparkOpts(sparkOpts);
for (int i = 0; i < sparkOptions.size(); i++) {
String opt = sparkOptions.get(i);
boolean addToSparkArgs = true;
if (yarnClusterMode || yarnClientMode) {
if (opt.startsWith(EXECUTOR_CLASSPATH)) {
appendWithPathSeparator(opt.substring(EXECUTOR_CLASSPATH.length()), executorClassPath);
addToSparkArgs = false;
}
if (opt.startsWith(DRIVER_CLASSPATH)) {
appendWithPathSeparator(opt.substring(DRIVER_CLASSPATH.length()), driverClassPath);
addToSparkArgs = false;
}
if (opt.equals(DRIVER_CLASSPATH_OPTION)) {
// we need the next element after this option
appendWithPathSeparator(sparkOptions.get(i + 1), driverClassPath);
// increase i to skip the next element.
i++;
addToSparkArgs = false;
}
}
if (opt.startsWith(SECURITY_TOKENS_HADOOPFS)) {
addedSecurityTokensHadoopFS = true;
}
if (opt.startsWith(SECURITY_TOKENS_HIVE)) {
addedSecurityTokensHive = true;
}
if (opt.startsWith(SECURITY_TOKENS_HBASE)) {
addedSecurityTokensHBase = true;
}
if (opt.startsWith(SECURITY_CREDENTIALS_HADOOPFS)) {
addedSecurityCredentialsHadoopFS = true;
}
if (opt.startsWith(SECURITY_CREDENTIALS_HIVE)) {
addedSecurityCredentialsHive = true;
}
if (opt.startsWith(SECURITY_CREDENTIALS_HBASE)) {
addedSecurityCredentialsHBase = true;
}
if (opt.startsWith(OPT_PROPERTIES_FILE)){
i++;
propertiesFile = sparkOptions.get(i);
addToSparkArgs = false;
}
if (opt.startsWith(EXECUTOR_EXTRA_JAVA_OPTIONS) || opt.startsWith(DRIVER_EXTRA_JAVA_OPTIONS)) {
if (!opt.contains(LOG4J_CONFIGURATION_JAVA_OPTION)) {
opt += " " + LOG4J_CONFIGURATION_JAVA_OPTION + SparkMain.SPARK_LOG4J_PROPS;
} else {
System.out.println("Warning: Spark Log4J settings are overwritten." +
" Child job IDs may not be available");
}
if (opt.startsWith(EXECUTOR_EXTRA_JAVA_OPTIONS)) {
addedLog4jExecutorSettings = true;
} else {
addedLog4jDriverSettings = true;
}
}
if (opt.startsWith(FILES_OPTION)) {
final String userFile;
if (opt.contains(OPT_SEPARATOR)) {
userFile = opt.substring(opt.indexOf(OPT_SEPARATOR) + OPT_SEPARATOR.length());
}
else {
userFile = sparkOptions.get(i + 1);
i++;
}
if (userFiles.length() > 0) {
userFiles.append(OPT_VALUE_SEPARATOR);
}
userFiles.append(userFile);
addToSparkArgs = false;
}
if (opt.startsWith(ARCHIVES_OPTION)) {
final String userArchive;
if (opt.contains(OPT_SEPARATOR)) {
userArchive = opt.substring(opt.indexOf(OPT_SEPARATOR) + OPT_SEPARATOR.length());
}
else {
userArchive = sparkOptions.get(i + 1);
i++;
}
if (userArchives.length() > 0) {
userArchives.append(OPT_VALUE_SEPARATOR);
}
userArchives.append(userArchive);
addToSparkArgs = false;
}
if (addToSparkArgs) {
sparkArgs.add(opt);
}
else if (sparkArgs.get(sparkArgs.size() - 1).equals(CONF_OPTION)) {
sparkArgs.remove(sparkArgs.size() - 1);
}
}
}
if ((yarnClusterMode || yarnClientMode)) {
// Include the current working directory (of executor container)
// in executor classpath, because it will contain localized
// files
appendWithPathSeparator(PWD, executorClassPath);
appendWithPathSeparator(PWD, driverClassPath);
sparkArgs.add(CONF_OPTION);
sparkArgs.add(EXECUTOR_CLASSPATH + executorClassPath.toString());
sparkArgs.add(CONF_OPTION);
sparkArgs.add(DRIVER_CLASSPATH + driverClassPath.toString());
}
if (actionConf.get(LauncherMain.MAPREDUCE_JOB_TAGS) != null) {
sparkArgs.add(CONF_OPTION);
sparkArgs.add(SPARK_YARN_TAGS + OPT_SEPARATOR + actionConf.get(LauncherMain.MAPREDUCE_JOB_TAGS));
}
if (!addedSecurityTokensHadoopFS) {
sparkArgs.add(CONF_OPTION);
sparkArgs.add(SECURITY_TOKENS_HADOOPFS + OPT_SEPARATOR + Boolean.toString(false));
}
if (!addedSecurityTokensHive) {
sparkArgs.add(CONF_OPTION);
sparkArgs.add(SECURITY_TOKENS_HIVE + OPT_SEPARATOR + Boolean.toString(false));
}
if (!addedSecurityTokensHBase) {
sparkArgs.add(CONF_OPTION);
sparkArgs.add(SECURITY_TOKENS_HBASE + OPT_SEPARATOR + Boolean.toString(false));
}
if (!addedSecurityCredentialsHadoopFS) {
sparkArgs.add(CONF_OPTION);
sparkArgs.add(SECURITY_CREDENTIALS_HADOOPFS + OPT_SEPARATOR + Boolean.toString(false));
}
if (!addedSecurityCredentialsHive) {
sparkArgs.add(CONF_OPTION);
sparkArgs.add(SECURITY_CREDENTIALS_HIVE + OPT_SEPARATOR + Boolean.toString(false));
}
if (!addedSecurityCredentialsHBase) {
sparkArgs.add(CONF_OPTION);
sparkArgs.add(SECURITY_CREDENTIALS_HBASE + OPT_SEPARATOR + Boolean.toString(false));
}
if (!addedLog4jExecutorSettings) {
sparkArgs.add(CONF_OPTION);
sparkArgs.add(EXECUTOR_EXTRA_JAVA_OPTIONS + LOG4J_CONFIGURATION_JAVA_OPTION + SparkMain.SPARK_LOG4J_PROPS);
}
if (!addedLog4jDriverSettings) {
sparkArgs.add(CONF_OPTION);
sparkArgs.add(DRIVER_EXTRA_JAVA_OPTIONS + LOG4J_CONFIGURATION_JAVA_OPTION + SparkMain.SPARK_LOG4J_PROPS);
}
mergeAndAddPropertiesFile(sparkArgs, propertiesFile);
if ((yarnClusterMode || yarnClientMode)) {
final Map<String, URI> fixedFileUrisMap =
SparkMain.fixFsDefaultUrisAndFilterDuplicates(DistributedCache.getCacheFiles(actionConf));
fixedFileUrisMap.put(SparkMain.SPARK_LOG4J_PROPS, new Path(SparkMain.SPARK_LOG4J_PROPS).toUri());
fixedFileUrisMap.put(SparkMain.HIVE_SITE_CONF, new Path(SparkMain.HIVE_SITE_CONF).toUri());
addUserDefined(userFiles.toString(), fixedFileUrisMap);
final Collection<URI> fixedFileUris = fixedFileUrisMap.values();
final JarFilter jarFilter = new JarFilter(fixedFileUris, jarPath);
jarFilter.filter();
jarPath = jarFilter.getApplicationJar();
final String cachedFiles = StringUtils.join(fixedFileUris, OPT_VALUE_SEPARATOR);
if (cachedFiles != null && !cachedFiles.isEmpty()) {
sparkArgs.add(FILES_OPTION);
sparkArgs.add(cachedFiles);
}
final Map<String, URI> fixedArchiveUrisMap = SparkMain.fixFsDefaultUrisAndFilterDuplicates(DistributedCache.
getCacheArchives(actionConf));
addUserDefined(userArchives.toString(), fixedArchiveUrisMap);
final String cachedArchives = StringUtils.join(fixedArchiveUrisMap.values(), OPT_VALUE_SEPARATOR);
if (cachedArchives != null && !cachedArchives.isEmpty()) {
sparkArgs.add(ARCHIVES_OPTION);
sparkArgs.add(cachedArchives);
}
setSparkYarnJarsConf(sparkArgs, jarFilter.getSparkYarnJar(), jarFilter.getSparkVersion());
}
if (!sparkArgs.contains(VERBOSE_OPTION)) {
sparkArgs.add(VERBOSE_OPTION);
}
sparkArgs.add(jarPath);
sparkArgs.addAll(Arrays.asList(mainArgs));
return sparkArgs;
}
private void mergeAndAddPropertiesFile(final List<String> sparkArgs, final String userDefinedPropertiesFile)
throws IOException {
final Properties properties = new Properties();
loadServerDefaultProperties(properties);
loadLocalizedDefaultPropertiesFile(properties);
loadUserDefinedPropertiesFile(userDefinedPropertiesFile, properties);
final boolean persisted = persistMergedProperties(properties);
if (persisted) {
sparkArgs.add(OPT_PROPERTIES_FILE);
sparkArgs.add(SPARK_DEFAULTS_GENERATED_PROPERTIES);
}
}
private boolean persistMergedProperties(final Properties properties) throws IOException {
if (!properties.isEmpty()) {
try (final Writer writer = new OutputStreamWriter(
new FileOutputStream(new File(SPARK_DEFAULTS_GENERATED_PROPERTIES)),
StandardCharsets.UTF_8.name())) {
properties.store(writer, "Properties file generated by Oozie");
System.out.println(String.format("Persisted merged Spark configs in file %s. Merged properties are: %s",
SPARK_DEFAULTS_GENERATED_PROPERTIES, Arrays.toString(properties.stringPropertyNames().toArray())));
return true;
} catch (IOException e) {
System.err.println(String.format("Could not persist derived Spark config file. Reason: %s", e.getMessage()));
throw e;
}
}
return false;
}
private void loadUserDefinedPropertiesFile(final String userDefinedPropertiesFile, final Properties properties) {
if (userDefinedPropertiesFile != null) {
System.out.println(String.format("Reading Spark config from %s %s...", OPT_PROPERTIES_FILE, userDefinedPropertiesFile));
loadProperties(new File(userDefinedPropertiesFile), properties);
}
}
private void loadLocalizedDefaultPropertiesFile(final Properties properties) {
final File localizedDefaultConfFile = SparkMain.getMatchingFile(SPARK_DEFAULTS_FILE_PATTERN);
if (localizedDefaultConfFile != null) {
System.out.println(String.format("Reading Spark config from file %s...", localizedDefaultConfFile.getName()));
loadProperties(localizedDefaultConfFile, properties);
}
}
private void loadServerDefaultProperties(final Properties properties) {
final String sparkDefaultsFromServer = actionConf.get(SPARK_DEFAULT_OPTS, "");
if (!sparkDefaultsFromServer.isEmpty()) {
System.out.println("Reading Spark config propagated from Oozie server...");
try (final StringReader reader = new StringReader(sparkDefaultsFromServer)) {
properties.load(reader);
} catch (IOException e) {
System.err.println(String.format("Could not read propagated Spark config! Reason: %s", e.getMessage()));
}
}
}
private void loadProperties(final File file, final Properties target) {
try (final Reader reader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8.name())) {
final Properties properties = new Properties();
properties.load(reader);
for(String key :properties.stringPropertyNames()) {
Object prevProperty = target.setProperty(key, properties.getProperty(key));
if(prevProperty != null){
System.out.println(String.format("Value of %s was overwritten from %s", key, file.getName()));
}
}
} catch (IOException e) {
System.err.println(String.format("Could not read Spark configs from file %s. Reason: %s", file.getName(),
e.getMessage()));
}
}
private void appendWithPathSeparator(final String what, final StringBuilder to) {
if (to.length() > 0) {
to.append(File.pathSeparator);
}
to.append(what);
}
private void addUserDefined(final String userList, final Map<String, URI> urisMap) {
if (userList != null) {
for (final String file : userList.split(OPT_VALUE_SEPARATOR)) {
if (!Strings.isEmpty(file)) {
final Path p = new Path(file);
urisMap.put(p.getName(), p.toUri());
}
}
}
}
/*
* Get properties that needs to be passed to Spark as Spark configuration from actionConf.
*/
@VisibleForTesting
void appendOoziePropertiesToSparkConf(final List<String> sparkArgs) {
for (final Map.Entry<String, String> oozieConfig : actionConf
.getValByRegex("^oozie\\.(?!launcher|spark).+").entrySet()) {
sparkArgs.add(CONF_OPTION);
sparkArgs.add(String.format("spark.%s=%s", oozieConfig.getKey(), oozieConfig.getValue()));
}
}
/**
* Sets spark.yarn.jars for Spark 2.X. Sets spark.yarn.jar for Spark 1.X.
*
* @param sparkArgs
* @param sparkYarnJar
* @param sparkVersion
*/
private void setSparkYarnJarsConf(final List<String> sparkArgs, final String sparkYarnJar, final String sparkVersion) {
if (SPARK_VERSION_1.matcher(sparkVersion).find()) {
// In Spark 1.X.X, set spark.yarn.jar to avoid
// multiple distribution
sparkArgs.add(CONF_OPTION);
sparkArgs.add(SPARK_YARN_JAR + OPT_SEPARATOR + sparkYarnJar);
} else {
// In Spark 2.X.X, set spark.yarn.jars
sparkArgs.add(CONF_OPTION);
sparkArgs.add(SPARK_YARN_JARS + OPT_SEPARATOR + sparkYarnJar);
}
}
}
|
Java
|
package com.common.dao;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;
/**
* La Clase BaseDAO implementa las operaciones básicas de acceso a datos DAO
* utilizando usado por las clases DAO del módulo de ejecución de transacciones.
*
* @author Gestorinc S.A.
* @version $Rev $
*/
public class BaseDAO {
/**
* Constante que representa el character '%'.
*/
public static final String SYMBOLO_LIKE = "%";
/**
* Constante que representa la cadena "'".
*/
public static final String SYMBOLO_APOSTROFE = "'";
/**
* Creación del log de auditoría.
*/
protected static final Logger LOGGER = Logger.getLogger(BaseDAO.class.getName());
/**
* Objeto que maneja las operaciones de persistencia.
*/
@PersistenceContext(name = "punit")
private EntityManager em;
/**
* Constructor por defecto.
*/
public BaseDAO() {
}
/**
* Retorna una referencia al objeto que maneja las operaciones de
* persistencia definidas por JPA.
*
* @return Referencia al objeto que maneja las operaciones de persistencia.
* En caso de que el objeto no este inicializado lanza la excepción
* @see java.lang.IllegalStateException
*/
protected EntityManager getEntityManager() {
if (em == null) {
throw new IllegalStateException(
"EntityManager no ha sido asignado a DAO antes del uso.");
} else {
return em;
}
}
/**
* Ejecuta una sentencia SQL obteniendo una conexión a la BD, referenciado
* por la unidad de persistencia: <b>punit</b>.<br/>
* No utilizar este método para ejecutar sentencias SELECT.
*
* @param sentencia Sentencia SQL que será ejecutada.
*/
public void ejecutarNativo(String sentencia) {
try {
java.sql.Connection connection = em.unwrap(java.sql.Connection.class);
PreparedStatement ps = connection.prepareStatement(sentencia);
ps.execute();
ps.close();
} catch (PersistenceException e) {
LOGGER.info("Error al ejecutar sentencia"+ e.getMessage());
} catch (SQLException e) {
LOGGER.info("Error al ejecutar sentencia"+ e.getMessage());
}
}
/**
* Pone apóstrofes a una cadena de caracteres.
*
* @param cadena la cadena
* @return la cadena con apóstrofes
*/
protected String comillar(String cadena) {
return SYMBOLO_APOSTROFE + cadena + SYMBOLO_APOSTROFE;
}
}
|
Java
|
#include <memory>
#include "envoy/config/endpoint/v3/endpoint.pb.h"
#include "envoy/config/endpoint/v3/endpoint.pb.validate.h"
#include "envoy/service/discovery/v3/discovery.pb.h"
#include "source/common/common/empty_string.h"
#include "source/common/config/api_version.h"
#include "source/common/config/grpc_mux_impl.h"
#include "source/common/config/protobuf_link_hacks.h"
#include "source/common/config/utility.h"
#include "source/common/protobuf/protobuf.h"
#include "source/common/stats/isolated_store_impl.h"
#include "test/common/stats/stat_test_utility.h"
#include "test/mocks/common.h"
#include "test/mocks/config/mocks.h"
#include "test/mocks/event/mocks.h"
#include "test/mocks/grpc/mocks.h"
#include "test/mocks/local_info/mocks.h"
#include "test/mocks/runtime/mocks.h"
#include "test/test_common/logging.h"
#include "test/test_common/resources.h"
#include "test/test_common/simulated_time_system.h"
#include "test/test_common/test_time.h"
#include "test/test_common/utility.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using testing::_;
using testing::AtLeast;
using testing::InSequence;
using testing::Invoke;
using testing::IsSubstring;
using testing::NiceMock;
using testing::Return;
using testing::ReturnRef;
namespace Envoy {
namespace Config {
namespace {
// We test some mux specific stuff below, other unit test coverage for singleton use of GrpcMuxImpl
// is provided in [grpc_]subscription_impl_test.cc.
class GrpcMuxImplTestBase : public testing::Test {
public:
GrpcMuxImplTestBase()
: async_client_(new Grpc::MockAsyncClient()),
control_plane_connected_state_(
stats_.gauge("control_plane.connected_state", Stats::Gauge::ImportMode::NeverImport)),
control_plane_pending_requests_(
stats_.gauge("control_plane.pending_requests", Stats::Gauge::ImportMode::NeverImport))
{}
void setup() {
grpc_mux_ = std::make_unique<GrpcMuxImpl>(
local_info_, std::unique_ptr<Grpc::MockAsyncClient>(async_client_), dispatcher_,
*Protobuf::DescriptorPool::generated_pool()->FindMethodByName(
"envoy.service.discovery.v3.AggregatedDiscoveryService.StreamAggregatedResources"),
random_, stats_, rate_limit_settings_, true);
}
void setup(const RateLimitSettings& custom_rate_limit_settings) {
grpc_mux_ = std::make_unique<GrpcMuxImpl>(
local_info_, std::unique_ptr<Grpc::MockAsyncClient>(async_client_), dispatcher_,
*Protobuf::DescriptorPool::generated_pool()->FindMethodByName(
"envoy.service.discovery.v3.AggregatedDiscoveryService.StreamAggregatedResources"),
random_, stats_, custom_rate_limit_settings, true);
}
void expectSendMessage(const std::string& type_url,
const std::vector<std::string>& resource_names, const std::string& version,
bool first = false, const std::string& nonce = "",
const Protobuf::int32 error_code = Grpc::Status::WellKnownGrpcStatus::Ok,
const std::string& error_message = "") {
envoy::service::discovery::v3::DiscoveryRequest expected_request;
if (first) {
expected_request.mutable_node()->CopyFrom(local_info_.node());
}
for (const auto& resource : resource_names) {
expected_request.add_resource_names(resource);
}
if (!version.empty()) {
expected_request.set_version_info(version);
}
expected_request.set_response_nonce(nonce);
expected_request.set_type_url(type_url);
if (error_code != Grpc::Status::WellKnownGrpcStatus::Ok) {
::google::rpc::Status* error_detail = expected_request.mutable_error_detail();
error_detail->set_code(error_code);
error_detail->set_message(error_message);
}
EXPECT_CALL(async_stream_, sendMessageRaw_(Grpc::ProtoBufferEq(expected_request), false));
}
NiceMock<Event::MockDispatcher> dispatcher_;
NiceMock<Random::MockRandomGenerator> random_;
NiceMock<LocalInfo::MockLocalInfo> local_info_;
Grpc::MockAsyncClient* async_client_;
Grpc::MockAsyncStream async_stream_;
GrpcMuxImplPtr grpc_mux_;
NiceMock<MockSubscriptionCallbacks> callbacks_;
NiceMock<MockOpaqueResourceDecoder> resource_decoder_;
Stats::TestUtil::TestStore stats_;
Envoy::Config::RateLimitSettings rate_limit_settings_;
Stats::Gauge& control_plane_connected_state_;
Stats::Gauge& control_plane_pending_requests_;
};
class GrpcMuxImplTest : public GrpcMuxImplTestBase {
public:
Event::SimulatedTimeSystem time_system_;
};
// Validate behavior when multiple type URL watches are maintained, watches are created/destroyed
// (via RAII).
TEST_F(GrpcMuxImplTest, MultipleTypeUrlStreams) {
setup();
InSequence s;
auto foo_sub = grpc_mux_->addWatch("foo", {"x", "y"}, callbacks_, resource_decoder_, {});
auto bar_sub = grpc_mux_->addWatch("bar", {}, callbacks_, resource_decoder_, {});
EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_));
expectSendMessage("foo", {"x", "y"}, "", true);
expectSendMessage("bar", {}, "");
grpc_mux_->start();
EXPECT_EQ(1, control_plane_connected_state_.value());
expectSendMessage("bar", {"z"}, "");
auto bar_z_sub = grpc_mux_->addWatch("bar", {"z"}, callbacks_, resource_decoder_, {});
expectSendMessage("bar", {"zz", "z"}, "");
auto bar_zz_sub = grpc_mux_->addWatch("bar", {"zz"}, callbacks_, resource_decoder_, {});
expectSendMessage("bar", {"z"}, "");
expectSendMessage("bar", {}, "");
expectSendMessage("foo", {}, "");
}
// Validate behavior when dynamic context parameters are updated.
TEST_F(GrpcMuxImplTest, DynamicContextParameters) {
setup();
InSequence s;
auto foo_sub = grpc_mux_->addWatch("foo", {"x", "y"}, callbacks_, resource_decoder_, {});
auto bar_sub = grpc_mux_->addWatch("bar", {}, callbacks_, resource_decoder_, {});
EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_));
expectSendMessage("foo", {"x", "y"}, "", true);
expectSendMessage("bar", {}, "");
grpc_mux_->start();
// Unknown type, shouldn't do anything.
local_info_.context_provider_.update_cb_handler_.runCallbacks("baz");
// Update to foo type should resend Node.
expectSendMessage("foo", {"x", "y"}, "", true);
local_info_.context_provider_.update_cb_handler_.runCallbacks("foo");
// Update to bar type should resend Node.
expectSendMessage("bar", {}, "", true);
local_info_.context_provider_.update_cb_handler_.runCallbacks("bar");
// Adding a new foo resource to the watch shouldn't send Node.
expectSendMessage("foo", {"z", "x", "y"}, "");
auto foo_z_sub = grpc_mux_->addWatch("foo", {"z"}, callbacks_, resource_decoder_, {});
expectSendMessage("foo", {"x", "y"}, "");
expectSendMessage("foo", {}, "");
}
// Validate behavior when multiple type URL watches are maintained and the stream is reset.
TEST_F(GrpcMuxImplTest, ResetStream) {
InSequence s;
auto* timer = new Event::MockTimer(&dispatcher_);
// TTL timers.
new Event::MockTimer(&dispatcher_);
new Event::MockTimer(&dispatcher_);
new Event::MockTimer(&dispatcher_);
setup();
auto foo_sub = grpc_mux_->addWatch("foo", {"x", "y"}, callbacks_, resource_decoder_, {});
auto bar_sub = grpc_mux_->addWatch("bar", {}, callbacks_, resource_decoder_, {});
auto baz_sub = grpc_mux_->addWatch("baz", {"z"}, callbacks_, resource_decoder_, {});
EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_));
expectSendMessage("foo", {"x", "y"}, "", true);
expectSendMessage("bar", {}, "");
expectSendMessage("baz", {"z"}, "");
grpc_mux_->start();
// Send another message for foo so that the node is cleared in the cached request.
// This is to test that the node is set again in the first message below.
expectSendMessage("foo", {"z", "x", "y"}, "");
auto foo_z_sub = grpc_mux_->addWatch("foo", {"z"}, callbacks_, resource_decoder_, {});
EXPECT_CALL(callbacks_,
onConfigUpdateFailed(Envoy::Config::ConfigUpdateFailureReason::ConnectionFailure, _))
.Times(4);
EXPECT_CALL(random_, random());
EXPECT_CALL(*timer, enableTimer(_, _));
grpc_mux_->grpcStreamForTest().onRemoteClose(Grpc::Status::WellKnownGrpcStatus::Canceled, "");
EXPECT_EQ(0, control_plane_connected_state_.value());
EXPECT_EQ(0, control_plane_pending_requests_.value());
EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_));
expectSendMessage("foo", {"z", "x", "y"}, "", true);
expectSendMessage("bar", {}, "");
expectSendMessage("baz", {"z"}, "");
expectSendMessage("foo", {"x", "y"}, "");
timer->invokeCallback();
expectSendMessage("baz", {}, "");
expectSendMessage("foo", {}, "");
}
// Validate pause-resume behavior.
TEST_F(GrpcMuxImplTest, PauseResume) {
setup();
InSequence s;
GrpcMuxWatchPtr foo_sub;
GrpcMuxWatchPtr foo_z_sub;
GrpcMuxWatchPtr foo_zz_sub;
foo_sub = grpc_mux_->addWatch("foo", {"x", "y"}, callbacks_, resource_decoder_, {});
{
ScopedResume a = grpc_mux_->pause("foo");
EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_));
grpc_mux_->start();
expectSendMessage("foo", {"x", "y"}, "", true);
}
{
ScopedResume a = grpc_mux_->pause("bar");
expectSendMessage("foo", {"z", "x", "y"}, "");
foo_z_sub = grpc_mux_->addWatch("foo", {"z"}, callbacks_, resource_decoder_, {});
}
{
ScopedResume a = grpc_mux_->pause("foo");
foo_zz_sub = grpc_mux_->addWatch("foo", {"zz"}, callbacks_, resource_decoder_, {});
expectSendMessage("foo", {"zz", "z", "x", "y"}, "");
}
// When nesting, we only have a single resumption.
{
ScopedResume a = grpc_mux_->pause("foo");
ScopedResume b = grpc_mux_->pause("foo");
foo_zz_sub = grpc_mux_->addWatch("foo", {"zz"}, callbacks_, resource_decoder_, {});
expectSendMessage("foo", {"zz", "z", "x", "y"}, "");
}
grpc_mux_->pause("foo")->cancel();
}
// Validate behavior when type URL mismatches occur.
TEST_F(GrpcMuxImplTest, TypeUrlMismatch) {
setup();
auto invalid_response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>();
InSequence s;
auto foo_sub = grpc_mux_->addWatch("foo", {"x", "y"}, callbacks_, resource_decoder_, {});
EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_));
expectSendMessage("foo", {"x", "y"}, "", true);
grpc_mux_->start();
{
auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>();
response->set_type_url("bar");
response->set_version_info("bar-version");
grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response));
}
{
invalid_response->set_type_url("foo");
invalid_response->set_version_info("foo-version");
invalid_response->mutable_resources()->Add()->set_type_url("bar");
EXPECT_CALL(callbacks_, onConfigUpdateFailed(_, _))
.WillOnce(Invoke([](Envoy::Config::ConfigUpdateFailureReason, const EnvoyException* e) {
EXPECT_TRUE(IsSubstring(
"", "", "bar does not match the message-wide type URL foo in DiscoveryResponse",
e->what()));
}));
expectSendMessage(
"foo", {"x", "y"}, "", false, "", Grpc::Status::WellKnownGrpcStatus::Internal,
fmt::format("bar does not match the message-wide type URL foo in DiscoveryResponse {}",
invalid_response->DebugString()));
grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(invalid_response));
}
expectSendMessage("foo", {}, "");
}
TEST_F(GrpcMuxImplTest, RpcErrorMessageTruncated) {
setup();
auto invalid_response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>();
InSequence s;
auto foo_sub = grpc_mux_->addWatch("foo", {"x", "y"}, callbacks_, resource_decoder_, {});
EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_));
expectSendMessage("foo", {"x", "y"}, "", true);
grpc_mux_->start();
{ // Large error message sent back to management server is truncated.
const std::string very_large_type_url(1 << 20, 'A');
invalid_response->set_type_url("foo");
invalid_response->set_version_info("invalid");
invalid_response->mutable_resources()->Add()->set_type_url(very_large_type_url);
EXPECT_CALL(callbacks_, onConfigUpdateFailed(_, _))
.WillOnce(Invoke([&very_large_type_url](Envoy::Config::ConfigUpdateFailureReason,
const EnvoyException* e) {
EXPECT_TRUE(IsSubstring(
"", "",
fmt::format("{} does not match the message-wide type URL foo in DiscoveryResponse",
very_large_type_url), // Local error message is not truncated.
e->what()));
}));
expectSendMessage("foo", {"x", "y"}, "", false, "", Grpc::Status::WellKnownGrpcStatus::Internal,
fmt::format("{}...(truncated)", std::string(4096, 'A')));
grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(invalid_response));
}
expectSendMessage("foo", {}, "");
}
envoy::service::discovery::v3::Resource heartbeatResource(std::chrono::milliseconds ttl,
const std::string& name) {
envoy::service::discovery::v3::Resource resource;
resource.mutable_ttl()->CopyFrom(Protobuf::util::TimeUtil::MillisecondsToDuration(ttl.count()));
resource.set_name(name);
return resource;
}
envoy::service::discovery::v3::Resource
resourceWithTtl(std::chrono::milliseconds ttl,
envoy::config::endpoint::v3::ClusterLoadAssignment& cla) {
envoy::service::discovery::v3::Resource resource;
resource.mutable_resource()->PackFrom(cla);
resource.mutable_ttl()->CopyFrom(Protobuf::util::TimeUtil::MillisecondsToDuration(ttl.count()));
resource.set_name(cla.cluster_name());
return resource;
}
// Validates the behavior when the TTL timer expires.
TEST_F(GrpcMuxImplTest, ResourceTTL) {
setup();
time_system_.setSystemTime(std::chrono::seconds(0));
TestUtility::TestOpaqueResourceDecoderImpl<envoy::config::endpoint::v3::ClusterLoadAssignment>
resource_decoder("cluster_name");
const std::string& type_url = Config::TypeUrl::get().ClusterLoadAssignment;
InSequence s;
auto* ttl_timer = new Event::MockTimer(&dispatcher_);
auto eds_sub = grpc_mux_->addWatch(type_url, {"x"}, callbacks_, resource_decoder, {});
EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_));
expectSendMessage(type_url, {"x"}, "", true);
grpc_mux_->start();
{
auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>();
response->set_type_url(type_url);
response->set_version_info("1");
envoy::config::endpoint::v3::ClusterLoadAssignment load_assignment;
load_assignment.set_cluster_name("x");
auto wrapped_resource = resourceWithTtl(std::chrono::milliseconds(1000), load_assignment);
response->add_resources()->PackFrom(wrapped_resource);
EXPECT_CALL(callbacks_, onConfigUpdate(_, "1"))
.WillOnce(Invoke([](const std::vector<DecodedResourceRef>& resources, const std::string&) {
EXPECT_EQ(1, resources.size());
}));
EXPECT_CALL(*ttl_timer, enabled());
EXPECT_CALL(*ttl_timer, enableTimer(std::chrono::milliseconds(1000), _));
expectSendMessage(type_url, {"x"}, "1");
grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response));
}
// Increase the TTL.
{
auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>();
response->set_type_url(type_url);
response->set_version_info("1");
envoy::config::endpoint::v3::ClusterLoadAssignment load_assignment;
load_assignment.set_cluster_name("x");
auto wrapped_resource = resourceWithTtl(std::chrono::milliseconds(10000), load_assignment);
response->add_resources()->PackFrom(wrapped_resource);
EXPECT_CALL(callbacks_, onConfigUpdate(_, "1"))
.WillOnce(Invoke([](const std::vector<DecodedResourceRef>& resources, const std::string&) {
EXPECT_EQ(1, resources.size());
}));
EXPECT_CALL(*ttl_timer, enabled());
EXPECT_CALL(*ttl_timer, enableTimer(std::chrono::milliseconds(10000), _));
// No update, just a change in TTL.
expectSendMessage(type_url, {"x"}, "1");
grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response));
}
// Refresh the TTL with a heartbeat response.
{
auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>();
response->set_type_url(type_url);
response->set_version_info("1");
auto wrapped_resource = heartbeatResource(std::chrono::milliseconds(10000), "x");
response->add_resources()->PackFrom(wrapped_resource);
EXPECT_CALL(*ttl_timer, enabled());
// No update, just a change in TTL.
expectSendMessage(type_url, {"x"}, "1");
grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response));
}
// Remove the TTL.
{
auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>();
response->set_type_url(type_url);
response->set_version_info("1");
envoy::config::endpoint::v3::ClusterLoadAssignment load_assignment;
load_assignment.set_cluster_name("x");
response->add_resources()->PackFrom(load_assignment);
EXPECT_CALL(callbacks_, onConfigUpdate(_, "1"))
.WillOnce(Invoke([](const std::vector<DecodedResourceRef>& resources, const std::string&) {
EXPECT_EQ(1, resources.size());
}));
EXPECT_CALL(*ttl_timer, disableTimer());
expectSendMessage(type_url, {"x"}, "1");
grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response));
}
// Put the TTL back.
{
auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>();
response->set_type_url(type_url);
response->set_version_info("1");
envoy::config::endpoint::v3::ClusterLoadAssignment load_assignment;
load_assignment.set_cluster_name("x");
auto wrapped_resource = resourceWithTtl(std::chrono::milliseconds(10000), load_assignment);
response->add_resources()->PackFrom(wrapped_resource);
EXPECT_CALL(callbacks_, onConfigUpdate(_, "1"))
.WillOnce(Invoke([](const std::vector<DecodedResourceRef>& resources, const std::string&) {
EXPECT_EQ(1, resources.size());
}));
EXPECT_CALL(*ttl_timer, enabled());
EXPECT_CALL(*ttl_timer, enableTimer(std::chrono::milliseconds(10000), _));
// No update, just a change in TTL.
expectSendMessage(type_url, {"x"}, "1");
grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response));
}
time_system_.setSystemTime(std::chrono::seconds(11));
EXPECT_CALL(callbacks_, onConfigUpdate(_, _, ""))
.WillOnce(Invoke([](auto, const auto& removed, auto) {
EXPECT_EQ(1, removed.size());
EXPECT_EQ("x", removed.Get(0));
}));
// Fire the TTL timer.
EXPECT_CALL(*ttl_timer, disableTimer());
ttl_timer->invokeCallback();
expectSendMessage(type_url, {}, "1");
}
// Checks that the control plane identifier is logged
TEST_F(GrpcMuxImplTest, LogsControlPlaneIndentifier) {
setup();
std::string type_url = "foo";
auto foo_sub = grpc_mux_->addWatch(type_url, {}, callbacks_, resource_decoder_, {});
EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_));
expectSendMessage(type_url, {}, "", true);
grpc_mux_->start();
{
auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>();
response->set_type_url(type_url);
response->set_version_info("1");
response->mutable_control_plane()->set_identifier("control_plane_ID");
EXPECT_CALL(callbacks_, onConfigUpdate(_, _));
expectSendMessage(type_url, {}, "1");
EXPECT_LOG_CONTAINS("debug", "for foo from control_plane_ID",
grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response)));
}
{
auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>();
response->set_type_url(type_url);
response->set_version_info("2");
response->mutable_control_plane()->set_identifier("different_ID");
EXPECT_CALL(callbacks_, onConfigUpdate(_, _));
expectSendMessage(type_url, {}, "2");
EXPECT_LOG_CONTAINS("debug", "for foo from different_ID",
grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response)));
}
}
// Validate behavior when watches has an unknown resource name.
TEST_F(GrpcMuxImplTest, WildcardWatch) {
setup();
InSequence s;
const std::string& type_url = Config::TypeUrl::get().ClusterLoadAssignment;
TestUtility::TestOpaqueResourceDecoderImpl<envoy::config::endpoint::v3::ClusterLoadAssignment>
resource_decoder("cluster_name");
auto foo_sub = grpc_mux_->addWatch(type_url, {}, callbacks_, resource_decoder, {});
EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_));
expectSendMessage(type_url, {}, "", true);
grpc_mux_->start();
{
auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>();
response->set_type_url(type_url);
response->set_version_info("1");
envoy::config::endpoint::v3::ClusterLoadAssignment load_assignment;
load_assignment.set_cluster_name("x");
response->add_resources()->PackFrom(load_assignment);
EXPECT_CALL(callbacks_, onConfigUpdate(_, "1"))
.WillOnce(Invoke([&load_assignment](const std::vector<DecodedResourceRef>& resources,
const std::string&) {
EXPECT_EQ(1, resources.size());
const auto& expected_assignment =
dynamic_cast<const envoy::config::endpoint::v3::ClusterLoadAssignment&>(
resources[0].get().resource());
EXPECT_TRUE(TestUtility::protoEqual(expected_assignment, load_assignment));
}));
expectSendMessage(type_url, {}, "1");
grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response));
}
}
// Validate behavior when watches specify resources (potentially overlapping).
TEST_F(GrpcMuxImplTest, WatchDemux) {
setup();
InSequence s;
TestUtility::TestOpaqueResourceDecoderImpl<envoy::config::endpoint::v3::ClusterLoadAssignment>
resource_decoder("cluster_name");
const std::string& type_url = Config::TypeUrl::get().ClusterLoadAssignment;
NiceMock<MockSubscriptionCallbacks> foo_callbacks;
auto foo_sub = grpc_mux_->addWatch(type_url, {"x", "y"}, foo_callbacks, resource_decoder, {});
NiceMock<MockSubscriptionCallbacks> bar_callbacks;
auto bar_sub = grpc_mux_->addWatch(type_url, {"y", "z"}, bar_callbacks, resource_decoder, {});
EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_));
// Should dedupe the "x" resource.
expectSendMessage(type_url, {"y", "z", "x"}, "", true);
grpc_mux_->start();
{
auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>();
response->set_type_url(type_url);
response->set_version_info("1");
envoy::config::endpoint::v3::ClusterLoadAssignment load_assignment;
load_assignment.set_cluster_name("x");
response->add_resources()->PackFrom(load_assignment);
EXPECT_CALL(bar_callbacks, onConfigUpdate(_, "1")).Times(0);
EXPECT_CALL(foo_callbacks, onConfigUpdate(_, "1"))
.WillOnce(Invoke([&load_assignment](const std::vector<DecodedResourceRef>& resources,
const std::string&) {
EXPECT_EQ(1, resources.size());
const auto& expected_assignment =
dynamic_cast<const envoy::config::endpoint::v3::ClusterLoadAssignment&>(
resources[0].get().resource());
EXPECT_TRUE(TestUtility::protoEqual(expected_assignment, load_assignment));
}));
expectSendMessage(type_url, {"y", "z", "x"}, "1");
grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response));
}
{
auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>();
response->set_type_url(type_url);
response->set_version_info("2");
envoy::config::endpoint::v3::ClusterLoadAssignment load_assignment_x;
load_assignment_x.set_cluster_name("x");
response->add_resources()->PackFrom(load_assignment_x);
envoy::config::endpoint::v3::ClusterLoadAssignment load_assignment_y;
load_assignment_y.set_cluster_name("y");
response->add_resources()->PackFrom(load_assignment_y);
envoy::config::endpoint::v3::ClusterLoadAssignment load_assignment_z;
load_assignment_z.set_cluster_name("z");
response->add_resources()->PackFrom(load_assignment_z);
EXPECT_CALL(bar_callbacks, onConfigUpdate(_, "2"))
.WillOnce(Invoke([&load_assignment_y, &load_assignment_z](
const std::vector<DecodedResourceRef>& resources, const std::string&) {
EXPECT_EQ(2, resources.size());
const auto& expected_assignment =
dynamic_cast<const envoy::config::endpoint::v3::ClusterLoadAssignment&>(
resources[0].get().resource());
EXPECT_TRUE(TestUtility::protoEqual(expected_assignment, load_assignment_y));
const auto& expected_assignment_1 =
dynamic_cast<const envoy::config::endpoint::v3::ClusterLoadAssignment&>(
resources[1].get().resource());
EXPECT_TRUE(TestUtility::protoEqual(expected_assignment_1, load_assignment_z));
}));
EXPECT_CALL(foo_callbacks, onConfigUpdate(_, "2"))
.WillOnce(Invoke([&load_assignment_x, &load_assignment_y](
const std::vector<DecodedResourceRef>& resources, const std::string&) {
EXPECT_EQ(2, resources.size());
const auto& expected_assignment =
dynamic_cast<const envoy::config::endpoint::v3::ClusterLoadAssignment&>(
resources[0].get().resource());
EXPECT_TRUE(TestUtility::protoEqual(expected_assignment, load_assignment_x));
const auto& expected_assignment_1 =
dynamic_cast<const envoy::config::endpoint::v3::ClusterLoadAssignment&>(
resources[1].get().resource());
EXPECT_TRUE(TestUtility::protoEqual(expected_assignment_1, load_assignment_y));
}));
expectSendMessage(type_url, {"y", "z", "x"}, "2");
grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response));
}
expectSendMessage(type_url, {"x", "y"}, "2");
expectSendMessage(type_url, {}, "2");
}
// Validate behavior when we have multiple watchers that send empty updates.
TEST_F(GrpcMuxImplTest, MultipleWatcherWithEmptyUpdates) {
setup();
InSequence s;
const std::string& type_url = Config::TypeUrl::get().ClusterLoadAssignment;
NiceMock<MockSubscriptionCallbacks> foo_callbacks;
auto foo_sub = grpc_mux_->addWatch(type_url, {"x", "y"}, foo_callbacks, resource_decoder_, {});
EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_));
expectSendMessage(type_url, {"x", "y"}, "", true);
grpc_mux_->start();
auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>();
response->set_type_url(type_url);
response->set_version_info("1");
EXPECT_CALL(foo_callbacks, onConfigUpdate(_, "1")).Times(0);
expectSendMessage(type_url, {"x", "y"}, "1");
grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response));
expectSendMessage(type_url, {}, "1");
}
// Validate behavior when we have Single Watcher that sends Empty updates.
TEST_F(GrpcMuxImplTest, SingleWatcherWithEmptyUpdates) {
setup();
const std::string& type_url = Config::TypeUrl::get().Cluster;
NiceMock<MockSubscriptionCallbacks> foo_callbacks;
auto foo_sub = grpc_mux_->addWatch(type_url, {}, foo_callbacks, resource_decoder_, {});
EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_));
expectSendMessage(type_url, {}, "", true);
grpc_mux_->start();
auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>();
response->set_type_url(type_url);
response->set_version_info("1");
// Validate that onConfigUpdate is called with empty resources.
EXPECT_CALL(foo_callbacks, onConfigUpdate(_, "1"))
.WillOnce(Invoke([](const std::vector<DecodedResourceRef>& resources, const std::string&) {
EXPECT_TRUE(resources.empty());
}));
expectSendMessage(type_url, {}, "1");
grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response));
}
// Exactly one test requires a mock time system to provoke behavior that cannot
// easily be achieved with a SimulatedTimeSystem.
class GrpcMuxImplTestWithMockTimeSystem : public GrpcMuxImplTestBase {
public:
Event::DelegatingTestTimeSystem<MockTimeSystem> mock_time_system_;
};
// Verifies that rate limiting is not enforced with defaults.
TEST_F(GrpcMuxImplTestWithMockTimeSystem, TooManyRequestsWithDefaultSettings) {
auto ttl_timer = new Event::MockTimer(&dispatcher_);
// Retry timer,
new Event::MockTimer(&dispatcher_);
// Validate that rate limiter is not created.
EXPECT_CALL(*mock_time_system_, monotonicTime()).Times(0);
setup();
EXPECT_CALL(async_stream_, sendMessageRaw_(_, false)).Times(AtLeast(99));
EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_));
const auto onReceiveMessage = [&](uint64_t burst) {
for (uint64_t i = 0; i < burst; i++) {
auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>();
response->set_version_info("baz");
response->set_nonce("bar");
response->set_type_url("foo");
EXPECT_CALL(*ttl_timer, disableTimer());
grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response));
}
};
auto foo_sub = grpc_mux_->addWatch("foo", {"x"}, callbacks_, resource_decoder_, {});
expectSendMessage("foo", {"x"}, "", true);
grpc_mux_->start();
// Exhausts the limit.
onReceiveMessage(99);
// API calls go over the limit but we do not see the stat incremented.
onReceiveMessage(1);
EXPECT_EQ(0, stats_.counter("control_plane.rate_limit_enforced").value());
}
// Verifies that default rate limiting is enforced with empty RateLimitSettings.
TEST_F(GrpcMuxImplTest, TooManyRequestsWithEmptyRateLimitSettings) {
// Validate that request drain timer is created.
auto ttl_timer = new Event::MockTimer(&dispatcher_);
Event::MockTimer* drain_request_timer = new Event::MockTimer(&dispatcher_);
Event::MockTimer* retry_timer = new Event::MockTimer(&dispatcher_);
RateLimitSettings custom_rate_limit_settings;
custom_rate_limit_settings.enabled_ = true;
setup(custom_rate_limit_settings);
// Attempt to send 99 messages. One of them is rate limited (and we never drain).
EXPECT_CALL(async_stream_, sendMessageRaw_(_, false)).Times(99);
EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_));
const auto onReceiveMessage = [&](uint64_t burst) {
for (uint64_t i = 0; i < burst; i++) {
auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>();
response->set_version_info("baz");
response->set_nonce("bar");
response->set_type_url("foo");
EXPECT_CALL(*ttl_timer, disableTimer());
grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response));
}
};
auto foo_sub = grpc_mux_->addWatch("foo", {"x"}, callbacks_, resource_decoder_, {});
expectSendMessage("foo", {"x"}, "", true);
grpc_mux_->start();
// Validate that drain_request_timer is enabled when there are no tokens.
EXPECT_CALL(*drain_request_timer, enableTimer(std::chrono::milliseconds(100), _));
// The drain timer enable is checked twice, once when we limit, again when the watch is destroyed.
EXPECT_CALL(*drain_request_timer, enabled()).Times(11);
onReceiveMessage(110);
EXPECT_EQ(11, stats_.counter("control_plane.rate_limit_enforced").value());
EXPECT_EQ(11, control_plane_pending_requests_.value());
// Validate that when we reset a stream with pending requests, it reverts back to the initial
// query (i.e. the queue is discarded).
EXPECT_CALL(callbacks_,
onConfigUpdateFailed(Envoy::Config::ConfigUpdateFailureReason::ConnectionFailure, _));
EXPECT_CALL(random_, random());
EXPECT_CALL(*retry_timer, enableTimer(_, _));
grpc_mux_->grpcStreamForTest().onRemoteClose(Grpc::Status::WellKnownGrpcStatus::Canceled, "");
EXPECT_EQ(11, control_plane_pending_requests_.value());
EXPECT_EQ(0, control_plane_connected_state_.value());
EXPECT_CALL(async_stream_, sendMessageRaw_(_, false));
EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_));
time_system_.setMonotonicTime(std::chrono::seconds(30));
retry_timer->invokeCallback();
EXPECT_EQ(0, control_plane_pending_requests_.value());
// One more message on the way out when the watch is destroyed.
EXPECT_CALL(async_stream_, sendMessageRaw_(_, false));
}
// Verifies that rate limiting is enforced with custom RateLimitSettings.
TEST_F(GrpcMuxImplTest, TooManyRequestsWithCustomRateLimitSettings) {
// Validate that request drain timer is created.
// TTL timer.
auto ttl_timer = new Event::MockTimer(&dispatcher_);
Event::MockTimer* drain_request_timer = new Event::MockTimer(&dispatcher_);
// Retry timer.
new Event::MockTimer(&dispatcher_);
RateLimitSettings custom_rate_limit_settings;
custom_rate_limit_settings.enabled_ = true;
custom_rate_limit_settings.max_tokens_ = 250;
custom_rate_limit_settings.fill_rate_ = 2;
setup(custom_rate_limit_settings);
EXPECT_CALL(async_stream_, sendMessageRaw_(_, false)).Times(AtLeast(260));
EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_));
const auto onReceiveMessage = [&](uint64_t burst) {
for (uint64_t i = 0; i < burst; i++) {
auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>();
response->set_version_info("baz");
response->set_nonce("bar");
response->set_type_url("foo");
EXPECT_CALL(*ttl_timer, disableTimer());
grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response));
}
};
auto foo_sub = grpc_mux_->addWatch("foo", {"x"}, callbacks_, resource_decoder_, {});
expectSendMessage("foo", {"x"}, "", true);
grpc_mux_->start();
// Validate that rate limit is not enforced for 100 requests.
onReceiveMessage(100);
EXPECT_EQ(0, stats_.counter("control_plane.rate_limit_enforced").value());
// Validate that drain_request_timer is enabled when there are no tokens.
EXPECT_CALL(*drain_request_timer, enableTimer(std::chrono::milliseconds(500), _));
EXPECT_CALL(*drain_request_timer, enabled()).Times(11);
onReceiveMessage(160);
EXPECT_EQ(11, stats_.counter("control_plane.rate_limit_enforced").value());
EXPECT_EQ(11, control_plane_pending_requests_.value());
// Validate that drain requests call when there are multiple requests in queue.
time_system_.setMonotonicTime(std::chrono::seconds(10));
drain_request_timer->invokeCallback();
// Check that the pending_requests stat is updated with the queue drain.
EXPECT_EQ(0, control_plane_pending_requests_.value());
}
// Verifies that a message with no resources is accepted.
TEST_F(GrpcMuxImplTest, UnwatchedTypeAcceptsEmptyResources) {
setup();
EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_));
const std::string& type_url = Config::TypeUrl::get().ClusterLoadAssignment;
grpc_mux_->start();
{
// subscribe and unsubscribe to simulate a cluster added and removed
expectSendMessage(type_url, {"y"}, "", true);
auto temp_sub = grpc_mux_->addWatch(type_url, {"y"}, callbacks_, resource_decoder_, {});
expectSendMessage(type_url, {}, "");
}
// simulate the server sending empty CLA message to notify envoy that the CLA was removed.
auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>();
response->set_nonce("bar");
response->set_version_info("1");
response->set_type_url(type_url);
// TODO(fredlas) the expectation of no discovery request here is against the xDS spec.
// The upcoming xDS overhaul (part of/followup to PR7293) will fix this.
//
// This contains zero resources. No discovery request should be sent.
grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response));
// when we add the new subscription version should be 1 and nonce should be bar
expectSendMessage(type_url, {"x"}, "1", false, "bar");
// simulate a new cluster x is added. add CLA subscription for it.
auto sub = grpc_mux_->addWatch(type_url, {"x"}, callbacks_, resource_decoder_, {});
expectSendMessage(type_url, {}, "1", false, "bar");
}
// Verifies that a message with some resources is rejected when there are no watches.
TEST_F(GrpcMuxImplTest, UnwatchedTypeRejectsResources) {
setup();
EXPECT_CALL(*async_client_, startRaw(_, _, _, _)).WillOnce(Return(&async_stream_));
const std::string& type_url = Config::TypeUrl::get().ClusterLoadAssignment;
grpc_mux_->start();
// subscribe and unsubscribe (by not keeping the return watch) so that the type is known to envoy
expectSendMessage(type_url, {"y"}, "", true);
expectSendMessage(type_url, {}, "");
grpc_mux_->addWatch(type_url, {"y"}, callbacks_, resource_decoder_, {});
// simulate the server sending CLA message to notify envoy that the CLA was added,
// even though envoy doesn't expect it. Envoy should reject this update.
auto response = std::make_unique<envoy::service::discovery::v3::DiscoveryResponse>();
response->set_nonce("bar");
response->set_version_info("1");
response->set_type_url(type_url);
envoy::config::endpoint::v3::ClusterLoadAssignment load_assignment;
load_assignment.set_cluster_name("x");
response->add_resources()->PackFrom(load_assignment);
// The message should be rejected.
expectSendMessage(type_url, {}, "", false, "bar");
EXPECT_LOG_CONTAINS("warning", "Ignoring unwatched type URL " + type_url,
grpc_mux_->grpcStreamForTest().onReceiveMessage(std::move(response)));
}
TEST_F(GrpcMuxImplTest, BadLocalInfoEmptyClusterName) {
EXPECT_CALL(local_info_, clusterName()).WillOnce(ReturnRef(EMPTY_STRING));
EXPECT_THROW_WITH_MESSAGE(
GrpcMuxImpl(
local_info_, std::unique_ptr<Grpc::MockAsyncClient>(async_client_), dispatcher_,
*Protobuf::DescriptorPool::generated_pool()->FindMethodByName(
"envoy.service.discovery.v3.AggregatedDiscoveryService.StreamAggregatedResources"),
random_, stats_, rate_limit_settings_, true),
EnvoyException,
"ads: node 'id' and 'cluster' are required. Set it either in 'node' config or via "
"--service-node and --service-cluster options.");
}
TEST_F(GrpcMuxImplTest, BadLocalInfoEmptyNodeName) {
EXPECT_CALL(local_info_, nodeName()).WillOnce(ReturnRef(EMPTY_STRING));
EXPECT_THROW_WITH_MESSAGE(
GrpcMuxImpl(
local_info_, std::unique_ptr<Grpc::MockAsyncClient>(async_client_), dispatcher_,
*Protobuf::DescriptorPool::generated_pool()->FindMethodByName(
"envoy.service.discovery.v3.AggregatedDiscoveryService.StreamAggregatedResources"),
random_, stats_, rate_limit_settings_, true),
EnvoyException,
"ads: node 'id' and 'cluster' are required. Set it either in 'node' config or via "
"--service-node and --service-cluster options.");
}
} // namespace
} // namespace Config
} // namespace Envoy
|
Java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.